@enbox/agent 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -7,7 +7,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
7
7
  || ${o} === "boolean" || ${i} === null`).assign(s,(0,Kt._)`[${i}]`)}}}function Ine({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,Kt._)`${e} !== undefined`,()=>r.assign((0,Kt._)`${e}[${t}]`,n))}function lD(r,e,t,n=Py.Correct){let i=n===Py.Correct?Kt.operators.EQ:Kt.operators.NEQ,a;switch(r){case"null":return(0,Kt._)`${e} ${i} null`;case"array":a=(0,Kt._)`Array.isArray(${e})`;break;case"object":a=(0,Kt._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=o((0,Kt._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=o();break;default:return(0,Kt._)`typeof ${e} ${i} ${r}`}return n===Py.Correct?a:(0,Kt.not)(a);function o(s=Kt.nil){return(0,Kt.and)((0,Kt._)`typeof ${e} == "number"`,s,t?(0,Kt._)`isFinite(${e})`:Kt.nil)}}vs.checkDataType=lD;function uD(r,e,t,n){if(r.length===1)return lD(r[0],e,t,n);let i,a=(0,zN.toHash)(r);if(a.array&&a.object){let o=(0,Kt._)`typeof ${e} != "object"`;i=a.null?o:(0,Kt._)`!${e} || ${o}`,delete a.null,delete a.array,delete a.object}else i=Kt.nil;a.number&&delete a.integer;for(let o in a)i=(0,Kt.and)(i,lD(o,e,t,n));return i}vs.checkDataTypes=uD;var Dne={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,Kt._)`{type: ${r}}`:(0,Kt._)`{type: ${e}}`};function fD(r){let e=Rne(r);(0,Sne.reportError)(e,Dne)}vs.reportTypeError=fD;function Rne(r){let{gen:e,data:t,schema:n}=r,i=(0,zN.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var VN=Ae(Ax=>{"use strict";g();Object.defineProperty(Ax,"__esModule",{value:!0});Ax.assignDefaults=void 0;var xy=jt(),Cne=Xt();function $ne(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)HN(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,a)=>HN(r,a,i.default))}Ax.assignDefaults=$ne;function HN(r,e,t){let{gen:n,compositeRule:i,data:a,opts:o}=r;if(t===void 0)return;let s=(0,xy._)`${a}${(0,xy.getProperty)(e)}`;if(i){(0,Cne.checkStrictMode)(r,`default is ignored for: ${s}`);return}let c=(0,xy._)`${s} === undefined`;o.useDefaults==="empty"&&(c=(0,xy._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,xy._)`${s} = ${(0,xy.stringify)(t)}`)}});var Ea=Ae(Lr=>{"use strict";g();Object.defineProperty(Lr,"__esModule",{value:!0});Lr.validateUnion=Lr.validateArray=Lr.usePattern=Lr.callValidateCode=Lr.schemaProperties=Lr.allSchemaProperties=Lr.noPropertyInData=Lr.propertyInData=Lr.isOwnProperty=Lr.hasPropFunc=Lr.reportMissingProp=Lr.checkMissingProp=Lr.checkReportMissingProp=void 0;var cn=jt(),pD=Xt(),Zu=xa(),Bne=Xt();function One(r,e){let{gen:t,data:n,it:i}=r;t.if(mD(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,cn._)`${e}`},!0),r.error()})}Lr.checkReportMissingProp=One;function jne({gen:r,data:e,it:{opts:t}},n,i){return(0,cn.or)(...n.map(a=>(0,cn.and)(mD(r,e,a,t.ownProperties),(0,cn._)`${i} = ${a}`)))}Lr.checkMissingProp=jne;function Mne(r,e){r.setParams({missingProperty:e},!0),r.error()}Lr.reportMissingProp=Mne;function WN(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,cn._)`Object.prototype.hasOwnProperty`})}Lr.hasPropFunc=WN;function hD(r,e,t){return(0,cn._)`${WN(r)}.call(${e}, ${t})`}Lr.isOwnProperty=hD;function Kne(r,e,t,n){let i=(0,cn._)`${e}${(0,cn.getProperty)(t)} !== undefined`;return n?(0,cn._)`${i} && ${hD(r,e,t)}`:i}Lr.propertyInData=Kne;function mD(r,e,t,n){let i=(0,cn._)`${e}${(0,cn.getProperty)(t)} === undefined`;return n?(0,cn.or)(i,(0,cn.not)(hD(r,e,t))):i}Lr.noPropertyInData=mD;function JN(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}Lr.allSchemaProperties=JN;function Nne(r,e){return JN(e).filter(t=>!(0,pD.alwaysValidSchema)(r,e[t]))}Lr.schemaProperties=Nne;function Une({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:a},it:o},s,c,l){let d=l?(0,cn._)`${r}, ${e}, ${n}${i}`:e,u=[[Zu.default.instancePath,(0,cn.strConcat)(Zu.default.instancePath,a)],[Zu.default.parentData,o.parentData],[Zu.default.parentDataProperty,o.parentDataProperty],[Zu.default.rootData,Zu.default.rootData]];o.opts.dynamicRef&&u.push([Zu.default.dynamicAnchors,Zu.default.dynamicAnchors]);let f=(0,cn._)`${d}, ${t.object(...u)}`;return c!==cn.nil?(0,cn._)`${s}.call(${c}, ${f})`:(0,cn._)`${s}(${f})`}Lr.callValidateCode=Une;var Lne=(0,cn._)`new RegExp`;function qne({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,n);return r.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,cn._)`${i.code==="new RegExp"?Lne:(0,Bne.useFunc)(r,i)}(${t}, ${n})`})}Lr.usePattern=qne;function zne(r){let{gen:e,data:t,keyword:n,it:i}=r,a=e.name("valid");if(i.allErrors){let s=e.let("valid",!0);return o(()=>e.assign(s,!1)),s}return e.var(a,!0),o(()=>e.break()),a;function o(s){let c=e.const("len",(0,cn._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:pD.Type.Num},a),e.if((0,cn.not)(a),s)})}}Lr.validateArray=zne;function Fne(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,pD.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),s=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},s);e.assign(o,(0,cn._)`${o} || ${s}`),r.mergeValidEvaluated(d,s)||e.if((0,cn.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}Lr.validateUnion=Fne});var XN=Ae(wd=>{"use strict";g();Object.defineProperty(wd,"__esModule",{value:!0});wd.validateKeywordUsage=wd.validSchemaType=wd.funcKeywordCode=wd.macroKeywordCode=void 0;var Vs=jt(),Hp=xa(),Gne=Ea(),Hne=Wv();function Vne(r,e){let{gen:t,keyword:n,schema:i,parentSchema:a,it:o}=r,s=e.macro.call(o.self,i,a,o),c=YN(t,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let l=t.name("valid");r.subschema({schema:s,schemaPath:Vs.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}wd.macroKeywordCode=Vne;function Wne(r,e){var t;let{gen:n,keyword:i,schema:a,parentSchema:o,$data:s,it:c}=r;Zne(c,e);let l=!s&&e.compile?e.compile.call(c.self,a,o,c):e.validate,d=YN(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)m(),e.modifying&&ZN(r),y(()=>r.error());else{let v=e.async?p():h();e.modifying&&ZN(r),y(()=>Jne(r,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,Vs._)`await `),w=>n.assign(u,!1).if((0,Vs._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Vs._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,Vs._)`${d}.errors`;return n.assign(v,null),m(Vs.nil),v}function m(v=e.async?(0,Vs._)`await `:Vs.nil){let w=c.opts.passContext?Hp.default.this:Hp.default.self,x=!("compile"in e&&!s||e.schema===!1);n.assign(u,(0,Vs._)`${v}${(0,Gne.callValidateCode)(r,d,w,x)}`,e.modifying)}function y(v){var w;n.if((0,Vs.not)((w=e.valid)!==null&&w!==void 0?w:u),v)}}wd.funcKeywordCode=Wne;function ZN(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Vs._)`${n.parentData}[${n.parentDataProperty}]`))}function Jne(r,e){let{gen:t}=r;t.if((0,Vs._)`Array.isArray(${e})`,()=>{t.assign(Hp.default.vErrors,(0,Vs._)`${Hp.default.vErrors} === null ? ${e} : ${Hp.default.vErrors}.concat(${e})`).assign(Hp.default.errors,(0,Vs._)`${Hp.default.vErrors}.length`),(0,Hne.extendErrors)(r)},()=>r.error())}function Zne({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function YN(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,Vs.stringify)(t)})}function Yne(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}wd.validSchemaType=Yne;function Xne({schema:r,opts:e,self:t,errSchemaPath:n},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(s=>!Object.prototype.hasOwnProperty.call(r,s)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}wd.validateKeywordUsage=Xne});var eU=Ae(Yu=>{"use strict";g();Object.defineProperty(Yu,"__esModule",{value:!0});Yu.extendSubschemaMode=Yu.extendSubschemaData=Yu.getSubschema=void 0;var vd=jt(),QN=Xt();function Qne(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:a,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let s=r.schema[e];return t===void 0?{schema:s,schemaPath:(0,vd._)`${r.schemaPath}${(0,vd.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:s[t],schemaPath:(0,vd._)`${r.schemaPath}${(0,vd.getProperty)(e)}${(0,vd.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,QN.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||a===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Yu.getSubschema=Qne;function eie(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:a,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=e;if(t!==void 0){let{errorPath:l,dataPathArr:d,opts:u}=e,f=s.let("data",(0,vd._)`${e.data}${(0,vd.getProperty)(t)}`,!0);c(f),r.errorPath=(0,vd.str)`${l}${(0,QN.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,vd._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof vd.Name?i:s.let("data",i,!0);c(l),o!==void 0&&(r.propertyName=o)}a&&(r.dataTypes=a);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}Yu.extendSubschemaData=eie;function tie(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:a}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),a!==void 0&&(r.allErrors=a),r.jtdDiscriminator=e,r.jtdMetadata=t}Yu.extendSubschemaMode=tie});var yD=Ae((vBe,tU)=>{"use strict";g();tU.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,a;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return!1;for(i=n;i--!==0;){var o=a[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var nU=Ae((PBe,rU)=>{"use strict";g();var Xu=rU.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Tx(e,n,i,r,"",r)};Xu.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Xu.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Xu.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Xu.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Tx(r,e,t,n,i,a,o,s,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,a,o,s,c,l);for(var d in n){var u=n[d];if(Array.isArray(u)){if(d in Xu.arrayKeywords)for(var f=0;f<u.length;f++)Tx(r,e,t,u[f],i+"/"+d+"/"+f,a,i,d,n,f)}else if(d in Xu.propsKeywords){if(u&&typeof u=="object")for(var p in u)Tx(r,e,t,u[p],i+"/"+d+"/"+rie(p),a,i,d,n,p)}else(d in Xu.keywords||r.allKeys&&!(d in Xu.skipKeywords))&&Tx(r,e,t,u,i+"/"+d,a,i,d,n)}t(n,i,a,o,s,c,l)}}function rie(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zv=Ae(ho=>{"use strict";g();Object.defineProperty(ho,"__esModule",{value:!0});ho.getSchemaRefs=ho.resolveUrl=ho.normalizeId=ho._getFullPath=ho.getFullPath=ho.inlineRef=void 0;var nie=Xt(),iie=yD(),sie=nU(),oie=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function aie(r,e=!0){return typeof r=="boolean"?!0:e===!0?!gD(r):e?iU(r)<=e:!1}ho.inlineRef=aie;var cie=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gD(r){for(let e in r){if(cie.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(gD)||typeof t=="object"&&gD(t))return!0}return!1}function iU(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!oie.has(t)&&(typeof r[t]=="object"&&(0,nie.eachItem)(r[t],n=>e+=iU(n)),e===1/0))return 1/0}return e}function sU(r,e="",t){t!==!1&&(e=Ey(e));let n=r.parse(e);return oU(r,n)}ho.getFullPath=sU;function oU(r,e){return r.serialize(e).split("#")[0]+"#"}ho._getFullPath=oU;var die=/#\/?$/;function Ey(r){return r?r.replace(die,""):""}ho.normalizeId=Ey;function lie(r,e,t){return t=Ey(t),r.resolve(e,t)}ho.resolveUrl=lie;var uie=/^[a-z_][-a-z0-9._]*$/i;function fie(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Ey(r[t]||e),a={"":i},o=sU(n,i,!1),s={},c=new Set;return sie(r,{allKeys:!0},(u,f,p,h)=>{if(h===void 0)return;let m=o+f,y=a[h];typeof u[t]=="string"&&(y=v.call(this,u[t])),w.call(this,u.$anchor),w.call(this,u.$dynamicAnchor),a[f]=y;function v(x){let _=this.opts.uriResolver.resolve;if(x=Ey(y?_(y,x):x),c.has(x))throw d(x);c.add(x);let A=this.refs[x];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?l(u,A.schema,x):x!==Ey(m)&&(x[0]==="#"?(l(u,s[x],x),s[x]=u):this.refs[x]=m),x}function w(x){if(typeof x=="string"){if(!uie.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),s;function l(u,f,p){if(f!==void 0&&!iie(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}ho.getSchemaRefs=fie});var Qv=Ae(Qu=>{"use strict";g();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.getData=Qu.KeywordCxt=Qu.validateFunctionCode=void 0;var uU=UN(),aU=Jv(),vD=dD(),Ix=Jv(),pie=VN(),Xv=XN(),wD=eU(),Qe=jt(),Tt=xa(),hie=Zv(),Rl=Xt(),Yv=Wv();function mie(r){if(hU(r)&&(mU(r),pU(r))){wie(r);return}fU(r,()=>(0,uU.topBoolOrEmptySchema)(r))}Qu.validateFunctionCode=mie;function fU({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},a){i.code.es5?r.func(e,(0,Qe._)`${Tt.default.data}, ${Tt.default.valCxt}`,n.$async,()=>{r.code((0,Qe._)`"use strict"; ${cU(t,i)}`),gie(r,i),r.code(a)}):r.func(e,(0,Qe._)`${Tt.default.data}, ${yie(i)}`,n.$async,()=>r.code(cU(t,i)).code(a))}function yie(r){return(0,Qe._)`{${Tt.default.instancePath}="", ${Tt.default.parentData}, ${Tt.default.parentDataProperty}, ${Tt.default.rootData}=${Tt.default.data}${r.dynamicRef?(0,Qe._)`, ${Tt.default.dynamicAnchors}={}`:Qe.nil}}={}`}function gie(r,e){r.if(Tt.default.valCxt,()=>{r.var(Tt.default.instancePath,(0,Qe._)`${Tt.default.valCxt}.${Tt.default.instancePath}`),r.var(Tt.default.parentData,(0,Qe._)`${Tt.default.valCxt}.${Tt.default.parentData}`),r.var(Tt.default.parentDataProperty,(0,Qe._)`${Tt.default.valCxt}.${Tt.default.parentDataProperty}`),r.var(Tt.default.rootData,(0,Qe._)`${Tt.default.valCxt}.${Tt.default.rootData}`),e.dynamicRef&&r.var(Tt.default.dynamicAnchors,(0,Qe._)`${Tt.default.valCxt}.${Tt.default.dynamicAnchors}`)},()=>{r.var(Tt.default.instancePath,(0,Qe._)`""`),r.var(Tt.default.parentData,(0,Qe._)`undefined`),r.var(Tt.default.parentDataProperty,(0,Qe._)`undefined`),r.var(Tt.default.rootData,Tt.default.data),e.dynamicRef&&r.var(Tt.default.dynamicAnchors,(0,Qe._)`{}`)})}function wie(r){let{schema:e,opts:t,gen:n}=r;fU(r,()=>{t.$comment&&e.$comment&&gU(r),Eie(r),n.let(Tt.default.vErrors,null),n.let(Tt.default.errors,0),t.unevaluated&&vie(r),yU(r),_ie(r)})}function vie(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,Qe._)`${t}.evaluated`),e.if((0,Qe._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,Qe._)`${r.evaluated}.props`,(0,Qe._)`undefined`)),e.if((0,Qe._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,Qe._)`${r.evaluated}.items`,(0,Qe._)`undefined`))}function cU(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,Qe._)`/*# sourceURL=${t} */`:Qe.nil}function bie(r,e){if(hU(r)&&(mU(r),pU(r))){Pie(r,e);return}(0,uU.boolOrEmptySchema)(r,e)}function pU({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function hU(r){return typeof r.schema!="boolean"}function Pie(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&gU(r),Sie(r),kie(r);let a=n.const("_errs",Tt.default.errors);yU(r,a),n.var(e,(0,Qe._)`${a} === ${Tt.default.errors}`)}function mU(r){(0,Rl.checkUnknownRules)(r),xie(r)}function yU(r,e){if(r.opts.jtd)return dU(r,[],!1,e);let t=(0,aU.getSchemaTypes)(r.schema),n=(0,aU.coerceAndCheckDataType)(r,t);dU(r,t,!n,e)}function xie(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Rl.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function Eie(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Rl.checkStrictMode)(r,"default is ignored in the schema root")}function Sie(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,hie.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function kie(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function gU({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let a=t.$comment;if(i.$comment===!0)r.code((0,Qe._)`${Tt.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let o=(0,Qe.str)`${n}/$comment`,s=r.scopeValue("root",{ref:e.root});r.code((0,Qe._)`${Tt.default.self}.opts.$comment(${a}, ${o}, ${s}.schema)`)}}function _ie(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:a}=r;t.$async?e.if((0,Qe._)`${Tt.default.errors} === 0`,()=>e.return(Tt.default.data),()=>e.throw((0,Qe._)`new ${i}(${Tt.default.vErrors})`)):(e.assign((0,Qe._)`${n}.errors`,Tt.default.vErrors),a.unevaluated&&Aie(r),e.return((0,Qe._)`${Tt.default.errors} === 0`))}function Aie({gen:r,evaluated:e,props:t,items:n}){t instanceof Qe.Name&&r.assign((0,Qe._)`${e}.props`,t),n instanceof Qe.Name&&r.assign((0,Qe._)`${e}.items`,n)}function dU(r,e,t,n){let{gen:i,schema:a,data:o,allErrors:s,opts:c,self:l}=r,{RULES:d}=l;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,Rl.schemaHasRulesButRef)(a,d))){i.block(()=>vU(r,"$ref",d.all.$ref.definition));return}c.jtd||Tie(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,vD.shouldUseGroup)(a,f)&&(f.type?(i.if((0,Ix.checkDataType)(f.type,o,c.strictNumbers)),lU(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ix.reportTypeError)(r)),i.endIf()):lU(r,f),s||i.if((0,Qe._)`${Tt.default.errors} === ${n||0}`))}}function lU(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,pie.assignDefaults)(r,e.type),t.block(()=>{for(let a of e.rules)(0,vD.shouldUseRule)(n,a)&&vU(r,a.keyword,a.definition,e.type)})}function Tie(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(Iie(r,e),r.opts.allowUnionTypes||Die(r,e),Rie(r,r.dataTypes))}function Iie(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{wU(r.dataTypes,t)||bD(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),$ie(r,e)}}function Die(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&bD(r,"use allowUnionTypes to allow union type keyword")}function Rie(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,vD.shouldUseRule)(r.schema,i)){let{type:a}=i.definition;a.length&&!a.some(o=>Cie(e,o))&&bD(r,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function Cie(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function wU(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function $ie(r,e){let t=[];for(let n of r.dataTypes)wU(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function bD(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Rl.checkStrictMode)(r,e,r.opts.strictTypes)}var Dx=class{constructor(e,t,n){if((0,Xv.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Rl.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",bU(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xv.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Tt.default.errors))}result(e,t,n){this.failResult((0,Qe.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,Qe.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,Qe._)`${t} !== undefined && (${(0,Qe.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Yv.reportExtraError:Yv.reportError)(this,this.def.error,t)}$dataError(){(0,Yv.reportError)(this,this.def.$dataError||Yv.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Yv.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=Qe.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=Qe.nil,t=Qe.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:a,def:o}=this;n.if((0,Qe.or)((0,Qe._)`${i} === undefined`,t)),e!==Qe.nil&&n.assign(e,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Qe.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:a}=this;return(0,Qe.or)(o(),s());function o(){if(n.length){if(!(t instanceof Qe.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Qe._)`${(0,Ix.checkDataTypes)(c,t,a.opts.strictNumbers,Ix.DataType.Wrong)}`}return Qe.nil}function s(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,Qe._)`!${c}(${t})`}return Qe.nil}}subschema(e,t){let n=(0,wD.getSubschema)(this.it,e);(0,wD.extendSubschemaData)(n,this.it,e),(0,wD.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return bie(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Rl.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Rl.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,Qe.Name)),!0}};Qu.KeywordCxt=Dx;function vU(r,e,t,n){let i=new Dx(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Xv.funcKeywordCode)(i,t):"macro"in t?(0,Xv.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Xv.funcKeywordCode)(i,t)}var Bie=/^\/(?:[^~]|~0|~1)*$/,Oie=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function bU(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,a;if(r==="")return Tt.default.rootData;if(r[0]==="/"){if(!Bie.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,a=Tt.default.rootData}else{let l=Oie.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(a=t[e-d],!i)return a}let o=a,s=i.split("/");for(let l of s)l&&(a=(0,Qe._)`${a}${(0,Qe.getProperty)((0,Rl.unescapeJsonPointer)(l))}`,o=(0,Qe._)`${o} && ${a}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Qu.getData=bU});var Rx=Ae(xD=>{"use strict";g();Object.defineProperty(xD,"__esModule",{value:!0});var PD=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xD.default=PD});var e0=Ae(kD=>{"use strict";g();Object.defineProperty(kD,"__esModule",{value:!0});var ED=Zv(),SD=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,ED.resolveUrl)(e,t,n),this.missingSchema=(0,ED.normalizeId)((0,ED.getFullPath)(e,this.missingRef))}};kD.default=SD});var t0=Ae(Sa=>{"use strict";g();Object.defineProperty(Sa,"__esModule",{value:!0});Sa.resolveSchema=Sa.getCompilingSchema=Sa.resolveRef=Sa.compileSchema=Sa.SchemaEnv=void 0;var Ec=jt(),jie=Rx(),Vp=xa(),Sc=Zv(),PU=Xt(),Mie=Qv(),Sy=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Sc.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Sa.SchemaEnv=Sy;function AD(r){let e=xU.call(this,r);if(e)return e;let t=(0,Sc.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:a}=this.opts,o=new Ec.CodeGen(this.scope,{es5:n,lines:i,ownProperties:a}),s;r.$async&&(s=o.scopeValue("Error",{ref:jie.default,code:(0,Ec._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:Vp.default.data,parentData:Vp.default.parentData,parentDataProperty:Vp.default.parentDataProperty,dataNames:[Vp.default.data],dataPathArr:[Ec.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Ec.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:s,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Ec.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ec._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,Mie.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(Vp.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${Vp.default.self}`,`${Vp.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof Ec.Name?void 0:h,items:m instanceof Ec.Name?void 0:m,dynamicProps:h instanceof Ec.Name,dynamicItems:m instanceof Ec.Name},p.source&&(p.source.evaluated=(0,Ec.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}Sa.compileSchema=AD;function Kie(r,e,t){var n;t=(0,Sc.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let a=Lie.call(this,r,t);if(a===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:s}=this.opts;o&&(a=new Sy({schema:o,schemaId:s,root:r,baseId:e}))}if(a!==void 0)return r.refs[t]=Nie.call(this,a)}Sa.resolveRef=Kie;function Nie(r){return(0,Sc.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:AD.call(this,r)}function xU(r){for(let e of this._compilations)if(Uie(e,r))return e}Sa.getCompilingSchema=xU;function Uie(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Lie(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Cx.call(this,r,e)}function Cx(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Sc._getFullPath)(this.opts.uriResolver,t),i=(0,Sc.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return _D.call(this,t,r);let a=(0,Sc.normalizeId)(n),o=this.refs[a]||this.schemas[a];if(typeof o=="string"){let s=Cx.call(this,r,o);return typeof s?.schema!="object"?void 0:_D.call(this,t,s)}if(typeof o?.schema=="object"){if(o.validate||AD.call(this,o),a===(0,Sc.normalizeId)(e)){let{schema:s}=o,{schemaId:c}=this.opts,l=s[c];return l&&(i=(0,Sc.resolveUrl)(this.opts.uriResolver,i,l)),new Sy({schema:s,schemaId:c,root:r,baseId:i})}return _D.call(this,t,o)}}Sa.resolveSchema=Cx;var qie=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _D(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,PU.unescapeFragment)(s)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!qie.has(s)&&l&&(e=(0,Sc.resolveUrl)(this.opts.uriResolver,e,l))}let a;if(typeof t!="boolean"&&t.$ref&&!(0,PU.schemaHasRulesButRef)(t,this.RULES)){let s=(0,Sc.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=Cx.call(this,n,s)}let{schemaId:o}=this.opts;if(a=a||new Sy({schema:t,schemaId:o,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var EU=Ae(($Be,zie)=>{zie.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ID=Ae((BBe,AU)=>{"use strict";g();var Fie=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kU=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function TD(r){let e="",t=0,n=0;for(n=0;n<r.length;n++)if(t=r[n].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n<r.length;n++){if(t=r[n].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var Gie=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function SU(r){return r.length=0,!0}function Hie(r,e,t){if(r.length){let n=TD(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function Vie(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],a=!1,o=!1,s=Hie;for(let c=0;c<r.length;c++){let l=r[c];if(!(l==="["||l==="]"))if(l===":"){if(a===!0&&(o=!0),!s(i,n,t))break;if(++e>7){t.error=!0;break}c>0&&r[c-1]===":"&&(a=!0),n.push(":");continue}else if(l==="%"){if(!s(i,n,t))break;s=SU}else{i.push(l);continue}}return i.length&&(s===SU?t.zone=i.join(""):o?n.push(i.join("")):n.push(TD(i))),t.address=n.join(""),t}function _U(r){if(Wie(r,":")<2)return{host:r,isIPV6:!1};let e=Vie(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function Wie(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}function Jie(r){let e=r,t=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else{t.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),t.length!==0&&t.pop();continue}}if((n=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,n)),e=e.slice(n)}return t.join("")}function Zie(r,e){let t=e!==!0?escape:unescape;return r.scheme!==void 0&&(r.scheme=t(r.scheme)),r.userinfo!==void 0&&(r.userinfo=t(r.userinfo)),r.host!==void 0&&(r.host=t(r.host)),r.path!==void 0&&(r.path=t(r.path)),r.query!==void 0&&(r.query=t(r.query)),r.fragment!==void 0&&(r.fragment=t(r.fragment)),r}function Yie(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host);if(!kU(t)){let n=_U(t);n.isIPV6===!0?t=`[${n.escapedHost}]`:t=r.host}e.push(t)}return(typeof r.port=="number"||typeof r.port=="string")&&(e.push(":"),e.push(String(r.port))),e.length?e.join(""):void 0}AU.exports={nonSimpleDomain:Gie,recomposeAuthority:Yie,normalizeComponentEncoding:Zie,removeDotSegments:Jie,isIPv4:kU,isUUID:Fie,normalizeIPv6:_U,stringArrayToHexStripped:TD}});var CU=Ae((jBe,RU)=>{"use strict";g();var{isUUID:Xie}=ID(),Qie=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ese=["http","https","ws","wss","urn","urn:uuid"];function tse(r){return ese.indexOf(r)!==-1}function DD(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function TU(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function IU(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function rse(r){return r.secure=DD(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function nse(r){if((r.port===(DD(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function ise(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Qie);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,a=RD(i);r.path=void 0,a&&(r=a.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function sse(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,a=RD(i);a&&(r=a.serialize(r,e));let o=r,s=r.nss;return o.path=`${n||e.nid}:${s}`,e.skipEscape=!0,o}function ose(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Xie(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function ase(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var DU={scheme:"http",domainHost:!0,parse:TU,serialize:IU},cse={scheme:"https",domainHost:DU.domainHost,parse:TU,serialize:IU},$x={scheme:"ws",domainHost:!0,parse:rse,serialize:nse},dse={scheme:"wss",domainHost:$x.domainHost,parse:$x.parse,serialize:$x.serialize},lse={scheme:"urn",parse:ise,serialize:sse,skipNormalize:!0},use={scheme:"urn:uuid",parse:ose,serialize:ase,skipNormalize:!0},Bx={http:DU,https:cse,ws:$x,wss:dse,urn:lse,"urn:uuid":use};Object.setPrototypeOf(Bx,null);function RD(r){return r&&(Bx[r]||Bx[r.toLowerCase()])||void 0}RU.exports={wsIsSecure:DD,SCHEMES:Bx,isValidSchemeName:tse,getSchemeHandler:RD}});var OU=Ae((KBe,jx)=>{"use strict";g();var{normalizeIPv6:fse,removeDotSegments:r0,recomposeAuthority:pse,normalizeComponentEncoding:Ox,isIPv4:hse,nonSimpleDomain:mse}=ID(),{SCHEMES:yse,getSchemeHandler:$U}=CU();function gse(r,e){return typeof r=="string"?r=bd(Cl(r,e),e):typeof r=="object"&&(r=Cl(bd(r,e),e)),r}function wse(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},i=BU(Cl(r,n),Cl(e,n),n,!0);return n.skipEscape=!0,bd(i,n)}function BU(r,e,t,n){let i={};return n||(r=Cl(bd(r,t),t),e=Cl(bd(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=r0(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=r0(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=r0(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=r0(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function vse(r,e,t){return typeof r=="string"?(r=unescape(r),r=bd(Ox(Cl(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=bd(Ox(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=bd(Ox(Cl(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=bd(Ox(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function bd(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[],a=$U(n.scheme||t.scheme);a&&a.serialize&&a.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=pse(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let s=t.path;!n.absolutePath&&(!a||!a.absolutePath)&&(s=r0(s)),o===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),i.push(s)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var bse=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Cl(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let a=r.match(bse);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host)if(hse(n.host)===!1){let c=fse(n.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let o=$U(t.scheme||n.scheme);if(!t.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(t.domainHost||o&&o.domainHost)&&i===!1&&mse(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(s){n.error=n.error||"Host's domain name can not be converted to ASCII: "+s}(!o||o&&!o.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),o&&o.parse&&o.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var CD={SCHEMES:yse,normalize:gse,resolve:wse,resolveComponent:BU,equal:vse,serialize:bd,parse:Cl};jx.exports=CD;jx.exports.default=CD;jx.exports.fastUri=CD});var MU=Ae($D=>{"use strict";g();Object.defineProperty($D,"__esModule",{value:!0});var jU=OU();jU.code='require("ajv/dist/runtime/uri").default';$D.default=jU});var GU=Ae(Yi=>{"use strict";g();Object.defineProperty(Yi,"__esModule",{value:!0});Yi.CodeGen=Yi.Name=Yi.nil=Yi.stringify=Yi.str=Yi._=Yi.KeywordCxt=void 0;var Pse=Qv();Object.defineProperty(Yi,"KeywordCxt",{enumerable:!0,get:function(){return Pse.KeywordCxt}});var ky=jt();Object.defineProperty(Yi,"_",{enumerable:!0,get:function(){return ky._}});Object.defineProperty(Yi,"str",{enumerable:!0,get:function(){return ky.str}});Object.defineProperty(Yi,"stringify",{enumerable:!0,get:function(){return ky.stringify}});Object.defineProperty(Yi,"nil",{enumerable:!0,get:function(){return ky.nil}});Object.defineProperty(Yi,"Name",{enumerable:!0,get:function(){return ky.Name}});Object.defineProperty(Yi,"CodeGen",{enumerable:!0,get:function(){return ky.CodeGen}});var xse=Rx(),qU=e0(),Ese=cD(),n0=t0(),Sse=jt(),i0=Zv(),Mx=Jv(),OD=Xt(),KU=EU(),kse=MU(),zU=(r,e)=>new RegExp(r,e);zU.code="new RegExp";var _se=["removeAdditional","useDefaults","coerceTypes"],Ase=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Tse={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Ise={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},NU=200;function Dse(r){var e,t,n,i,a,o,s,c,l,d,u,f,p,h,m,y,v,w,x,_,A,D,N,$,z;let L=r.strict,j=(e=r.code)===null||e===void 0?void 0:e.optimize,H=j===!0||j===void 0?1:j||0,Y=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zU,R=(i=r.uriResolver)!==null&&i!==void 0?i:kse.default;return{strictSchema:(o=(a=r.strictSchema)!==null&&a!==void 0?a:L)!==null&&o!==void 0?o:!0,strictNumbers:(c=(s=r.strictNumbers)!==null&&s!==void 0?s:L)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:L)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:L)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:L)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:H,regExp:Y}:{optimize:H,regExp:Y},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:NU,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:NU,meta:(v=r.meta)!==null&&v!==void 0?v:!0,messages:(w=r.messages)!==null&&w!==void 0?w:!0,inlineRefs:(x=r.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(_=r.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(A=r.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(D=r.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(N=r.validateFormats)!==null&&N!==void 0?N:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(z=r.int32range)!==null&&z!==void 0?z:!0,uriResolver:R}}var s0=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Dse(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new Sse.ValueScope({scope:{},prefixes:Ase,es5:t,lines:n}),this.logger=jse(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ese.getRules)(),UU.call(this,Tse,e,"NOT SUPPORTED"),UU.call(this,Ise,e,"DEPRECATED","warn"),this._metaOpts=Bse.call(this),e.formats&&Cse.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$se.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Rse.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=KU;n==="id"&&(i={...KU},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(d,u){await a.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function a(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof qU.default))throw u;return s.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function s({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await a.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);return this}let a;if(typeof e=="object"){let{schemaId:o}=this.opts;if(a=e[o],a!==void 0&&typeof a!="string")throw new Error(`schema ${o} must be string`)}return t=(0,i0.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=LU.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new n0.SchemaEnv({schema:{},schemaId:n});if(t=n0.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=LU.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,i0.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Kse.call(this,n,t),!t)return(0,OD.eachItem)(n,a=>BD.call(this,a)),this;Use.call(this,t);let i={...t,type:(0,Mx.getJSONTypes)(t.type),schemaType:(0,Mx.getJSONTypes)(t.schemaType)};return(0,OD.eachItem)(n,i.type.length===0?a=>BD.call(this,a,i):a=>i.type.forEach(o=>BD.call(this,a,i,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(a=>a.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),o=e;for(let s of a)o=o[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:l}=c.definition,d=o[s];l&&d&&(o[s]=FU(d))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof e=="object")o=e[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,i0.normalizeId)(o||n);let l=i0.getSchemaRefs.call(this,e,n);return c=new n0.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):n0.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{n0.compileSchema.call(this,e)}finally{this.opts=t}}};s0.ValidationError=xse.default;s0.MissingRefError=qU.default;Yi.default=s0;function UU(r,e,t,n="error"){for(let i in r){let a=i;a in e&&this.logger[n](`${t}: option ${i}. ${r[a]}`)}}function LU(r){return r=(0,i0.normalizeId)(r),this.schemas[r]||this.refs[r]}function Rse(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function Cse(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function $se(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function Bse(){let r={...this.opts};for(let e of _se)delete r[e];return r}var Ose={log(){},warn(){},error(){}};function jse(r){if(r===!1)return Ose;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var Mse=/^[a-z_$][a-z0-9_$:-]*$/i;function Kse(r,e){let{RULES:t}=this;if((0,OD.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Mse.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function BD(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=i?a.post:a.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},a.rules.push(o)),a.keywords[r]=!0,!e)return;let s={keyword:r,definition:{...e,type:(0,Mx.getJSONTypes)(e.type),schemaType:(0,Mx.getJSONTypes)(e.schemaType)}};e.before?Nse.call(this,o,s,e.before):o.rules.push(s),a.all[r]=s,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Nse(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function Use(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=FU(e)),r.validateSchema=this.compile(e,!0))}var Lse={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function FU(r){return{anyOf:[r,Lse]}}});var HU=Ae(jD=>{"use strict";g();Object.defineProperty(jD,"__esModule",{value:!0});var qse={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jD.default=qse});var Ux=Ae(Wp=>{"use strict";g();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.callRef=Wp.getValidate=void 0;var zse=e0(),VU=Ea(),mo=jt(),_y=xa(),WU=t0(),Kx=Xt(),Fse={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:a,validateName:o,opts:s,self:c}=n,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return u();let d=WU.resolveRef.call(c,l,i,t);if(d===void 0)throw new zse.default(n.opts.uriResolver,i,t);if(d instanceof WU.SchemaEnv)return f(d);return p(d);function u(){if(a===l)return Nx(r,o,a,a.$async);let h=e.scopeValue("root",{ref:l});return Nx(r,(0,mo._)`${h}.validate`,l,l.$async)}function f(h){let m=JU(r,h);Nx(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",s.code.source===!0?{ref:h,code:(0,mo.stringify)(h)}:{ref:h}),y=e.name("valid"),v=r.subschema({schema:h,dataTypes:[],schemaPath:mo.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(v),r.ok(y)}}};function JU(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,mo._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Wp.getValidate=JU;function Nx(r,e,t,n){let{gen:i,it:a}=r,{allErrors:o,schemaEnv:s,opts:c}=a,l=c.passContext?_y.default.this:mo.nil;n?d():u();function d(){if(!s.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,mo._)`await ${(0,VU.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,mo._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function u(){r.result((0,VU.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,mo._)`${h}.errors`;i.assign(_y.default.vErrors,(0,mo._)`${_y.default.vErrors} === null ? ${m} : ${_y.default.vErrors}.concat(${m})`),i.assign(_y.default.errors,(0,mo._)`${_y.default.vErrors}.length`)}function p(h){var m;if(!a.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=Kx.mergeEvaluated.props(i,y.props,a.props));else{let v=i.var("props",(0,mo._)`${h}.evaluated.props`);a.props=Kx.mergeEvaluated.props(i,v,a.props,mo.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=Kx.mergeEvaluated.items(i,y.items,a.items));else{let v=i.var("items",(0,mo._)`${h}.evaluated.items`);a.items=Kx.mergeEvaluated.items(i,v,a.items,mo.Name)}}}Wp.callRef=Nx;Wp.default=Fse});var ZU=Ae(MD=>{"use strict";g();Object.defineProperty(MD,"__esModule",{value:!0});var Gse=HU(),Hse=Ux(),Vse=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Gse.default,Hse.default];MD.default=Vse});var YU=Ae(KD=>{"use strict";g();Object.defineProperty(KD,"__esModule",{value:!0});var Lx=jt(),ef=Lx.operators,qx={maximum:{okStr:"<=",ok:ef.LTE,fail:ef.GT},minimum:{okStr:">=",ok:ef.GTE,fail:ef.LT},exclusiveMaximum:{okStr:"<",ok:ef.LT,fail:ef.GTE},exclusiveMinimum:{okStr:">",ok:ef.GT,fail:ef.LTE}},Wse={message:({keyword:r,schemaCode:e})=>(0,Lx.str)`must be ${qx[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Lx._)`{comparison: ${qx[r].okStr}, limit: ${e}}`},Jse={keyword:Object.keys(qx),type:"number",schemaType:"number",$data:!0,error:Wse,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Lx._)`${t} ${qx[e].fail} ${n} || isNaN(${t})`)}};KD.default=Jse});var XU=Ae(ND=>{"use strict";g();Object.defineProperty(ND,"__esModule",{value:!0});var o0=jt(),Zse={message:({schemaCode:r})=>(0,o0.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,o0._)`{multipleOf: ${r}}`},Yse={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Zse,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,a=i.opts.multipleOfPrecision,o=e.let("res"),s=a?(0,o0._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,o0._)`${o} !== parseInt(${o})`;r.fail$data((0,o0._)`(${n} === 0 || (${o} = ${t}/${n}, ${s}))`)}};ND.default=Yse});var QU=Ae(UD=>{"use strict";g();Object.defineProperty(UD,"__esModule",{value:!0});var Jp=jt(),Xse=Xt(),Qse=Uk(),eoe={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,Jp.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,Jp._)`{limit: ${r}}`},toe={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eoe,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,a=e==="maxLength"?Jp.operators.GT:Jp.operators.LT,o=i.opts.unicode===!1?(0,Jp._)`${t}.length`:(0,Jp._)`${(0,Xse.useFunc)(r.gen,Qse.default)}(${t})`;r.fail$data((0,Jp._)`${o} ${a} ${n}`)}};UD.default=toe});var eL=Ae(LD=>{"use strict";g();Object.defineProperty(LD,"__esModule",{value:!0});var roe=Ea(),noe=Xt(),Ay=jt(),ioe={message:({schemaCode:r})=>(0,Ay.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Ay._)`{pattern: ${r}}`},soe={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ioe,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:a,it:o}=r,s=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Ay._)`new RegExp`:(0,noe.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Ay._)`${l}(${a}, ${s}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Ay._)`!${d}`)}else{let c=(0,roe.usePattern)(r,i);r.fail$data((0,Ay._)`!${c}.test(${t})`)}}};LD.default=soe});var tL=Ae(qD=>{"use strict";g();Object.defineProperty(qD,"__esModule",{value:!0});var a0=jt(),ooe={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,a0.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,a0._)`{limit: ${r}}`},aoe={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ooe,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?a0.operators.GT:a0.operators.LT;r.fail$data((0,a0._)`Object.keys(${t}).length ${i} ${n}`)}};qD.default=aoe});var rL=Ae(zD=>{"use strict";g();Object.defineProperty(zD,"__esModule",{value:!0});var c0=Ea(),d0=jt(),coe=Xt(),doe={message:({params:{missingProperty:r}})=>(0,d0.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,d0._)`{missingProperty: ${r}}`},loe={keyword:"required",type:"object",schemaType:"array",$data:!0,error:doe,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:a,it:o}=r,{opts:s}=o;if(!a&&t.length===0)return;let c=t.length>=s.loopRequired;if(o.allErrors?l():d(),s.strictRequired){let p=r.parentSchema.properties,{definedProperties:h}=r.it;for(let m of t)if(p?.[m]===void 0&&!h.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,coe.checkStrictMode)(o,v,o.opts.strictRequired)}}function l(){if(c||a)r.block$data(d0.nil,u);else for(let p of t)(0,c0.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||a){let h=e.let("valid",!0);r.block$data(h,()=>f(p,h)),r.ok(h)}else e.if((0,c0.checkMissingProp)(r,t,p)),(0,c0.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,c0.noPropertyInData)(e,i,p,s.ownProperties),()=>r.error())})}function f(p,h){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,c0.propertyInData)(e,i,p,s.ownProperties)),e.if((0,d0.not)(h),()=>{r.error(),e.break()})},d0.nil)}}};zD.default=loe});var nL=Ae(FD=>{"use strict";g();Object.defineProperty(FD,"__esModule",{value:!0});var l0=jt(),uoe={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,l0.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,l0._)`{limit: ${r}}`},foe={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uoe,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?l0.operators.GT:l0.operators.LT;r.fail$data((0,l0._)`${t}.length ${i} ${n}`)}};FD.default=foe});var zx=Ae(GD=>{"use strict";g();Object.defineProperty(GD,"__esModule",{value:!0});var iL=yD();iL.code='require("ajv/dist/runtime/equal").default';GD.default=iL});var sL=Ae(VD=>{"use strict";g();Object.defineProperty(VD,"__esModule",{value:!0});var HD=Jv(),Xi=jt(),poe=Xt(),hoe=zx(),moe={message:({params:{i:r,j:e}})=>(0,Xi.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Xi._)`{i: ${r}, j: ${e}}`},yoe={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:moe,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:a,schemaCode:o,it:s}=r;if(!n&&!i)return;let c=e.let("valid"),l=a.items?(0,HD.getSchemaTypes)(a.items):[];r.block$data(c,d,(0,Xi._)`${o} === false`),r.ok(c);function d(){let h=e.let("i",(0,Xi._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Xi._)`${h} > 1`,()=>(u()?f:p)(h,m))}function u(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),v=(0,HD.checkDataTypes)(l,y,s.opts.strictNumbers,HD.DataType.Wrong),w=e.const("indices",(0,Xi._)`{}`);e.for((0,Xi._)`;${h}--;`,()=>{e.let(y,(0,Xi._)`${t}[${h}]`),e.if(v,(0,Xi._)`continue`),l.length>1&&e.if((0,Xi._)`typeof ${y} == "string"`,(0,Xi._)`${y} += "_"`),e.if((0,Xi._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Xi._)`${w}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Xi._)`${w}[${y}] = ${h}`)})}function p(h,m){let y=(0,poe.useFunc)(e,hoe.default),v=e.name("outer");e.label(v).for((0,Xi._)`;${h}--;`,()=>e.for((0,Xi._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Xi._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(v)})))}}};VD.default=yoe});var oL=Ae(JD=>{"use strict";g();Object.defineProperty(JD,"__esModule",{value:!0});var WD=jt(),goe=Xt(),woe=zx(),voe={message:"must be equal to constant",params:({schemaCode:r})=>(0,WD._)`{allowedValue: ${r}}`},boe={keyword:"const",$data:!0,error:voe,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:a}=r;n||a&&typeof a=="object"?r.fail$data((0,WD._)`!${(0,goe.useFunc)(e,woe.default)}(${t}, ${i})`):r.fail((0,WD._)`${a} !== ${t}`)}};JD.default=boe});var aL=Ae(ZD=>{"use strict";g();Object.defineProperty(ZD,"__esModule",{value:!0});var u0=jt(),Poe=Xt(),xoe=zx(),Eoe={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,u0._)`{allowedValues: ${r}}`},Soe={keyword:"enum",schemaType:"array",$data:!0,error:Eoe,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:a,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,Poe.useFunc)(e,xoe.default)),d;if(s||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",a);d=(0,u0.or)(...i.map((h,m)=>f(p,m)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",a,p=>e.if((0,u0._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,u0._)`${l()}(${t}, ${p}[${h}])`:(0,u0._)`${t} === ${m}`}}};ZD.default=Soe});var cL=Ae(YD=>{"use strict";g();Object.defineProperty(YD,"__esModule",{value:!0});var koe=YU(),_oe=XU(),Aoe=QU(),Toe=eL(),Ioe=tL(),Doe=rL(),Roe=nL(),Coe=sL(),$oe=oL(),Boe=aL(),Ooe=[koe.default,_oe.default,Aoe.default,Toe.default,Ioe.default,Doe.default,Roe.default,Coe.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},$oe.default,Boe.default];YD.default=Ooe});var QD=Ae(f0=>{"use strict";g();Object.defineProperty(f0,"__esModule",{value:!0});f0.validateAdditionalItems=void 0;var Zp=jt(),XD=Xt(),joe={message:({params:{len:r}})=>(0,Zp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Zp._)`{limit: ${r}}`},Moe={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:joe,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,XD.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}dL(r,n)}};function dL(r,e){let{gen:t,schema:n,data:i,keyword:a,it:o}=r;o.items=!0;let s=t.const("len",(0,Zp._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Zp._)`${s} <= ${e.length}`);else if(typeof n=="object"&&!(0,XD.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Zp._)`${s} <= ${e.length}`);t.if((0,Zp.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,s,d=>{r.subschema({keyword:a,dataProp:d,dataPropType:XD.Type.Num},l),o.allErrors||t.if((0,Zp.not)(l),()=>t.break())})}}f0.validateAdditionalItems=dL;f0.default=Moe});var eR=Ae(p0=>{"use strict";g();Object.defineProperty(p0,"__esModule",{value:!0});p0.validateTuple=void 0;var lL=jt(),Fx=Xt(),Koe=Ea(),Noe={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return uL(r,"additionalItems",e);t.items=!0,!(0,Fx.alwaysValidSchema)(t,e)&&r.ok((0,Koe.validateArray)(r))}};function uL(r,e,t=r.schema){let{gen:n,parentSchema:i,data:a,keyword:o,it:s}=r;d(i),s.opts.unevaluated&&t.length&&s.items!==!0&&(s.items=Fx.mergeEvaluated.items(n,t.length,s.items));let c=n.name("valid"),l=n.const("len",(0,lL._)`${a}.length`);t.forEach((u,f)=>{(0,Fx.alwaysValidSchema)(s,u)||(n.if((0,lL._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=s,h=t.length,m=h===u.minItems&&(h===u.maxItems||u[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Fx.checkStrictMode)(s,y,f.strictTuples)}}}p0.validateTuple=uL;p0.default=Noe});var fL=Ae(tR=>{"use strict";g();Object.defineProperty(tR,"__esModule",{value:!0});var Uoe=eR(),Loe={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,Uoe.validateTuple)(r,"items")};tR.default=Loe});var hL=Ae(rR=>{"use strict";g();Object.defineProperty(rR,"__esModule",{value:!0});var pL=jt(),qoe=Xt(),zoe=Ea(),Foe=QD(),Goe={message:({params:{len:r}})=>(0,pL.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,pL._)`{limit: ${r}}`},Hoe={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Goe,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,qoe.alwaysValidSchema)(n,e)&&(i?(0,Foe.validateAdditionalItems)(r,i):r.ok((0,zoe.validateArray)(r)))}};rR.default=Hoe});var mL=Ae(nR=>{"use strict";g();Object.defineProperty(nR,"__esModule",{value:!0});var ka=jt(),Gx=Xt(),Voe={message:({params:{min:r,max:e}})=>e===void 0?(0,ka.str)`must contain at least ${r} valid item(s)`:(0,ka.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,ka._)`{minContains: ${r}}`:(0,ka._)`{minContains: ${r}, maxContains: ${e}}`},Woe={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Voe,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r,o,s,{minContains:c,maxContains:l}=n;a.opts.next?(o=c===void 0?1:c,s=l):o=1;let d=e.const("len",(0,ka._)`${i}.length`);if(r.setParams({min:o,max:s}),s===void 0&&o===0){(0,Gx.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Gx.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Gx.alwaysValidSchema)(a,t)){let m=(0,ka._)`${d} >= ${o}`;s!==void 0&&(m=(0,ka._)`${m} && ${d} <= ${s}`),r.pass(m);return}a.items=!0;let u=e.name("valid");s===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),s!==void 0&&e.if((0,ka._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,v=>{r.subschema({keyword:"contains",dataProp:v,dataPropType:Gx.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,ka._)`${m}++`),s===void 0?e.if((0,ka._)`${m} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,ka._)`${m} > ${s}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,ka._)`${m} >= ${o}`,()=>e.assign(u,!0)))}}};nR.default=Woe});var Hx=Ae(Pd=>{"use strict";g();Object.defineProperty(Pd,"__esModule",{value:!0});Pd.validateSchemaDeps=Pd.validatePropertyDeps=Pd.error=void 0;var iR=jt(),Joe=Xt(),h0=Ea();Pd.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,iR.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,iR._)`{property: ${r},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${e},
10
- deps: ${t}}`};var Zoe={keyword:"dependencies",type:"object",schemaType:"object",error:Pd.error,code(r){let[e,t]=Yoe(r);yL(r,e),gL(r,t)}};function Yoe({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function yL(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let o in e){let s=e[o];if(s.length===0)continue;let c=(0,h0.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of s)(0,h0.checkReportMissingProp)(r,l)}):(t.if((0,iR._)`${c} && (${(0,h0.checkMissingProp)(r,s,a)})`),(0,h0.reportMissingProp)(r,a),t.else())}}Pd.validatePropertyDeps=yL;function gL(r,e=r.schema){let{gen:t,data:n,keyword:i,it:a}=r,o=t.name("valid");for(let s in e)(0,Joe.alwaysValidSchema)(a,e[s])||(t.if((0,h0.propertyInData)(t,n,s,a.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:s},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}Pd.validateSchemaDeps=gL;Pd.default=Zoe});var vL=Ae(sR=>{"use strict";g();Object.defineProperty(sR,"__esModule",{value:!0});var wL=jt(),Xoe=Xt(),Qoe={message:"property name must be valid",params:({params:r})=>(0,wL._)`{propertyName: ${r.propertyName}}`},eae={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qoe,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Xoe.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,wL.not)(a),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(a)}};sR.default=eae});var aR=Ae(oR=>{"use strict";g();Object.defineProperty(oR,"__esModule",{value:!0});var Vx=Ea(),kc=jt(),tae=xa(),Wx=Xt(),rae={message:"must NOT have additional properties",params:({params:r})=>(0,kc._)`{additionalProperty: ${r.additionalProperty}}`},nae={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rae,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:a,it:o}=r;if(!a)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Wx.alwaysValidSchema)(o,t))return;let l=(0,Vx.allSchemaProperties)(n.properties),d=(0,Vx.allSchemaProperties)(n.patternProperties);u(),r.ok((0,kc._)`${a} === ${tae.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(l.length>8){let w=(0,Wx.schemaRefOrVal)(o,n.properties,"properties");v=(0,Vx.isOwnProperty)(e,w,y)}else l.length?v=(0,kc.or)(...l.map(w=>(0,kc._)`${y} === ${w}`)):v=kc.nil;return d.length&&(v=(0,kc.or)(v,...d.map(w=>(0,kc._)`${(0,Vx.usePattern)(r,w)}.test(${y})`))),(0,kc.not)(v)}function p(y){e.code((0,kc._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),s||e.break();return}if(typeof t=="object"&&!(0,Wx.alwaysValidSchema)(o,t)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,kc.not)(v),()=>{r.reset(),p(y)})):(m(y,v),s||e.if((0,kc.not)(v),()=>e.break()))}}function m(y,v,w){let x={keyword:"additionalProperties",dataProp:y,dataPropType:Wx.Type.Str};w===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(x,v)}}};oR.default=nae});var xL=Ae(dR=>{"use strict";g();Object.defineProperty(dR,"__esModule",{value:!0});var iae=Qv(),bL=Ea(),cR=Xt(),PL=aR(),sae={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&PL.default.code(new iae.KeywordCxt(a,PL.default,"additionalProperties"));let o=(0,bL.allSchemaProperties)(t);for(let u of o)a.definedProperties.add(u);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=cR.mergeEvaluated.props(e,(0,cR.toHash)(o),a.props));let s=o.filter(u=>!(0,cR.alwaysValidSchema)(a,t[u]));if(s.length===0)return;let c=e.name("valid");for(let u of s)l(u)?d(u):(e.if((0,bL.propertyInData)(e,i,u,a.opts.ownProperties)),d(u),a.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return a.opts.useDefaults&&!a.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};dR.default=sae});var _L=Ae(lR=>{"use strict";g();Object.defineProperty(lR,"__esModule",{value:!0});var EL=Ea(),Jx=jt(),SL=Xt(),kL=Xt(),oae={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:a}=r,{opts:o}=a,s=(0,EL.allSchemaProperties)(t),c=s.filter(m=>(0,SL.alwaysValidSchema)(a,t[m]));if(s.length===0||c.length===s.length&&(!a.opts.unevaluated||a.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof Jx.Name)&&(a.props=(0,kL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of s)l&&p(m),a.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,SL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,Jx._)`${(0,EL.usePattern)(r,m)}.test(${y})`,()=>{let v=c.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kL.Type.Str},d),a.opts.unevaluated&&u!==!0?e.assign((0,Jx._)`${u}[${y}]`,!0):!v&&!a.allErrors&&e.if((0,Jx.not)(d),()=>e.break())})})}}};lR.default=oae});var AL=Ae(uR=>{"use strict";g();Object.defineProperty(uR,"__esModule",{value:!0});var aae=Xt(),cae={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,aae.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};uR.default=cae});var TL=Ae(fR=>{"use strict";g();Object.defineProperty(fR,"__esModule",{value:!0});var dae=Ea(),lae={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dae.validateUnion,error:{message:"must match a schema in anyOf"}};fR.default=lae});var IL=Ae(pR=>{"use strict";g();Object.defineProperty(pR,"__esModule",{value:!0});var Zx=jt(),uae=Xt(),fae={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Zx._)`{passingSchemas: ${r.passing}}`},pae={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fae,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=t,o=e.let("valid",!1),s=e.let("passing",null),c=e.name("_valid");r.setParams({passing:s}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){a.forEach((d,u)=>{let f;(0,uae.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Zx._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Zx._)`[${s}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(s,u),f&&r.mergeEvaluated(f,Zx.Name)})})}}};pR.default=pae});var DL=Ae(hR=>{"use strict";g();Object.defineProperty(hR,"__esModule",{value:!0});var hae=Xt(),mae={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,o)=>{if((0,hae.alwaysValidSchema)(n,a))return;let s=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(s)})}};hR.default=mae});var $L=Ae(mR=>{"use strict";g();Object.defineProperty(mR,"__esModule",{value:!0});var Yx=jt(),CL=Xt(),yae={message:({params:r})=>(0,Yx.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Yx._)`{failingKeyword: ${r.ifClause}}`},gae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yae,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,CL.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=RL(n,"then"),a=RL(n,"else");if(!i&&!a)return;let o=e.let("valid",!0),s=e.name("_valid");if(c(),r.reset(),i&&a){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(s,l("then",d),l("else",d))}else i?e.if(s,l("then")):e.if((0,Yx.not)(s),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},s);e.assign(o,s),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Yx._)`${d}`):r.setParams({ifClause:d})}}}};function RL(r,e){let t=r.schema[e];return t!==void 0&&!(0,CL.alwaysValidSchema)(r,t)}mR.default=gae});var BL=Ae(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var wae=Xt(),vae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,wae.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};yR.default=vae});var OL=Ae(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var bae=QD(),Pae=fL(),xae=eR(),Eae=hL(),Sae=mL(),kae=Hx(),_ae=vL(),Aae=aR(),Tae=xL(),Iae=_L(),Dae=AL(),Rae=TL(),Cae=IL(),$ae=DL(),Bae=$L(),Oae=BL();function jae(r=!1){let e=[Dae.default,Rae.default,Cae.default,$ae.default,Bae.default,Oae.default,_ae.default,Aae.default,kae.default,Tae.default,Iae.default];return r?e.push(Pae.default,Eae.default):e.push(bae.default,xae.default),e.push(Sae.default),e}gR.default=jae});var vR=Ae(m0=>{"use strict";g();Object.defineProperty(m0,"__esModule",{value:!0});m0.dynamicAnchor=void 0;var wR=jt(),Mae=xa(),jL=t0(),Kae=Ux(),Nae={keyword:"$dynamicAnchor",schemaType:"string",code:r=>ML(r,r.schema)};function ML(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,wR._)`${Mae.default.dynamicAnchors}${(0,wR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Uae(r);t.if((0,wR._)`!${i}`,()=>t.assign(i,a))}m0.dynamicAnchor=ML;function Uae(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:a,localRefs:o,meta:s}=e.root,{schemaId:c}=n.opts,l=new jL.SchemaEnv({schema:t,schemaId:c,root:i,baseId:a,localRefs:o,meta:s});return jL.compileSchema.call(n,l),(0,Kae.getValidate)(r,l)}m0.default=Nae});var bR=Ae(y0=>{"use strict";g();Object.defineProperty(y0,"__esModule",{value:!0});y0.dynamicRef=void 0;var KL=jt(),Lae=xa(),NL=Ux(),qae={keyword:"$dynamicRef",schemaType:"string",code:r=>UL(r,r.schema)};function UL(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0,KL._)`${Lae.default.dynamicAnchors}${(0,KL.getProperty)(a)}`);t.if(l,s(l,c),s(i.validateName,c))}else s(i.validateName,c)()}function s(c,l){return l?()=>t.block(()=>{(0,NL.callRef)(r,c),t.let(l,!0)}):()=>(0,NL.callRef)(r,c)}}y0.dynamicRef=UL;y0.default=qae});var LL=Ae(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var zae=vR(),Fae=Xt(),Gae={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,zae.dynamicAnchor)(r,""):(0,Fae.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};PR.default=Gae});var qL=Ae(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var Hae=bR(),Vae={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Hae.dynamicRef)(r,r.schema)};xR.default=Vae});var zL=Ae(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var Wae=vR(),Jae=bR(),Zae=LL(),Yae=qL(),Xae=[Wae.default,Jae.default,Zae.default,Yae.default];ER.default=Xae});var GL=Ae(SR=>{"use strict";g();Object.defineProperty(SR,"__esModule",{value:!0});var FL=Hx(),Qae={keyword:"dependentRequired",type:"object",schemaType:"object",error:FL.error,code:r=>(0,FL.validatePropertyDeps)(r)};SR.default=Qae});var HL=Ae(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var ece=Hx(),tce={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,ece.validateSchemaDeps)(r)};kR.default=tce});var VL=Ae(_R=>{"use strict";g();Object.defineProperty(_R,"__esModule",{value:!0});var rce=Xt(),nce={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,rce.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};_R.default=nce});var WL=Ae(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var ice=GL(),sce=HL(),oce=VL(),ace=[ice.default,sce.default,oce.default];AR.default=ace});var ZL=Ae(TR=>{"use strict";g();Object.defineProperty(TR,"__esModule",{value:!0});var tf=jt(),JL=Xt(),cce=xa(),dce={message:"must NOT have unevaluated properties",params:({params:r})=>(0,tf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},lce={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:dce,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:s}=a;s instanceof tf.Name?e.if((0,tf._)`${s} !== true`,()=>e.forIn("key",n,u=>e.if(l(s,u),()=>c(u)))):s!==!0&&e.forIn("key",n,u=>s===void 0?c(u):e.if(d(s,u),()=>c(u))),a.props=!0,r.ok((0,tf._)`${i} === ${cce.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,JL.alwaysValidSchema)(a,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:JL.Type.Str},f),o||e.if((0,tf.not)(f),()=>e.break())}}function l(u,f){return(0,tf._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let h in u)u[h]===!0&&p.push((0,tf._)`${f} !== ${h}`);return(0,tf.and)(...p)}}};TR.default=lce});var XL=Ae(IR=>{"use strict";g();Object.defineProperty(IR,"__esModule",{value:!0});var Yp=jt(),YL=Xt(),uce={message:({params:{len:r}})=>(0,Yp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Yp._)`{limit: ${r}}`},fce={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:uce,code(r){let{gen:e,schema:t,data:n,it:i}=r,a=i.items||0;if(a===!0)return;let o=e.const("len",(0,Yp._)`${n}.length`);if(t===!1)r.setParams({len:a}),r.fail((0,Yp._)`${o} > ${a}`);else if(typeof t=="object"&&!(0,YL.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,Yp._)`${o} <= ${a}`);e.if((0,Yp.not)(c),()=>s(c,a)),r.ok(c)}i.items=!0;function s(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:YL.Type.Num},c),i.allErrors||e.if((0,Yp.not)(c),()=>e.break())})}}};IR.default=fce});var QL=Ae(DR=>{"use strict";g();Object.defineProperty(DR,"__esModule",{value:!0});var pce=ZL(),hce=XL(),mce=[pce.default,hce.default];DR.default=mce});var e9=Ae(RR=>{"use strict";g();Object.defineProperty(RR,"__esModule",{value:!0});var Gn=jt(),yce={message:({schemaCode:r})=>(0,Gn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Gn._)`{format: ${r}}`},gce={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:yce,code(r,e){let{gen:t,data:n,$data:i,schema:a,schemaCode:o,it:s}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=s;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),m=t.const("fDef",(0,Gn._)`${h}[${o}]`),y=t.let("fType"),v=t.let("format");t.if((0,Gn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,Gn._)`${m}.type || "string"`).assign(v,(0,Gn._)`${m}.validate`),()=>t.assign(y,(0,Gn._)`"string"`).assign(v,m)),r.fail$data((0,Gn.or)(w(),x()));function w(){return c.strictSchema===!1?Gn.nil:(0,Gn._)`${o} && !${v}`}function x(){let _=d.$async?(0,Gn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Gn._)`${v}(${n})`,A=(0,Gn._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,Gn._)`${v} && ${v} !== true && ${y} === ${e} && !${A}`}}function p(){let h=u.formats[a];if(!h){w();return}if(h===!0)return;let[m,y,v]=x(h);m===e&&r.pass(_());function w(){if(c.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function x(A){let D=A instanceof RegExp?(0,Gn.regexpCode)(A):c.code.formats?(0,Gn._)`${c.code.formats}${(0,Gn.getProperty)(a)}`:void 0,N=t.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Gn._)`${N}.validate`]:["string",A,N]}function _(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Gn._)`await ${v}(${n})`}return typeof y=="function"?(0,Gn._)`${v}(${n})`:(0,Gn._)`${v}.test(${n})`}}}};RR.default=gce});var t9=Ae(CR=>{"use strict";g();Object.defineProperty(CR,"__esModule",{value:!0});var wce=e9(),vce=[wce.default];CR.default=vce});var r9=Ae(Ty=>{"use strict";g();Object.defineProperty(Ty,"__esModule",{value:!0});Ty.contentVocabulary=Ty.metadataVocabulary=void 0;Ty.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ty.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var i9=Ae($R=>{"use strict";g();Object.defineProperty($R,"__esModule",{value:!0});var bce=ZU(),Pce=cL(),xce=OL(),Ece=zL(),Sce=WL(),kce=QL(),_ce=t9(),n9=r9(),Ace=[Ece.default,bce.default,Pce.default,(0,xce.default)(!0),_ce.default,n9.metadataVocabulary,n9.contentVocabulary,Sce.default,kce.default];$R.default=Ace});var o9=Ae(Xx=>{"use strict";g();Object.defineProperty(Xx,"__esModule",{value:!0});Xx.DiscrError=void 0;var s9;(function(r){r.Tag="tag",r.Mapping="mapping"})(s9||(Xx.DiscrError=s9={}))});var c9=Ae(OR=>{"use strict";g();Object.defineProperty(OR,"__esModule",{value:!0});var Iy=jt(),BR=o9(),a9=t0(),Tce=e0(),Ice=Xt(),Dce={message:({params:{discrError:r,tagName:e}})=>r===BR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Iy._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},Rce={keyword:"discriminator",type:"object",schemaType:"object",error:Dce,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:a}=r,{oneOf:o}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Iy._)`${t}${(0,Iy.getProperty)(s)}`);e.if((0,Iy._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:BR.DiscrError.Tag,tag:l,tagName:s})),r.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Iy._)`${l} === ${h}`),e.assign(c,u(p[h]));e.else(),r.error(!1,{discrError:BR.DiscrError.Mapping,tag:l,tagName:s}),e.endIf()}function u(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Iy.Name),h}function f(){var p;let h={},m=v(i),y=!0;for(let _=0;_<o.length;_++){let A=o[_];if(A?.$ref&&!(0,Ice.schemaHasRulesButRef)(A,a.self.RULES)){let N=A.$ref;if(A=a9.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),A instanceof a9.SchemaEnv&&(A=A.schema),A===void 0)throw new Tce.default(a.opts.uriResolver,a.baseId,N)}let D=(p=A?.properties)===null||p===void 0?void 0:p[s];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);y=y&&(m||v(A)),w(D,_)}if(!y)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:_}){return Array.isArray(_)&&_.includes(s)}function w(_,A){if(_.const)x(_.const,A);else if(_.enum)for(let D of _.enum)x(D,A);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function x(_,A){if(typeof _!="string"||_ in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[_]=A}}}};OR.default=Rce});var d9=Ae((jOe,Cce)=>{Cce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var l9=Ae((MOe,$ce)=>{$ce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var u9=Ae((KOe,Bce)=>{Bce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var f9=Ae((NOe,Oce)=>{Oce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var p9=Ae((UOe,jce)=>{jce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var h9=Ae((LOe,Mce)=>{Mce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var m9=Ae((qOe,Kce)=>{Kce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var y9=Ae((zOe,Nce)=>{Nce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var g9=Ae(jR=>{"use strict";g();Object.defineProperty(jR,"__esModule",{value:!0});var Uce=d9(),Lce=l9(),qce=u9(),zce=f9(),Fce=p9(),Gce=h9(),Hce=m9(),Vce=y9(),Wce=["/properties"];function Jce(r){return[Uce,Lce,qce,zce,Fce,e(this,Gce),Hce,e(this,Vce)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,Wce):n}}jR.default=Jce});var NR=Ae((dn,KR)=>{"use strict";g();Object.defineProperty(dn,"__esModule",{value:!0});dn.MissingRefError=dn.ValidationError=dn.CodeGen=dn.Name=dn.nil=dn.stringify=dn.str=dn._=dn.KeywordCxt=dn.Ajv2020=void 0;var Zce=GU(),Yce=i9(),Xce=c9(),Qce=g9(),MR="https://json-schema.org/draft/2020-12/schema",Dy=class extends Zce.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Yce.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xce.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Qce.default.call(this,e),this.refs["http://json-schema.org/schema"]=MR)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(MR)?MR:void 0)}};dn.Ajv2020=Dy;KR.exports=dn=Dy;KR.exports.Ajv2020=Dy;Object.defineProperty(dn,"__esModule",{value:!0});dn.default=Dy;var ede=Qv();Object.defineProperty(dn,"KeywordCxt",{enumerable:!0,get:function(){return ede.KeywordCxt}});var Ry=jt();Object.defineProperty(dn,"_",{enumerable:!0,get:function(){return Ry._}});Object.defineProperty(dn,"str",{enumerable:!0,get:function(){return Ry.str}});Object.defineProperty(dn,"stringify",{enumerable:!0,get:function(){return Ry.stringify}});Object.defineProperty(dn,"nil",{enumerable:!0,get:function(){return Ry.nil}});Object.defineProperty(dn,"Name",{enumerable:!0,get:function(){return Ry.Name}});Object.defineProperty(dn,"CodeGen",{enumerable:!0,get:function(){return Ry.CodeGen}});var tde=Rx();Object.defineProperty(dn,"ValidationError",{enumerable:!0,get:function(){return tde.default}});var rde=e0();Object.defineProperty(dn,"MissingRefError",{enumerable:!0,get:function(){return rde.default}})});var rf,Qx=G(()=>{"use strict";g();SP();Et();rf=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:o}=e;await Ko.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:o}),r.verifyScope(t,a.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:o}=e;await Ko.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:a,messageStore:o});let c=a.scope.protocol,l=i.descriptor.filter?.protocol;if(c!==void 0&&l!==c)throw new ie(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${c} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ie(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function Ws(r){let e=r.indexOf(":");if(e===-1)return;let t=r.substring(0,e),n=r.substring(e+1);return{alias:t,protocolPath:n}}function nf(r){return r.includes(":")}function e2(r){return r.split("/").slice(-1)[0]}function Ed(r,e){let t=r.split("/"),n,i=e;for(let a of t){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var xd,Xp=G(()=>{"use strict";g();Pn();Um();xd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,d=[Pt.ProtocolPath,e.protocol];async function u(f,p){for(let h in f)if(!h.startsWith("$")){let m=[...p,h],y=f[h];if(y.$ref!==void 0){await u(y,m);continue}let v=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:v},await u(y,m)}}return await u(i.structure,d),i}let a=t;async function o(l,d){for(let u in l)if(!u.startsWith("$")){let f=await Ni.derivePrivateKey(d,[u]),p=l[u];if(p.$ref!==void 0){await o(p,f);continue}let h=await At.getPublicKey({key:f.derivedPrivateKey});p.$encryption={rootKeyId:a,publicKeyJwk:h},await o(p,f)}}let s={derivationScheme:Pt.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},c=await Ni.derivePrivateKey(s,[Pt.ProtocolPath,e.protocol]);return await o(i.structure,c),i}}});var w9,_a,t2=G(()=>{"use strict";g();Pc();w9=Tn(NR(),1);vr();dc();Qx();ms();Et();ur();Xp();ga();Bg();_a=class r extends On{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),definition:r.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await ye.createAuthorization({descriptor:t,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),r.validateProtocolDefinition(i.descriptor.definition),new r(i)}async authorizeAuthorDelegate(e){let t=Ir.parse(this.message.authorization.authorDelegatedGrant);await rf.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}static validateProtocolDefinition(e){let{protocol:t,types:n,uses:i}=e;li(t);for(let a in n){let o=n[a].schema;o!==void 0&&td(o)}i!==void 0&&r.validateUses(i,t),r.validateStructure(e)}static validateUses(e,t){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ie(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{li(e[i])}catch{throw new ie(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ie(re.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${t}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:t}=e,n=Object.keys(e.types),i=r.fetchAllRolePathsRecursively("",e.structure,[]);r.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:t,types:e.types})}static fetchAllRolePathsRecursively(e,t,n){if(e.split("/").length>10)throw new ie(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let a=t[i],o;e===""?o=i:o=`${e}/${i}`,a.$role?n.push(o):r.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:o,types:s}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ie(re.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);r.validateRefNode(t,n,o)}if(t.$size!==void 0){let{min:l=0,max:d}=t.$size;if(d!==void 0&&d<l)throw new ie(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${d} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:d}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ie(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Wl);if(!u.includes(d))throw new ie(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new w9.default.default,{$allowUndefinedTags:d,$requiredTags:u,...f}=t.$tags;for(let p in f){let h=f[p];if(!l.validateSchema(h)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${p}`});throw new ie(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let c=t.$actions??[];for(let l=0;l<c.length;l++){let d=c[l];if(d.role!==void 0){if(nf(d.role))r.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ie(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ie(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(d.who===$c.Recipient&&d.of===void 0&&d.can.some(f=>![xr.CoUpdate,xr.CoDelete,xr.CoPrune].includes(f)))throw new ie(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who===$c.Author&&!d.of)throw new ie(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(nf(d.of))r.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ie(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes(xr.Update)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes(xr.Delete)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes(xr.Prune)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<c.length;u++){let f=c[u];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ie(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ie(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let l=n.split("/").pop();s[l]?.encryptionRequired===!0&&c.some(f=>f.who===$c.Anyone&&f.can.includes(xr.Read))&&console.warn(`ProtocolsConfigure: type '${l}' at path '${n}' has encryptionRequired: true but allows { who: 'anyone', can: ['read'] }. Anyone can read the record but no one outside the key holders can decrypt it.`)}t.$delivery!==void 0&&(t.$actions===void 0||t.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${t.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),t.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes(xr.Update)||d.can.includes(xr.CoUpdate))&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $immutable: true but $actions include 'update' or 'co-update'. The $immutable directive takes precedence \u2014 updates will always be rejected regardless of action rules.`);for(let l in t){if(l.startsWith("$"))continue;let d=t[l];if(d.$ref===void 0&&!i.includes(l))throw new ie(re.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,r.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:o,types:s})}}static validateRefNode(e,t,n){let i=e.$ref,a=Ws(i);if(a===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${t}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let s of o)if(e[s]!==void 0)throw new ie(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${s}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let a=Ws(e);if(a===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(o,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t===void 0||t[a.alias]===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(o,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let t={};for(let i in e.types)t[i]={...e.types[i]};for(let i in t){let a=t[i].schema;a!==void 0&&(t[i].schema=Ep(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Ns(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Ns(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var r2,v9=G(()=>{"use strict";g();Fo();vr();Go();Ho();t2();Qx();Et();ur();Xp();r2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _a.parse(t)}catch(d){return wt(d,400)}try{await yn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return wt(d,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(d){return wt(d,400)}let i={interface:ve.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),o=await ye.getCid(t);for(let d of a)if(await ye.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let s=await ye.getNewestMessage(a),c=!1;(s===void 0||await ye.isNewer(t,s))&&(c=!0,s=t);let l;if(c){let d=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},d,u),l={status:{code:202,detail:"Accepted"}}}else{let d=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),l={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==s){let u=await _a.parse(d),f=r.constructIndexes(u,!1),p=await ye.getCid(d);await this.deps.messageStore.delete(e,p),await this.deps.messageStore.put(e,d,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:t}}static async authorizeProtocolsConfigure(e,t,n){if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await rt.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await rf.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ie(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let a=new Map;for(let o in i){let s=i[o],c=await r.fetchInstalledProtocolDefinition(e,s,n);if(c===void 0)throw new ie(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${s}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}r.validateRefsAndRolesRecursively(t.structure,"",a)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:ve.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],o=t===""?i:`${t}/${i}`;if(a.$ref!==void 0){let c=Ws(a.$ref);if(c!==void 0){let l=n.get(c.alias);if(l===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),u=l.structure;for(let f=0;f<d.length;f++){let p=d[f],h=u[p];if(h===void 0)throw new ie(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(h.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ie(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${l.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}u=h}}}let s=a.$actions??[];for(let c of s){if(c.role!==void 0){let l=Ws(c.role);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let u=Ed(l.protocolPath,d.structure);if(u===void 0||!u.$role)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let l=Ws(c.of);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(Ed(l.protocolPath,d.structure)===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}r.validateRefsAndRolesRecursively(a,o,n)}}}});var Aa,n2=G(()=>{"use strict";g();Pc();vr();Ho();Qx();Oi();ms();Et();ur();ga();Aa=class r extends On{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&li(e.descriptor.filter.protocol),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};rr(t);let n;e.signer!==void 0&&(n=await ye.createAuthorization({descriptor:t,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),new r(i)}static normalizeFilter(e){return{...e,protocol:Ns(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await rt.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await rf.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ie(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var i2,b9=G(()=>{"use strict";g();Fo();Et();Go();n2();Oi();ur();i2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Aa.parse(t)}catch(o){return wt(o,400)}try{await yn(t.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code===re.AuthenticateJwsMissing||o.code===re.ProtocolsQueryUnauthorized||o.code===re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let s=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:s}}else return wt(o,401)}let i={...t.descriptor.filter,interface:ve.Protocols,method:me.Configure,isLatestBaseState:!0};rr(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:ve.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function g0(r,e,t,n,i,a,o,s){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let l=t,d=c;if(nf(c)){let h=Ws(c);if(h===void 0)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(i.uses===void 0||i.uses[h.alias]===void 0)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${h.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);l=i.uses[h.alias],d=h.protocolPath;let m=await o(r,l,a,s),y=Ed(d,m.structure);if(y===void 0||!y.$role)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${c} does not match role record type.`)}else{let h=Ed(c,i.structure);if(h===void 0||!h.$role)throw new ie(re.ProtocolAuthorizationNotARole,`Protocol path ${c} does not match role record type.`)}let u={interface:ve.Records,method:me.Write,protocol:l,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ie(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=nr.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:p}=await a.query(r,[u]);if(p.length===0)throw new ie(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${d}`)}async function nde(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,a=await _t.fetchInitialRecordsWrite(t,r,i);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push(xr.CoPrune),e.author===a.author&&o.push(xr.Prune)):(o.push(xr.CoDelete),e.author===a.author&&o.push(xr.Delete)),o;case me.Count:return[xr.Read];case me.Query:return[xr.Read];case me.Read:return[xr.Read];case me.Subscribe:return[xr.Read];case me.Write:let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?[xr.Squash,xr.Create]:[xr.Create];{let l=e.message.recordId,d=await _t.fetchInitialRecordsWrite(t,r,l);return d===void 0?[]:e.author===d.author?[xr.CoUpdate,xr.Update]:[xr.CoUpdate]}}return[]}async function w0(r,e,t,n,i,a){let o=e.message.descriptor.method,s=await nde(r,e,i),c=e.author,l=t.$actions;if(l===void 0)throw new ie(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(h=>s.includes(h)))continue;if(u.who===$c.Anyone)return;if(c===void 0)continue;if(d!==void 0){if(u.role===d)return;continue}if(u.who===$c.Recipient&&u.of===void 0){let h;if(e.message.descriptor.method===me.Write?h=e.message:h=n[n.length-1],h.descriptor.recipient===c)return;continue}if(await ide(c,u,n,a))return}throw new ie(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function ide(r,e,t,n){let i=e.of;if(i===void 0)return!1;let a;if(nf(i)&&n?.uses!==void 0){let o=Ws(i);if(o!==void 0){let s=n.uses[o.alias];s!==void 0&&(a=t.find(c=>c.descriptor.protocol===s&&c.descriptor.protocolPath===o.protocolPath))}}else a=t.find(o=>o.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===$c.Recipient)return r===a.descriptor.recipient;{let o=(await _t.parse(a)).author;return r===o}}var P9=G(()=>{"use strict";g();yc();Gs();Et();ur();Xp();Bg()});async function Cy(r,e,t){let n={interface:ve.Records,method:me.Write,recordId:e},{messages:i}=await t.query(r,[n]);return i.length===0?void 0:await _t.getInitialWrite(i)}async function v0(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await Cy(r,i,t);if(a===void 0)throw new ie(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(a),i=a.descriptor.parentId}return n.reverse()}async function UR(r,e,t){let n=await Cy(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var x9=G(()=>{"use strict";g();Gs();Et();ur()});async function S9(r,e,t,n,i){let a=e.message.descriptor.protocolPath,o=e2(a),s=e.message.descriptor.parentId;if(s===void 0){if(a!==o)throw new ie(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,l=await sde(r,c,a,t,n,i),d={isLatestBaseState:!0,interface:ve.Records,method:me.Write,protocol:l,recordId:s},{messages:u}=await t.query(r,[d]),f=u[0];if(f===void 0)throw l!==c?new ie(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${s}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ie(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new ie(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ie(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function sde(r,e,t,n,i,a){let o=t.split("/");if(o.length<=1)return e;let s=await i(r,e,n,a),c=s.structure[o[0]];if(c?.$ref!==void 0){let l=Ws(c.$ref);if(l!==void 0&&s.uses!==void 0){let d=s.uses[l.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function k9(r,e,t,n,i,a){let o=e.descriptor.protocolPath,s=e2(o),c=await ode(r,o,t,n,i,a);ade(e,c,s)}async function ode(r,e,t,n,i,a){let o=e.split("/"),s=t.structure[o[0]];if(s?.$ref!==void 0&&o.length===1){let c=Ws(s.$ref);if(c!==void 0&&t.uses!==void 0){let l=t.uses[c.alias];if(l!==void 0)return(await i(r,l,n,a)).types}}return t.types}function ade(r,e,t){let n=t??e2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ie(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=r.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ie(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:s}=r.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(s))throw new ie(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${s}'`);if(a.encryptionRequired===!0&&r.encryption===void 0)throw new ie(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function _9(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ie(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ie(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function A9(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...s}=e.$tags,c=a||!1,l=o||[],d=new E9.default.default,u=d.compile({type:"object",properties:s,required:l,additionalProperties:c});if(!u(t)){let p=d.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ie(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${p}`)}}}async function T9(r,e,t,n){if(!t.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ie(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let o=i.message.descriptor.protocolPath,s={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:o,recipient:a},c=Ie.getParentContextFromOfContextId(i.message.contextId);if(c!==""){let f=nr.constructPrefixFilterAsRangeFilter(c);s.contextId=f}let{messages:l}=await n.query(r,[s]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ie(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function I9(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=t.$recordLimit,s=e.message.descriptor.protocolPath,c={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:s},l=Ie.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=nr.constructPrefixFilterAsRangeFilter(l);c.contextId=u}if(await n.count(r,[c])>=a)throw o===Wl.Reject?new ie(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${a} reached at protocol path '${s}'${l!==""?` under parent context '${l}'`:""}: new records are rejected until existing records are deleted.`):new ie(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${o}' is not yet implemented.`)}async function D9(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ie(re.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${r.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await r.isInitialWrite())throw new ie(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function R9(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ie(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var E9,C9=G(()=>{"use strict";g();Bg();E9=Tn(NR(),1);yc();ti();Et();ur();Xp()});var bs,Qp=G(()=>{"use strict";g();Xp();ed();Et();ur();P9();x9();C9();bs=class r{static async validateReferentialIntegrity(e,t,n,i){let a=await UR(e,t,n),o=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),s=r.createBoundFetchDefinition(i);await k9(e,t.message,o,n,s,a),await S9(e,t,n,s,a);let c=r.getRuleSet(t.message.descriptor.protocolPath,o);await T9(e,t,c,n),_9(t,c),A9(t,c),await R9(t,c),await D9(t,c),await I9(e,t,c,n)}static async authorizeWrite(e,t,n,i){let a=await Cy(e,t.message.recordId,n),o;a===void 0?o=await v0(e,t.message.descriptor.parentId,n):o=await v0(e,t.message.recordId,n);let s=await UR(e,t,n),c=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,s,i),l=r.getRuleSet(t.message.descriptor.protocolPath,c),d=r.createBoundFetchDefinition(i);await g0(e,t,t.message.descriptor.protocol,t.message.contextId,c,n,d,s),await w0(e,t,l,o,n,c)}static async authorizeRead(e,t,n,i,a){let o=await v0(e,n.message.recordId,i),s=await Cy(e,n.message.recordId,i),c=s!==void 0?s.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await g0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await w0(e,t,d,o,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:a,protocolPath:o,contextId:s}=t.message.descriptor.filter,c=await r.fetchProtocolDefinition(e,a,n,void 0,i),l=r.getRuleSet(o,c),d=r.createBoundFetchDefinition(i);await g0(e,t,a,s,c,n,d),await w0(e,t,l,[],n,c)}static async authorizeDelete(e,t,n,i,a){let o=await v0(e,t.message.descriptor.recordId,i),s=await Cy(e,t.message.descriptor.recordId,i),c=s!==void 0?s.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await g0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await w0(e,t,d,o,i,l)}static async fetchProtocolDefinition(e,t,n,i,a){if(a!==void 0){let l=a.getDefinition(t);if(l!==void 0)return l}let o={interface:ve.Protocols,method:me.Configure,protocol:t};i!==void 0?o.messageTimestamp={lte:i}:o.isLatestBaseState=!0;let{messages:s}=await n.query(e,[o],{messageTimestamp:Rt.Descending},{limit:1});if(s.length===0)throw new ie(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return s[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,a)=>r.fetchProtocolDefinition(t,n,i,a,e)}static getRuleSet(e,t){let n=Ed(e,t.structure);if(n===void 0)throw new ie(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var s2,$9=G(()=>{"use strict";g();Fo();vr();Go();Qp();ti();dx();ur();s2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await hd.parse(t)}catch(a){return wt(a,400)}let i;if(Ie.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return wt(a,401)}n.author===e?i=await this.countRecordsAsOwner(e,n):i=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:i}}async countRecordsAsOwner(e,t){let{filter:n}=t.message.descriptor,i={...Ie.convertFilter(n),interface:ve.Records,method:me.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,t){let{filter:n}=t.message.descriptor,i=[];return Ie.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),Ie.filterIncludesUnpublishedRecords(n)&&(Ie.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),Ie.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ie.shouldBuildUnpublishedRecipientFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsForCountAuthorFilter(t))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,t){let n=r.buildPublishedRecordsFilter(t);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var Ta,b0=G(()=>{"use strict";g();Pc();vr();dc();ti();rd();Oi();ms();ur();Ta=class r extends On{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=kt.getCurrentTimestamp(),i={interface:ve.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},a=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:i,authorization:a};return ye.validateJsonSchema(o),new r(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:o,schema:s,parentId:c,dateCreated:l}=e.descriptor,d={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:o,schema:s,parentId:c,dateCreated:l,contextId:e.contextId,author:this.author,...n};return rr(d),d}async authorizeDelegate(e,t){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var sf,o2,a2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(sf||(sf={}));o2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[sf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[sf.RecordsSquash]:async n=>await t.performRecordsSquash(n)}}async run(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,t);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,t)},r.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{r.clearTimeoutExtensionTimer(n)}}static clearTimeoutExtensionTimer(e){clearInterval(e)}async resumeTasksAndWaitForCompletion(){for(;;){let e=await this.resumableTaskStore.grab(this.resumableTaskBatchSize);if(e===void 0||e.length===0)break;await this.retryTasksUntilCompletion(e)}}async retryTasksUntilCompletion(e){let t=e;for(;t.length>0;){let n=t;t=[];for(let i of n)try{await this.runWithAutomaticTimeoutExtension(i)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",i),t.push(i)}}}}});var c2,B9=G(()=>{"use strict";g();Fo();ur();vr();Go();Ho();Qp();ti();b0();rd();Gs();a2();c2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Ta.parse(t)}catch(l){return wt(l,400)}try{await yn(t.authorization,this.deps.didResolver)}catch(l){return wt(l,401)}let i={interface:ve.Records,recordId:t.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),o=await ye.getNewestMessage(a);if(!Ie.canPerformDeleteAgainstRecord(t,o))return{status:{code:404,detail:"Not Found"}};if(!await ye.isNewer(t,o))return{status:{code:409,detail:"Conflict"}};try{let l=await _t.fetchInitialRecordsWrite(this.deps.messageStore,e,t.descriptor.recordId);await r.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return wt(l,401)}return await this.deps.resumableTaskManager.run({name:sf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,a){if(ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let o=await rt.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Ln.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await bs.authorizeDelete(e,t,n,i,a)}}});var d2,O9=G(()=>{"use strict";g();Fo();mp();vr();Go();Qp();ti();lx();Gs();ed();ur();d2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await ba.parse(t)}catch(o){return wt(o,400)}let i,a;if(Ie.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);i=o.messages,a=o.cursor}else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return wt(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);i=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);i=o.messages,a=o.cursor}}for(let o of i)if(!await _t.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:Rt.Ascending};case Ut.CreatedDescending:return{dateCreated:Rt.Descending};case Ut.PublishedAscending:return{datePublished:Rt.Ascending};case Ut.PublishedDescending:return{datePublished:Rt.Descending};case Ut.UpdatedAscending:return{messageTimestamp:Rt.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:Rt.Descending};default:return{dateCreated:Rt.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:a}=t.message.descriptor,o={...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0},s=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],s,a)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:a}=t.message.descriptor,o=[];Ie.filterIncludesPublishedRecords(a)&&o.push(r.buildPublishedRecordsFilter(t)),Ie.filterIncludesUnpublishedRecords(a)&&(Ie.shouldBuildUnpublishedAuthorFilter(a,t.author)&&o.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),Ie.shouldProtocolAuthorize(t.signaturePayload)&&o.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ie.shouldBuildUnpublishedRecipientFilter(a,t.author)&&o.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let s=this.convertDateSort(n);return this.deps.messageStore.query(e,o,s,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,a=r.buildPublishedRecordsFilter(t),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var Sd,LR=G(()=>{"use strict";g();Pc();mp();vr();dc();ti();rd();Oi();ms();Et();ur();Sd=class r extends On{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ut.PublishedAscending||e.descriptor.dateSort===Ut.PublishedDescending))throw new ie(re.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:a,dateSort:o}=e,s=kt.getCurrentTimestamp();if(e.filter.published===!1&&(o===Ut.PublishedAscending||o===Ut.PublishedDescending))throw new ie(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:ve.Records,method:me.Read,filter:Ie.normalizeFilter(t),messageTimestamp:e.messageTimestamp??s,permissionGrantId:i,dateSort:o};rr(c);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:c,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:l};return ye.validateJsonSchema(d),new r(d)}async authorizeDelegate(e,t){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var l2,j9=G(()=>{"use strict";g();Fo();yu();In();vr();Go();Ho();Qp();ti();rd();LR();Gs();Et();ur();l2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Sd.parse(t)}catch(u){return wt(u,400)}try{n.author!==void 0&&await yn(t.authorization,this.deps.didResolver)}catch(u){return wt(u,401)}let i={interface:ve.Records,isLatestBaseState:!0,...Ie.convertFilter(t.descriptor.filter)},a=Ie.convertDateSort(t.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[i],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let s=o[0];if(s.descriptor.method===me.Delete){let u=s,f=u.descriptor.recordId,p=await _t.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(p===void 0)return wt(new ie(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let h;try{h=await _t.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{h=p}let m=await _t.parse(h);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return wt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:p}}}let c=s;try{let u=await _t.parse(c);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return wt(u,401)}let l;if(c.encodedData!==void 0){let u=De.base64UrlToBytes(c.encodedData);l=Wt.fromBytes(u),delete c.encodedData}else{let u=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};l=u.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:l}};if(!await _t.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,t,n,i,a){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i);let{descriptor:o}=n.message;if(t.author!==e){if(o.published===!0)return;if(t.author!==void 0&&(t.author===o.recipient||t.author===n.author))return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let s=await rt.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Ln.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:s,messageStore:i})}else await bs.authorizeRead(e,t,n,i,a)}}}});var Ia,u2=G(()=>{"use strict";g();Pc();vr();dc();ti();rd();Oi();ms();Et();ur();ga();Ia=class r extends On{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ie(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&li(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&td(e.descriptor.filter.schema),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),filter:Ie.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};rr(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:t,authorization:i};return ye.validateJsonSchema(a),new r(a)}async authorizeDelegate(e){let t=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var f2,M9=G(()=>{"use strict";g();Fo();mp();vr();Go();Qp();ti();u2();Gs();ed();Et();ur();f2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return wt(new ie(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Ia.parse(t)}catch(f){return wt(f,400)}let a=[],o=[];if(Ie.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[r.buildPublishedEventFilter(i)],o=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return wt(f,401)}i.author===e?(a=r.buildOwnerEventFilters(i),o=r.buildOwnerQueryFilters(i)):(a=r.buildNonOwnerEventFilters(i),o=r.buildNonOwnerQueryFilters(i))}let s=await ye.getCid(t),{cursor:c}=i.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,s,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ie&&f.code===re.EventLogProgressGap){let p=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:p!==void 0?{code:"ProgressGap",...p}:void 0}}return wt(f,500)}let l=await this.deps.eventLog.subscribe(e,s,n,{filters:a}),d,u;try{let{dateSort:f,pagination:p}=i.message.descriptor,h=r.convertDateSort(f),m=await this.deps.messageStore.query(e,o,h,p);d=m.messages,u=m.cursor;for(let y of d)if(!await _t.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),wt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:d,cursor:u}}static convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:Rt.Ascending};case Ut.CreatedDescending:return{dateCreated:Rt.Descending};case Ut.PublishedAscending:return{datePublished:Rt.Ascending};case Ut.PublishedDescending:return{datePublished:Rt.Descending};case Ut.UpdatedAscending:return{messageTimestamp:Rt.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:Rt.Descending};default:return{dateCreated:Rt.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...Ie.convertFilter(t),interface:ve.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return Ie.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),Ie.filterIncludesUnpublishedRecords(n)&&(Ie.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...Ie.convertFilter(n),author:e.author,interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ie.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ie.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ie.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...Ie.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...Ie.convertFilter(e.message.descriptor.filter),interface:ve.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return Ie.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),Ie.filterIncludesUnpublishedRecords(i)&&(Ie.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...Ie.convertFilter(i,n),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ie.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ie.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var $y,qR=G(()=>{"use strict";g();my();yc();vr();ti();b0();Gs();ur();$y=class r{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:t,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=t,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:t}){let n={interface:ve.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await ye.getNewestMessage(i);if(!Ie.canPerformDeleteAgainstRecord(t,a))return;let o=await Ta.parse(t),s=await _t.getInitialWrite(i),c=o.constructIndexes(s),l=await ye.getCid(t);await this.messageStore.put(e,t,c),await this.stateIndex.insert(e,l,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:s},c,l),t.descriptor.prune&&await r.purgeRecordDescendants(e,t.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await r.deleteAllOlderMessagesButKeepInitialWrite(e,i,t,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:t}){let{protocol:n,protocolPath:i,messageTimestamp:a}=t.descriptor,o={interface:ve.Records,protocol:n,protocolPath:i},s=Ie.getParentContextFromOfContextId(t.contextId);if(s!==void 0&&s!==""){let d=nr.constructPrefixFilterAsRangeFilter(s);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),l=new Map;for(let d of c){let u;Ie.isRecordsWrite(d)?u=d.recordId:u=d.descriptor.recordId;let f=l.get(u);f!==void 0?f.push(d):l.set(u,[d])}for(let[d,u]of l){if(d===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await r.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,t,n,i){if(n.descriptor.method!==me.Write)return;let a=n;a.descriptor.dataSize<=lo.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,a){let o={interface:ve.Records,parentId:t},{messages:s}=await n.query(e,[o]),c=new Map;for(let l of s){let d;Ie.isRecordsWrite(l)?d=l.recordId:d=l.descriptor.recordId;let u=c.get(d);u?u.push(l):c.set(d,[l])}for(let l of c.keys())await r.purgeRecordDescendants(e,l,n,i,a);for(let l of c.keys())await r.purgeRecordMessages(e,c.get(l),n,i,a)}static async purgeRecordMessages(e,t,n,i,a){let o=t.filter(l=>l.descriptor.method===me.Write),s=await ye.getNewestMessage(o);await i.delete(e,s.recordId,s.descriptor.dataCid);let c=await Promise.all(t.map(l=>ye.getCid(l)));await a.delete(e,c),await Promise.all(c.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,a,o){let s=[];for(let c of t){if(await ye.isOlder(c,n)){await r.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ye.getCid(c);if(await i.delete(e,d),await _t.isInitialWrite(c)){let h=await(await _t.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await i.put(e,m,h)}else{let f=await ye.getCid(c);s.push(f)}}await o.delete(e,s)}}}});var p2,K9=G(()=>{"use strict";g();Fo();ll();yu();my();In();yc();vr();Go();Ho();Qp();ti();rd();Gs();a2();ed();qR();Et();ur();p2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,dataStream:n}){let i;try{i=await _t.parse(t),await bs.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(h){return wt(h,400)}try{await yn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(h){return wt(h,401)}let a={interface:ve.Records,recordId:t.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),s=await i.isInitialWrite(),c;if(!s)try{c=await _t.getInitialWrite(o),_t.verifyEqualityOfImmutableProperties(c,t)}catch(h){return wt(h,400)}try{await this.enforceSquashBackstop(e,t)}catch(h){return wt(h,409)}let l=await ye.getNewestMessage(o),d=!1,u;if(l===void 0||await ye.isNewer(t,l)?(d=!0,u=t):u=l,!d){let h=!1;if(l!==void 0&&n!==void 0&&await _t.isInitialWrite(l)){let y=!!l.encodedData,v=this.deps.dataStore?!!await this.deps.dataStore.get(e,i.message.recordId,t.descriptor.dataCid):!1;h=!y&&!v}if(!h)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(t.descriptor.protocol):void 0;try{if(l?.descriptor.method===me.Delete)throw new ie(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let h=!1,m=t;if(n!==void 0)m=await this.processMessageWithDataStream(e,t,n),h=!0;else if(!s){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),h=!0}let y=await i.constructIndexes(h);await this.deps.messageStore.put(e,m,y);let v=await ye.getCid(t);await this.deps.stateIndex.insert(e,v,y),this.deps.eventLog!==void 0&&h&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,v)}catch(h){if(h instanceof ie&&(h.code===re.RecordsWriteMissingEncodedDataInPrevious||h.code===re.RecordsWriteMissingDataInPrevious||h.code===re.RecordsWriteNotAllowedAfterDelete||h.code===re.RecordsWriteDataCidMismatch||h.code===re.RecordsWriteDataSizeMismatch||h.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(h.code)!==void 0))return wt(h,400);throw h}let p={status:s&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await $y.deleteAllOlderMessagesButKeepInitialWrite(e,o,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:sf.RecordsSquash,data:{tenant:e,message:t}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),p}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=De.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=lo.maxDataSizeAllowedToBeEncoded){let a=await Wt.toBytes(n),o=await mr.computeDagPbCidFromBytes(a);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,a.length);let s=t.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(t.descriptor.protocol):void 0;s?.validateRecord!==void 0&&s.validateRecord(t,a),i=await this.cloneAndAddEncodedData(t,a)}else{let[a,o]=Wt.duplicateDataStream(n,2);try{let[s,c]=await Promise.all([mr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,o)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,s,c.dataSize)}catch(s){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),s}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:a,dataSize:o}=t.descriptor;if(r.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=lo.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)i.encodedData=n.encodedData;else throw new ie(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ie(re.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,t,n,i){if(e!==n)throw new ie(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ie(re.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${t}`)}async enforceSquashBackstop(e,t){if(t.descriptor.protocol===void 0||t.descriptor.protocolPath===void 0)return;let n;try{n=await bs.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,d);return}let i=t.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let d=1;d<i.length&&a!==void 0;d++)a=a[i[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},s=Ie.getParentContextFromOfContextId(t.contextId);if(s!==void 0&&s!==""){let d=nr.constructPrefixFilterAsRangeFilter(s);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:Rt.Descending},{limit:1});if(c.length===0)return;let l=c[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ie(re.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${t.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${t.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,t,n){if(t.owner!==void 0&&t.owner!==e)throw new ie(re.RecordsWriteOwnerAndTenantMismatch,`Owner ${t.owner} must be the same as tenant ${e} when specified.`);if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.isSignedByOwnerDelegate&&await t.authorizeOwnerDelegate(n),t.owner===void 0){if(t.author===e)return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await rt.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Ln.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await bs.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function Mde(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var a=r.charAt(i),o=a.charCodeAt(0);if(t[o]!==255)throw new TypeError(a+" is ambiguous");t[o]=i}var s=r.length,c=r.charAt(0),l=Math.log(s)/Math.log(256),d=Math.log(256)/Math.log(s);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,y=0,v=0,w=h.length;v!==w&&h[v]===0;)v++,m++;for(var x=(w-v)*d+1>>>0,_=new Uint8Array(x);v!==w;){for(var A=h[v],D=0,N=x-1;(A!==0||D<y)&&N!==-1;N--,D++)A+=256*_[N]>>>0,_[N]=A%s>>>0,A=A/s>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,v++}for(var $=x-y;$!==x&&_[$]===0;)$++;for(var z=c.repeat(m);$<x;++$)z+=r.charAt(_[$]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var y=0,v=0;h[m]===c;)y++,m++;for(var w=(h.length-m)*l+1>>>0,x=new Uint8Array(w);h[m];){var _=t[h.charCodeAt(m)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<v)&&D!==-1;D--,A++)_+=s*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=A,m++}if(h[m]!==" "){for(var N=w-v;N!==w&&x[N]===0;)N++;for(var $=new Uint8Array(y+(w-N)),z=y;N!==w;)$[z++]=x[N++];return $}}}function p(h){var m=f(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}function Wde(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Jde(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function QR(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function w7(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tle;)e[t++]=r&255|q9,r/=128;for(;r&ele;)e[t++]=r&255|q9,r>>>=7;return e[t]=r|0,w7.bytes=t-n+1,e}function eC(r,n){var t=0,n=n||0,i=0,a=n,o,s=r.length;do{if(a>=s)throw eC.bytes=0,new RangeError("Could not decode varint");o=r[a++],t+=i<28?(o&z9)<<i:(o&z9)*Math.pow(2,i),i+=7}while(o>=nle);return eC.bytes=a-n,t}function v7(r){Object.keys(r).forEach(e=>{r[e]===void 0?delete r[e]:typeof r[e]=="object"&&v7(r[e])})}function $d(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function uh(r){if(!$d(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=_le[r[t]];return e}function x7(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function _C(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function V9(r){if(r>=Bl._0&&r<=Bl._9)return r-Bl._0;if(r>=Bl._A&&r<=Bl._F)return r-(Bl._A-10);if(r>=Bl._a&&r<=Bl._f)return r-(Bl._a-10)}function Hy(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,a=0;i<t;i++,a+=2){let o=V9(r.charCodeAt(a)),s=V9(r.charCodeAt(a+1));if(o===void 0||s===void 0){let c=r[a]+r[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[i]=o*16+s}return n}function ch(r){return _C(uh(r))}function Pf(r){if(!$d(r))throw new Error("Uint8Array expected");return _C(uh(Uint8Array.from(r).reverse()))}function Bd(r,e){return Hy(r.toString(16).padStart(e*2,"0"))}function Vy(r,e){return Bd(r,e).reverse()}function Ale(r){return Hy(x7(r))}function Wn(r,e,t){let n;if(typeof e=="string")try{n=Hy(e)}catch(a){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${a}`)}else if($d(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(`${r} expected ${t} bytes, got ${i}`);return n}function fh(...r){let e=0;for(let i=0;i<r.length;i++){let a=r[i];if(!$d(a))throw new Error("Uint8Array expected");e+=a.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let a=r[i];t.set(a,n),n+=a.length}return t}function Tle(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ile(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Dle(r){let e;for(e=0;r>P7;r>>=nE,e+=1);return e}function Rle(r,e){return r>>BigInt(e)&nE}function E7(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=zR(r),i=zR(r),a=0,o=()=>{n.fill(1),i.fill(0),a=0},s=(...d)=>t(i,n,...d),c=(d=zR())=>{i=s(W9([0]),d),n=s(),d.length!==0&&(i=s(W9([1]),d),n=s())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,u=[];for(;d<e;){n=s();let f=n.slice();u.push(f),d+=n.length}return fh(...u)};return(d,u)=>{o(),c(d);let f;for(;!(f=u(l()));)c();return o(),f}}function mh(r,e,t={}){let n=(i,a,o)=>{let s=$le[a];if(typeof s!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=r[i];if(!(o&&c===void 0)&&!s(c,r))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(t))n(i,a,!0);return r}function J9(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function Ble(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function S7(r,...e){if(!Ble(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function Ole(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J9(r.outputLen),J9(r.blockLen)}function F2(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function jle(r,e){S7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function k7(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function _7(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function TC(r){if(typeof r=="string"&&(r=_7(r)),!k7(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function A7(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!k7(i))throw new Error("Uint8Array expected");e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let a=r[n];t.set(a,i),i+=a.length}return t}function I7(r){let e=n=>r().update(TC(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function IC(r=32){if(FR&&typeof FR.getRandomValues=="function")return FR.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Kle(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),o=Number(t>>i&a),s=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+l,s,n)}function Xr(r,e){let t=r%e;return t>=yi?t:e+t}function C7(r,e,t){if(t<=yi||e<yi)throw new Error("Expected power/modulo > 0");if(t===gn)return yi;let n=gn;for(;e>yi;)e&gn&&(n=n*r%t),r=r*r%t,e>>=gn;return n}function Sn(r,e,t){let n=r;for(;e-- >yi;)n*=n,n%=t;return n}function nC(r,e){if(r===yi||e<=yi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Xr(r,e),n=e,i=yi,a=gn,o=gn,s=yi;for(;t!==yi;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}if(n!==gn)throw new Error("invert: does not exist");return Xr(i,e)}function Gle(r){let e=(r-gn)/nh,t,n,i;for(t=r-gn,n=0;t%nh===yi;t/=nh,n++);for(i=nh;i<r&&C7(i,e,r)!==r-gn;i++);if(n===1){let o=(r+gn)/rC;return function(s,c){let l=s.pow(c,o);if(!s.eql(s.sqr(l),c))throw new Error("Cannot find square root");return l}}let a=(t+gn)/nh;return function(o,s){if(o.pow(s,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,l=o.pow(o.mul(o.ONE,i),t),d=o.pow(s,a),u=o.pow(s,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let f=1;for(let h=o.sqr(u);f<c&&!o.eql(h,o.ONE);f++)h=o.sqr(h);let p=o.pow(l,gn<<BigInt(c-f-1));l=o.sqr(p),d=o.mul(d,p),u=o.mul(u,l),c=f}return d}}function Hle(r){if(r%rC===zle){let e=(r+gn)/rC;return function(t,n){let i=t.pow(n,e);if(!t.eql(t.sqr(i),n))throw new Error("Cannot find square root");return i}}if(r%Y9===Z9){let e=(r-Z9)/Y9;return function(t,n){let i=t.mul(n,nh),a=t.pow(i,e),o=t.mul(n,a),s=t.mul(t.mul(o,nh),a),c=t.mul(o,t.sub(s,t.ONE));if(!t.eql(t.sqr(c),n))throw new Error("Cannot find square root");return c}}return r%Fle,Gle(r)}function Jle(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Wle.reduce((n,i)=>(n[i]="function",n),e);return mh(r,t)}function Zle(r,e,t){if(t<yi)throw new Error("Expected power > 0");if(t===yi)return r.ONE;if(t===gn)return e;let n=r.ONE,i=e;for(;t>yi;)t&gn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=gn;return n}function Yle(r,e){let t=new Array(e.length),n=e.reduce((a,o,s)=>r.is0(o)?a:(t[s]=a,r.mul(a,o)),r.ONE),i=r.inv(n);return e.reduceRight((a,o,s)=>r.is0(o)?a:(t[s]=r.mul(a,t[s]),r.mul(a,o)),i),t}function $7(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function DC(r,e,t=!1,n={}){if(r<=yi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:a}=$7(r,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Hle(r),s=Object.freeze({ORDER:r,BITS:i,BYTES:a,MASK:AC(i),ZERO:yi,ONE:gn,create:c=>Xr(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return yi<=c&&c<r},is0:c=>c===yi,isOdd:c=>(c&gn)===gn,neg:c=>Xr(-c,r),eql:(c,l)=>c===l,sqr:c=>Xr(c*c,r),add:(c,l)=>Xr(c+l,r),sub:(c,l)=>Xr(c-l,r),mul:(c,l)=>Xr(c*l,r),pow:(c,l)=>Zle(s,c,l),div:(c,l)=>Xr(c*nC(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>nC(c,r),sqrt:n.sqrt||(c=>o(s,c)),invertBatch:c=>Yle(s,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Vy(c,a):Bd(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return t?Pf(c):ch(c)}});return Object.freeze(s)}function Xle(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function B7(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function O7(r){let e=B7(r);return e+Math.ceil(e/2)}function Qle(r,e,t=!1){let n=r.length,i=B7(e),a=O7(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=t?ch(r):Pf(r),s=Xr(o,e-gn)+gn;return t?Vy(s,i):Bd(s,i)}function j7(r,e){let t=(i,a)=>{let o=a.negate();return i?o:a},n=i=>{let a=Math.ceil(e/i)+1,o=2**(i-1);return{windows:a,windowSize:o}};return{constTimeNegate:t,unsafeLadder(i,a){let o=r.ZERO,s=i;for(;a>eue;)a&HR&&(o=o.add(s)),s=s.double(),a>>=HR;return o},precomputeWindow(i,a){let{windows:o,windowSize:s}=n(a),c=[],l=i,d=l;for(let u=0;u<o;u++){d=l,c.push(d);for(let f=1;f<s;f++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(i,a,o){let{windows:s,windowSize:c}=n(i),l=r.ZERO,d=r.BASE,u=BigInt(2**i-1),f=2**i,p=BigInt(i);for(let h=0;h<s;h++){let m=h*c,y=Number(o&u);o>>=p,y>c&&(y-=f,o+=HR);let v=m,w=m+Math.abs(y)-1,x=h%2!==0,_=y<0;y===0?d=d.add(t(x,a[v])):l=l.add(t(_,a[w]))}return{p:l,f:d}},wNAFCached(i,a,o,s){let c=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&a.set(i,s(l))),this.wNAF(c,l,o)}}}function RC(r){return Jle(r.Fp),mh(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$7(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function tue(r){let e=RC(r);mh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:i}=e;if(t){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function iue(r){let e=tue(r),{Fp:t}=e,n=e.toBytes||((h,m,y)=>{let v=m.toAffine();return fh(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(h=>{let m=h.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),v=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:v}});function a(h){let{a:m,b:y}=e,v=t.sqr(h),w=t.mul(v,h);return t.add(t.add(w,t.mul(h,m)),y)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function o(h){return typeof h=="bigint"&&Ul<h&&h<e.n}function s(h){if(!o(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof h!="bigint"){if($d(h)&&(h=uh(h)),typeof h!="string"||!m.includes(h.length))throw new Error("Invalid key");h=h.padStart(y*2,"0")}let x;try{x=typeof h=="bigint"?h:ch(Wn("private key",h,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof h}`)}return v&&(x=Xr(x,w)),s(x),x}let l=new Map;function d(h){if(!(h instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,v){if(this.px=m,this.py=y,this.pz=v,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(v==null||!t.isValid(v))throw new Error("z required")}static fromAffine(m){let{x:y,y:v}=m||{};if(!m||!t.isValid(y)||!t.isValid(v))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(v)?u.ZERO:new u(y,v,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(v=>v.pz));return m.map((v,w)=>v.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(Wn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let v=t.sqr(y),w=a(m);if(!t.eql(v,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:v,pz:w}=this,{px:x,py:_,pz:A}=m,D=t.eql(t.mul(y,A),t.mul(x,w)),N=t.eql(t.mul(v,A),t.mul(_,w));return D&&N}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,X9),{px:w,py:x,pz:_}=this,A=t.ZERO,D=t.ZERO,N=t.ZERO,$=t.mul(w,w),z=t.mul(x,x),L=t.mul(_,_),j=t.mul(w,x);return j=t.add(j,j),N=t.mul(w,_),N=t.add(N,N),A=t.mul(m,N),D=t.mul(v,L),D=t.add(A,D),A=t.sub(z,D),D=t.add(z,D),D=t.mul(A,D),A=t.mul(j,A),N=t.mul(v,N),L=t.mul(m,L),j=t.sub($,L),j=t.mul(m,j),j=t.add(j,N),N=t.add($,$),$=t.add(N,$),$=t.add($,L),$=t.mul($,j),D=t.add(D,$),L=t.mul(x,_),L=t.add(L,L),$=t.mul(L,j),A=t.sub(A,$),N=t.mul(L,z),N=t.add(N,N),N=t.add(N,N),new u(A,D,N)}add(m){d(m);let{px:y,py:v,pz:w}=this,{px:x,py:_,pz:A}=m,D=t.ZERO,N=t.ZERO,$=t.ZERO,z=e.a,L=t.mul(e.b,X9),j=t.mul(y,x),H=t.mul(v,_),Y=t.mul(w,A),R=t.add(y,v),C=t.add(x,_);R=t.mul(R,C),C=t.add(j,H),R=t.sub(R,C),C=t.add(y,w);let P=t.add(x,A);return C=t.mul(C,P),P=t.add(j,Y),C=t.sub(C,P),P=t.add(v,w),D=t.add(_,A),P=t.mul(P,D),D=t.add(H,Y),P=t.sub(P,D),$=t.mul(z,C),D=t.mul(L,Y),$=t.add(D,$),D=t.sub(H,$),$=t.add(H,$),N=t.mul(D,$),H=t.add(j,j),H=t.add(H,j),Y=t.mul(z,Y),C=t.mul(L,C),H=t.add(H,Y),Y=t.sub(j,Y),Y=t.mul(z,Y),C=t.add(C,Y),j=t.mul(H,C),N=t.add(N,j),j=t.mul(P,C),D=t.mul(R,D),D=t.sub(D,j),j=t.mul(R,H),$=t.mul(P,$),$=t.add($,j),new u(D,N,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return p.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,x)=>w.toAffine(v[x])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Ul)return y;if(s(m),m===Oa)return this;let{endo:v}=e;if(!v)return p.unsafeLadder(this,m);let{k1neg:w,k1:x,k2neg:_,k2:A}=v.splitScalar(m),D=y,N=y,$=this;for(;x>Ul||A>Ul;)x&Oa&&(D=D.add($)),A&Oa&&(N=N.add($)),$=$.double(),x>>=Oa,A>>=Oa;return w&&(D=D.negate()),_&&(N=N.negate()),N=new u(t.mul(N.px,v.beta),N.py,N.pz),D.add(N)}multiply(m){s(m);let y=m,v,w,{endo:x}=e;if(x){let{k1neg:_,k1:A,k2neg:D,k2:N}=x.splitScalar(y),{p:$,f:z}=this.wNAF(A),{p:L,f:j}=this.wNAF(N);$=p.constTimeNegate(_,$),L=p.constTimeNegate(D,L),L=new u(t.mul(L.px,x.beta),L.py,L.pz),v=$.add(L),w=z.add(j)}else{let{p:_,f:A}=this.wNAF(y);v=_,w=A}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,x=(A,D)=>D===Ul||D===Oa||!A.equals(w)?A.multiplyUnsafe(D):A.multiply(D),_=x(this,y).add(x(m,v));return _.is0()?void 0:_}toAffine(m){let{px:y,py:v,pz:w}=this,x=this.is0();m==null&&(m=x?t.ONE:t.inv(w));let _=t.mul(y,m),A=t.mul(v,m),D=t.mul(w,m);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(D,t.ONE))throw new Error("invZ was invalid");return{x:_,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Oa)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Oa?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return uh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=j7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function sue(r){let e=RC(r);return mh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function oue(r){let e=sue(r),{Fp:t,n}=e,i=t.BYTES+1,a=2*t.BYTES+1;function o(C){return Ul<C&&C<t.ORDER}function s(C){return Xr(C,n)}function c(C){return nC(C,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:f}=iue({...e,toBytes(C,P,S){let E=P.toAffine(),k=t.toBytes(E.x),I=fh;return S?I(Uint8Array.from([P.hasEvenY()?2:3]),k):I(Uint8Array.from([4]),k,t.toBytes(E.y))},fromBytes(C){let P=C.length,S=C[0],E=C.subarray(1);if(P===i&&(S===2||S===3)){let k=ch(E);if(!o(k))throw new Error("Point is not on curve");let I=u(k),K=t.sqrt(I),F=(K&Oa)===Oa;return(S&1)===1!==F&&(K=t.neg(K)),{x:k,y:K}}else if(P===a&&S===4){let k=t.fromBytes(E.subarray(0,t.BYTES)),I=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:k,y:I}}else throw new Error(`Point of length ${P} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),p=C=>uh(Bd(C,e.nByteLength));function h(C){let P=n>>Oa;return C>P}function m(C){return h(C)?s(-C):C}let y=(C,P,S)=>ch(C.slice(P,S));class v{constructor(P,S,E){this.r=P,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(P){let S=e.nByteLength;return P=Wn("compactSignature",P,S*2),new v(y(P,0,S),y(P,S,2*S))}static fromDER(P){let{r:S,s:E}=oh.toSig(Wn("DER",P));return new v(S,E)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(P){return new v(this.r,this.s,P)}recoverPublicKey(P){let{r:S,s:E,recovery:k}=this,I=N(Wn("msgHash",P));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let K=k===2||k===3?S+e.n:S;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let F=k&1?"03":"02",V=l.fromHex(F+p(K)),W=c(K),J=s(-I*W),Q=s(E*W),q=l.BASE.multiplyAndAddUnsafe(V,J,Q);if(!q)throw new Error("point at infinify");return q.assertValidity(),q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Hy(this.toDERHex())}toDERHex(){return oh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Hy(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let w={isValidPrivateKey(C){try{return d(C),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let C=O7(e.n);return Qle(e.randomBytes(C),e.n)},precompute(C=8,P=l.BASE){return P._setWindowSize(C),P.multiply(BigInt(3)),P}};function x(C,P=!0){return l.fromPrivateKey(C).toRawBytes(P)}function _(C){let P=$d(C),S=typeof C=="string",E=(P||S)&&C.length;return P?E===i||E===a:S?E===2*i||E===2*a:C instanceof l}function A(C,P,S=!0){if(_(C))throw new Error("first arg must be private key");if(!_(P))throw new Error("second arg must be public key");return l.fromHex(P).multiply(d(C)).toRawBytes(S)}let D=e.bits2int||function(C){let P=ch(C),S=C.length*8-e.nBitLength;return S>0?P>>BigInt(S):P},N=e.bits2int_modN||function(C){return s(D(C))},$=AC(e.nBitLength);function z(C){if(typeof C!="bigint")throw new Error("bigint expected");if(!(Ul<=C&&C<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Bd(C,e.nByteLength)}function L(C,P,S=j){if(["recovered","canonical"].some(se=>se in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:k}=e,{lowS:I,prehash:K,extraEntropy:F}=S;I==null&&(I=!0),C=Wn("msgHash",C),K&&(C=Wn("prehashed msgHash",E(C)));let V=N(C),W=d(P),J=[z(W),z(V)];if(F!=null){let se=F===!0?k(t.BYTES):F;J.push(Wn("extraEntropy",se))}let Q=fh(...J),q=V;function ee(se){let ne=D(se);if(!f(ne))return;let X=c(ne),le=l.BASE.multiply(ne).toAffine(),ue=s(le.x);if(ue===Ul)return;let pe=s(X*s(q+ue*W));if(pe===Ul)return;let xe=(le.x===ue?0:2)|Number(le.y&Oa),de=pe;return I&&h(pe)&&(de=m(pe),xe^=1),new v(ue,de,xe)}return{seed:Q,k2sig:ee}}let j={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function Y(C,P,S=j){let{seed:E,k2sig:k}=L(C,P,S),I=e;return E7(I.hash.outputLen,I.nByteLength,I.hmac)(E,k)}l.BASE._setWindowSize(8);function R(C,P,S,E=H){let k=C;if(P=Wn("msgHash",P),S=Wn("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:K}=E,F,V;try{if(typeof k=="string"||$d(k))try{F=v.fromDER(k)}catch(X){if(!(X instanceof oh.Err))throw X;F=v.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:X,s:le}=k;F=new v(X,le)}else throw new Error("PARSE");V=l.fromHex(S)}catch(X){if(X.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&F.hasHighS())return!1;K&&(P=e.hash(P));let{r:W,s:J}=F,Q=N(P),q=c(J),ee=s(Q*q),se=s(W*q),ne=l.BASE.multiplyAndAddUnsafe(V,ee,se)?.toAffine();return ne?s(ne.x)===W:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:A,sign:Y,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function aue(r){return{hash:r,hmac:(e,...t)=>K7(r,e,A7(...t)),randomBytes:IC}}function N7(r,e){let t=n=>oue({...r,...aue(n)});return Object.freeze({...t(e),create:t})}function due(r){let e=U7,t=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),o=BigInt(23),s=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Sn(d,t,e)*d%e,f=Sn(u,t,e)*d%e,p=Sn(f,iC,e)*l%e,h=Sn(p,i,e)*p%e,m=Sn(h,a,e)*h%e,y=Sn(m,s,e)*m%e,v=Sn(y,c,e)*y%e,w=Sn(v,s,e)*m%e,x=Sn(w,t,e)*d%e,_=Sn(x,o,e)*h%e,A=Sn(_,n,e)*l%e,D=Sn(A,iC,e);if(!sC.eql(sC.sqr(D),r))throw new Error("Cannot find square root");return D}function lue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function L7(r,...e){if(!lue(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function tq(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function uue(r,e){L7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function fue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function q7(r){return typeof r=="string"&&(r=fue(r)),L7(r),r}function hue(r){let e=n=>r().update(q7(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function mue(r=32){if(E2&&typeof E2.getRandomValues=="function")return E2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function yue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),o=Number(t>>i&a),s=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+l,s,n)}function xue(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),a={};for(let o of i)a[o]=e(n[o]);return a}return n},t=e(r);return JSON.stringify(t)}function _r(r){return Sue(this,arguments,void 0,function*({jwk:e}){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);v7(n);let i=xue(n),a=st.string(i).toUint8Array(),o=yield z7.digest({data:a});return st.uint8Array(o).toBase64Url()})}function dh(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="EC"||typeof r.d!="string"||typeof r.x!="string")}function CC(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r)||"d"in r||r.kty!=="EC"||typeof r.x!="string")}function zl(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="OKP"||typeof r.d!="string"||typeof r.x!="string")}function $C(r){return!(!r||typeof r!="object"||"d"in r||!("kty"in r&&"crv"in r&&"x"in r)||r.kty!=="OKP"||typeof r.x!="string")}function kue(r){if(!r||typeof r!="object")return!1;switch(r.kty){case"EC":case"OKP":case"RSA":return"d"in r;case"oct":return"k"in r;default:return!1}}function G7(r,e=!1){return e?{h:Number(r&m2),l:Number(r>>oC&m2)}:{h:Number(r>>oC&m2)|0,l:Number(r&m2)|0}}function Rue(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:a,l:o}=G7(r[i],e);[t[i],n[i]]=[a,o]}return[t,n]}function Gue(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function ife(r){let e=RC(r);return mh(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function BC(r){let e=ife(r),{Fp:t,n,prehash:i,hash:a,randomBytes:o,nByteLength:s,h:c}=e,l=y2<<BigInt(s*8)-Vo,d=t.create,u=e.uvRatio||((S,E)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(E))}}catch{return{isValid:!1,value:_c}}}),f=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,k)=>{if(E.length||k)throw new Error("Contexts/pre-hash are not supported");return S}),h=S=>typeof S=="bigint"&&_c<S,m=(S,E)=>h(S)&&h(E)&&S<E,y=S=>S===_c||m(S,l);function v(S,E){if(m(S,E))return S;throw new Error(`Expected valid scalar < ${E}, got ${typeof S} ${S}`)}function w(S){return S===_c?S:v(S,n)}let x=new Map;function _(S){if(!(S instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(E,k,I,K){if(this.ex=E,this.ey=k,this.ez=I,this.et=K,!y(E))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(K))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof A)throw new Error("extended point not allowed");let{x:k,y:I}=E||{};if(!y(k)||!y(I))throw new Error("invalid affine point");return new A(k,I,Vo,d(k*I))}static normalizeZ(E){let k=t.invertBatch(E.map(I=>I.ez));return E.map((I,K)=>I.toAffine(k[K])).map(A.fromAffine)}_setWindowSize(E){this._WINDOW_SIZE=E,x.delete(this)}assertValidity(){let{a:E,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:K,ez:F,et:V}=this,W=d(I*I),J=d(K*K),Q=d(F*F),q=d(Q*Q),ee=d(W*E),se=d(Q*d(ee+J)),ne=d(q+d(k*d(W*J)));if(se!==ne)throw new Error("bad point: equation left != right (1)");let X=d(I*K),le=d(F*V);if(X!==le)throw new Error("bad point: equation left != right (2)")}equals(E){_(E);let{ex:k,ey:I,ez:K}=this,{ex:F,ey:V,ez:W}=E,J=d(k*W),Q=d(F*K),q=d(I*W),ee=d(V*K);return J===Q&&q===ee}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:E}=e,{ex:k,ey:I,ez:K}=this,F=d(k*k),V=d(I*I),W=d(y2*d(K*K)),J=d(E*F),Q=k+I,q=d(d(Q*Q)-F-V),ee=J+V,se=ee-W,ne=J-V,X=d(q*se),le=d(ee*ne),ue=d(q*ne),pe=d(se*ee);return new A(X,le,pe,ue)}add(E){_(E);let{a:k,d:I}=e,{ex:K,ey:F,ez:V,et:W}=this,{ex:J,ey:Q,ez:q,et:ee}=E;if(k===BigInt(-1)){let Bt=d((F-K)*(Q+J)),_e=d((F+K)*(Q-J)),at=d(_e-Bt);if(at===_c)return this.double();let It=d(V*y2*ee),$t=d(W*y2*q),Ht=$t+It,T=_e+Bt,M=$t-It,U=d(Ht*at),te=d(T*M),ce=d(Ht*M),ge=d(at*T);return new A(U,te,ge,ce)}let se=d(K*J),ne=d(F*Q),X=d(W*I*ee),le=d(V*q),ue=d((K+F)*(J+Q)-se-ne),pe=le-X,xe=le+X,de=d(ne-k*se),Pe=d(ue*pe),Ne=d(xe*de),He=d(ue*de),Je=d(pe*xe);return new A(Pe,Ne,Je,He)}subtract(E){return this.add(E.negate())}wNAF(E){return $.wNAFCached(this,x,E,A.normalizeZ)}multiply(E){let{p:k,f:I}=this.wNAF(v(E,n));return A.normalizeZ([k,I])[0]}multiplyUnsafe(E){let k=w(E);return k===_c?N:this.equals(N)||k===Vo?this:this.equals(D)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(E){let{ex:k,ey:I,ez:K}=this,F=this.is0();E==null&&(E=F?rfe:t.inv(K));let V=d(k*E),W=d(I*E),J=d(K*E);if(F)return{x:_c,y:Vo};if(J!==Vo)throw new Error("invZ was invalid");return{x:V,y:W}}clearCofactor(){let{h:E}=e;return E===Vo?this:this.multiplyUnsafe(E)}static fromHex(E,k=!1){let{d:I,a:K}=e,F=t.BYTES;E=Wn("pointHex",E,F);let V=E.slice(),W=E[F-1];V[F-1]=W&-129;let J=Pf(V);J===_c||(k?v(J,l):v(J,t.ORDER));let Q=d(J*J),q=d(Q-Vo),ee=d(I*Q-K),{isValid:se,value:ne}=u(q,ee);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let X=(ne&Vo)===Vo,le=(W&128)!==0;if(!k&&ne===_c&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==X&&(ne=d(-ne)),A.fromAffine({x:ne,y:J})}static fromPrivateKey(E){return j(E).point}toRawBytes(){let{x:E,y:k}=this.toAffine(),I=Vy(k,t.BYTES);return I[I.length-1]|=E&Vo?128:0,I}toHex(){return uh(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,Vo,d(e.Gx*e.Gy)),A.ZERO=new A(_c,Vo,Vo,_c);let{BASE:D,ZERO:N}=A,$=j7(A,s*8);function z(S){return Xr(S,n)}function L(S){return z(Pf(S))}function j(S){let E=s;S=Wn("private key",S,E);let k=Wn("hashed private key",a(S),2*E),I=f(k.slice(0,E)),K=k.slice(E,2*E),F=L(I),V=D.multiply(F),W=V.toRawBytes();return{head:I,prefix:K,scalar:F,point:V,pointBytes:W}}function H(S){return j(S).pointBytes}function Y(S=new Uint8Array,...E){let k=fh(...E);return L(a(p(k,Wn("context",S),!!i)))}function R(S,E,k={}){S=Wn("message",S),i&&(S=i(S));let{prefix:I,scalar:K,pointBytes:F}=j(E),V=Y(k.context,I,S),W=D.multiply(V).toRawBytes(),J=Y(k.context,W,F,S),Q=z(V+J*K);w(Q);let q=fh(W,Vy(Q,t.BYTES));return Wn("result",q,s*2)}let C=nfe;function P(S,E,k,I=C){let{context:K,zip215:F}=I,V=t.BYTES;S=Wn("signature",S,2*V),E=Wn("message",E),i&&(E=i(E));let W=Pf(S.slice(V,2*V)),J,Q,q;try{J=A.fromHex(k,F),Q=A.fromHex(S.slice(0,V),F),q=D.multiplyUnsafe(W)}catch{return!1}if(!F&&J.isSmallOrder())return!1;let ee=Y(K,Q.toRawBytes(),J.toRawBytes(),E);return Q.add(J.multiplyUnsafe(ee)).subtract(q).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:P,ExtendedPoint:A,utils:{getExtendedPublicKey:j,randomPrivateKey:()=>o(t.BYTES),precompute(S=8,E=A.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}function sfe(r){return mh(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function ofe(r){let e=sfe(r),{P:t}=e,n=x=>Xr(x,t),i=e.montgomeryBits,a=Math.ceil(i/8),o=e.nByteLength,s=e.adjustScalarBytes||(x=>x),c=e.powPminus2||(x=>C7(x,t-BigInt(2),t));function l(x,_,A){let D=n(x*(_-A));return _=n(_-D),A=n(A+D),[_,A]}function d(x){if(typeof x=="bigint"&&E0<=x&&x<t)return x;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(x,_){let A=d(x),D=d(_),N=A,$=WR,z=E0,L=A,j=WR,H=E0,Y;for(let C=BigInt(i-1);C>=E0;C--){let P=D>>C&WR;H^=P,Y=l(H,$,L),$=Y[0],L=Y[1],Y=l(H,z,j),z=Y[0],j=Y[1],H=P;let S=$+z,E=n(S*S),k=$-z,I=n(k*k),K=E-I,F=L+j,V=L-j,W=n(V*S),J=n(F*k),Q=W+J,q=W-J;L=n(Q*Q),j=n(N*n(q*q)),$=n(E*I),z=n(K*(E+n(u*K)))}Y=l(H,$,L),$=Y[0],L=Y[1],Y=l(H,z,j),z=Y[0],j=Y[1];let R=c(z);return n($*R)}function p(x){return Vy(n(x),a)}function h(x){let _=Wn("u coordinate",x,a);return o===32&&(_[31]&=127),Pf(_)}function m(x){let _=Wn("scalar",x),A=_.length;if(A!==a&&A!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${A}`);return Pf(s(_))}function y(x,_){let A=h(_),D=m(x),N=f(A,D);if(N===E0)throw new Error("Invalid private or public key received");return p(N)}let v=p(e.Gu);function w(x){return y(x,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(x,_)=>y(x,_),getPublicKey:x=>w(x),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function V7(r){let e=W0,t=r*r%e*r%e,n=Sn(t,aC,e)*t%e,i=Sn(n,afe,e)*r%e,a=Sn(i,cfe,e)*i%e,o=Sn(a,sq,e)*a%e,s=Sn(o,dfe,e)*o%e,c=Sn(s,lfe,e)*s%e,l=Sn(c,oq,e)*c%e,d=Sn(l,oq,e)*c%e,u=Sn(d,sq,e)*a%e;return{pow_p_5_8:Sn(u,aC,e)*r%e,b2:t}}function W7(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ufe(r,e){let t=W0,n=Xr(e*e*e,t),i=Xr(n*n*e,t),a=V7(r*i).pow_p_5_8,o=Xr(r*n*a,t),s=Xr(e*o*o,t),c=o,l=Xr(o*iq,t),d=s===r,u=s===Xr(-r,t),f=s===Xr(-r*iq,t);return d&&(o=c),(u||f)&&(o=l),Vle(o,t)&&(o=Xr(-o,t)),{isValid:d||u,value:o}}function J7(r,e,t){if(e.length>255)throw new Error("Context is too big");return A7(_7("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function ffe(r){let{y:e}=th.ExtendedPoint.fromHex(r),t=BigInt(1);return Na.toBytes(Na.create((t+e)*Na.inv(t-e)))}function pfe(r){let e=J0.hash(r.subarray(0,32));return J0.adjustScalarBytes(e).subarray(0,32)}function Efe(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(r)?"Array":r instanceof Uint8Array?"Uint8Array":r.constructor===Object?"Object":Sfe(r)||"Object"}function Sfe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(xfe.includes(e))return e}function G2(r){return tb&&globalThis.Buffer.isBuffer(r)}function Z7(r){return r instanceof Uint8Array?G2(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function Y7(r,e){if(G2(r)&&G2(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function aq(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function Xy(r,e,t){if(r.length-e<t)throw new Error(`${kn} not enough data for type`)}function yh(r,e,t){Xy(r,e,1);let n=r[e];if(t.strict===!0&&n<ss[0])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function gh(r,e,t){Xy(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ss[1])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function wh(r,e,t){Xy(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ss[2])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function vh(r,e,t){Xy(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&a<ss[3])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(t.allowBigInt===!0)return a;throw new Error(`${kn} integers outside of the safe integer range are not supported`)}function Bfe(r,e,t,n){return new tt(Se.uint,yh(r,e+1,n),2)}function Ofe(r,e,t,n){return new tt(Se.uint,gh(r,e+1,n),3)}function jfe(r,e,t,n){return new tt(Se.uint,wh(r,e+1,n),5)}function Mfe(r,e,t,n){return new tt(Se.uint,vh(r,e+1,n),9)}function bh(r,e){return La(r,0,e.value)}function La(r,e,t){if(t<ss[0]){let n=Number(t);r.push([e|n])}else if(t<ss[1]){let n=Number(t);r.push([e|24,n])}else if(t<ss[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ss[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ss[4]){let i=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=a&255,a=a>>8,i[7]=a&255,a=a>>8,i[6]=a&255,a=a>>8,i[5]=a&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${kn} encountered BigInt larger than allowable range`)}}function Kfe(r,e,t,n){return new tt(Se.negint,-1-yh(r,e+1,n),2)}function Nfe(r,e,t,n){return new tt(Se.negint,-1-gh(r,e+1,n),3)}function Ufe(r,e,t,n){return new tt(Se.negint,-1-wh(r,e+1,n),5)}function Lfe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new tt(Se.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${kn} integers outside of the safe integer range are not supported`);return new tt(Se.negint,OC-BigInt(i),9)}function jC(r,e){let t=e.value,n=typeof t=="bigint"?t*OC-ez:t*-1-1;La(r,e.type.majorEncoded,n)}function nb(r,e,t,n){Xy(r,e,t+n);let i=r.slice(e+t,e+t+n);return new tt(Se.bytes,i,t+n)}function qfe(r,e,t,n){return nb(r,e,1,t)}function zfe(r,e,t,n){return nb(r,e,2,yh(r,e+1,n))}function Ffe(r,e,t,n){return nb(r,e,3,gh(r,e+1,n))}function Gfe(r,e,t,n){return nb(r,e,5,wh(r,e+1,n))}function Hfe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer bytes lengths not supported`);return nb(r,e,9,i)}function H2(r){return r.encodedBytes===void 0&&(r.encodedBytes=Se.equals(r.type,Se.string)?Tfe(r.value):r.value),r.encodedBytes}function iE(r,e){let t=H2(e);La(r,e.type.majorEncoded,t.length),r.push(t)}function Vfe(r,e){return r.length<e.length?-1:r.length>e.length?1:Y7(r,e)}function Jfe(r,e,t){if(t-e<Wfe){let n="";for(let i=e;i<t;i++){let a=r[i];if(a&128)return cq.decode(r.subarray(e,t));n+=String.fromCharCode(a)}return n}return cq.decode(r.subarray(e,t))}function ib(r,e,t,n,i){let a=t+n;Xy(r,e,a);let o=new tt(Se.string,Jfe(r,e+t,e+a),a);return i.retainStringBytes===!0&&(o.byteValue=r.slice(e+t,e+a)),o}function Zfe(r,e,t,n){return ib(r,e,1,t,n)}function Yfe(r,e,t,n){return ib(r,e,2,yh(r,e+1,n),n)}function Xfe(r,e,t,n){return ib(r,e,3,gh(r,e+1,n),n)}function Qfe(r,e,t,n){return ib(r,e,5,wh(r,e+1,n),n)}function epe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer string lengths not supported`);return ib(r,e,9,i,n)}function Qy(r,e,t,n){return new tt(Se.array,n,t)}function rpe(r,e,t,n){return Qy(r,e,1,t)}function npe(r,e,t,n){return Qy(r,e,2,yh(r,e+1,n))}function ipe(r,e,t,n){return Qy(r,e,3,gh(r,e+1,n))}function spe(r,e,t,n){return Qy(r,e,5,wh(r,e+1,n))}function ope(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer array lengths not supported`);return Qy(r,e,9,i)}function ape(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Qy(r,e,1,1/0)}function MC(r,e){La(r,Se.array.majorEncoded,e.value)}function eg(r,e,t,n){return new tt(Se.map,n,t)}function cpe(r,e,t,n){return eg(r,e,1,t)}function dpe(r,e,t,n){return eg(r,e,2,yh(r,e+1,n))}function lpe(r,e,t,n){return eg(r,e,3,gh(r,e+1,n))}function upe(r,e,t,n){return eg(r,e,5,wh(r,e+1,n))}function fpe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer map lengths not supported`);return eg(r,e,9,i)}function ppe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return eg(r,e,1,1/0)}function KC(r,e){La(r,Se.map.majorEncoded,e.value)}function hpe(r,e,t,n){return new tt(Se.tag,t,1)}function mpe(r,e,t,n){return new tt(Se.tag,yh(r,e+1,n),2)}function ype(r,e,t,n){return new tt(Se.tag,gh(r,e+1,n),3)}function gpe(r,e,t,n){return new tt(Se.tag,wh(r,e+1,n),5)}function wpe(r,e,t,n){return new tt(Se.tag,vh(r,e+1,n),9)}function NC(r,e){La(r,Se.tag.majorEncoded,e.value)}function vpe(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${kn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new tt(Se.null,null,1):new tt(Se.undefined,void 0,1)}function bpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return new tt(Se.break,void 0,1)}function UC(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${kn} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${kn} Infinity values are not supported`)}return new tt(Se.float,r,e)}function Ppe(r,e,t,n){return UC(qC(r,e+1),3,n)}function xpe(r,e,t,n){return UC(zC(r,e+1),5,n)}function Epe(r,e,t,n){return UC(cz(r,e+1),9,n)}function LC(r,e,t){let n=e.value;if(n===!1)r.push([Se.float.majorEncoded|tz]);else if(n===!0)r.push([Se.float.majorEncoded|rz]);else if(n===null)r.push([Se.float.majorEncoded|nz]);else if(n===void 0)r.push([Se.float.majorEncoded|iz]);else{let i,a=!1;(!t||t.float64!==!0)&&(oz(n),i=qC(Ac,1),n===i||Number.isNaN(n)?(Ac[0]=249,r.push(Ac.slice(0,3)),a=!0):(az(n),i=zC(Ac,1),n===i&&(Ac[0]=250,r.push(Ac.slice(0,5)),a=!0))),a||(Spe(n),i=cz(Ac,1),Ac[0]=251,r.push(Ac.slice(0,9)))}}function oz(r){if(r===1/0)$a.setUint16(0,31744,!1);else if(r===-1/0)$a.setUint16(0,64512,!1);else if(Number.isNaN(r))$a.setUint16(0,32256,!1);else{$a.setFloat32(0,r);let e=$a.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)$a.setUint16(0,31744,!1);else if(t===0)$a.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?$a.setUint16(0,0):i<-14?$a.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$a.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function qC(r,e){if(r.length-e<2)throw new Error(`${kn} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,t&32768?-a:a}function az(r){$a.setFloat32(0,r,!1)}function zC(r,e){if(r.length-e<4)throw new Error(`${kn} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Spe(r){$a.setFloat64(0,r,!1)}function cz(r,e){if(r.length-e<8)throw new Error(`${kn} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function yr(r,e,t){throw new Error(`${kn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function sE(r){return()=>{throw new Error(`${kn} ${r}`)}}function kpe(r){switch(r.type){case Se.false:return Kl([244]);case Se.true:return Kl([245]);case Se.null:return Kl([246]);case Se.bytes:return r.value.length?void 0:Kl([64]);case Se.string:return r.value===""?Kl([96]):void 0;case Se.array:return r.value===0?Kl([128]):void 0;case Se.map:return r.value===0?Kl([160]):void 0;case Se.uint:return r.value<24?Kl([Number(r.value)]):void 0;case Se.negint:if(r.value>=-24)return Kl([31-Number(r.value)])}}function Ape(){let r=[];return r[Se.uint.major]=bh,r[Se.negint.major]=jC,r[Se.bytes.major]=iE,r[Se.string.major]=tpe,r[Se.array.major]=MC,r[Se.map.major]=KC,r[Se.tag.major]=NC,r[Se.float.major]=LC,r}function S2(r,e={},t){let n=Efe(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Ef[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let a=Ef[n];if(!a)throw new Error(`${Q7} unsupported type: ${n}`);return a(r,n,e,t)}function Dpe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Rpe(r,e){if(r[0]instanceof tt&&e[0]instanceof tt){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=lq(t.value)),n._keyBytes||(n._keyBytes=lq(n.value)),Y7(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function lq(r){return Cpe(r,Tpe,_pe)}function lz(r,e,t,n){if(Array.isArray(e))for(let i of e)lz(r,i,t,n);else t[e.type.major](r,e,n)}function Cpe(r,e,t,n){let i=n instanceof Uint8Array,a=i?new $fe(n):Ipe,o=S2(r,t);if(!Array.isArray(o)&&t.quickEncodeToken){let s=t.quickEncodeToken(o);if(s)return i?(a.push(s),a.toBytes()):s;let c=e[o.type.major];if(c.encodedSize){let l=c.encodedSize(o,t);if(i||(a=new X7(l)),c(a,o,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return i?a.toBytes():Z7(a.chunks[0])}}return a.reset(),lz(a,o,e,t),a.toBytes(!0)}function Zs(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function $pe({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function Bpe({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=oE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await _r({jwk:e})===await _r({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function oE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(V2)??[]),Object.keys(tE).forEach(t=>{e.push(...r[t]?.filter(V2)??[])}),e}function uz({didDocument:r}){let e=oE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function fz({didDocument:r,methodId:e}){let t=[];return Object.keys(tE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],a=Zs(e);i.some(o=>{let s=Zs(o)===a,c=V2(o)&&Zs(o.id)===a;return s||c})&&t.push(n)}}),t}function pz(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function Ope(r){return!(!pz(r)||r.type!=="DecentralizedWebNode")}function V2(r){return!(!r||typeof r!="object"||r===null||!("id"in r&&"type"in r&&"controller"in r)||typeof r.id!="string"||typeof r.type!="string"||typeof r.controller!="string")}function Ph(r){return!(!r||typeof r!="object"||r===null)&&"uri"in r&&"document"in r&&"metadata"in r&&(!("keyManager"in r)||r.keyManager===void 0)}function hz({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=Ua.addPrefix({code:e,data:r,name:t}),i=st.uint8Array(n).toBase58Btc();return st.base58Btc(i).toMultibase()}function mz({multibaseKeyId:r}){try{let e=st.multibase(r).toBase58Btc(),t=st.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Ua.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new nt("invalidDid",`Invalid multibase identifier: ${r}`)}}function ob(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function Pz(r){return ArrayBuffer.isView(r)?"arraybufferview":Array.isArray(r)?"array":r instanceof Number?"number":r instanceof Boolean?"boolean":r instanceof Set?"set":r instanceof Map?"map":r instanceof String?"string":r instanceof ArrayBuffer?"arraybuffer":typeof r}function br(r,e,t){let n=[],i=null;return br._encode(n,r),i=Mpe(n),br.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function Sz(r,e,t){let n=0,i=1;for(let a=e;a<t;a++){let o=r[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){i=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*i}function bt(r,e,t,n){return r==null||r.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof t!="number"&&n==null&&(n=t,t=void 0),bt.position=0,bt.encoding=n||null,bt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):Fl(r),bt.bytes=bt.data.length,bt.next())}function Vpe(r){let e=2;for(let t of r)e+=cE(t);return e}function Wpe(r){let e=2;for(let[t,n]of r){let i=Fl(t).byteLength;e+=ob(i)+1+i,e+=cE(n)}return e}function Jpe(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=Fl(t[n]).byteLength;e+=ob(i)+1+i,e+=cE(r[t[n]])}return e}function Zpe(r){let e=Fl(r).byteLength;return ob(e)+1+e}function Ype(r){let e=r.byteLength-r.byteOffset;return ob(e)+1+e}function cE(r){if(r==null)return 0;let e=Pz(r);switch(e){case"arraybufferview":return Ype(r);case"string":return Zpe(r);case"array":case"set":return Vpe(r);case"number":return 1+ob(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Jpe(r);case"map":return Wpe(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function Az(r){if(Cd.isFormat(r))return Cd.size;if(xf.isFormat(r))return xf.size;throw Error(`Invalid ip address: ${r}`)}function the(r){return Az(r)===Cd.size?1:2}function rhe(r,e,t){t=~~t;let n=Az(r);return typeof e=="function"&&(e=e(t+n)),n===Cd.size?Cd.encode(r,e,t):xf.encode(r,e,t)}function nhe(r,e,t){if(e=~~e,t=t||r.length-e,t===Cd.size)return Cd.decode(r,e,t);if(t===xf.size)return xf.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${Cd.size} for v4 or ${xf.size} for v6.`)}function dE(r){switch(r){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+r}function Z0(r){switch(r.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}function ihe(r){switch(r){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+r}function she(r){switch(r){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+r}function Tz(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r}function Iz(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function ohe(r){switch(r){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return r<0?null:`OPTION_${r}`}function Eq(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function Dz(r){let e=0,t=r.length;for(let n=0;n<t;n+=1){let i=r.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let a=n+1;a===t||i>=56320||(r.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Y0(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(Dz(r)+t));let i=t;for(let a=0;a<n;a+=1){let o=r.charCodeAt(a);if(o<=127)e[i++]=o;else if(o<=2047)e[i++]=192|(o&1984)>>6,e[i++]=128|o&63;else if((o&63488)!==55296)e[i++]=224|(o&61440)>>12,e[i++]=128|(o&4032)>>6,e[i++]=128|o&63;else{let s=a+1;if(s===n||o>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let c=r.charCodeAt(s);(c&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=s,o=65536|(o&1023)<<10|c&1023,e[i++]=240|(o&1835008)>>18,e[i++]=128|(o&258048)>>12,e[i++]=128|(o&4032)>>6,e[i++]=128|o&63)}}}return Y0.bytes=i-t,e}function ab(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let a=r[i++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|r[i++]&63;else if(a>239&&a<365){o=((a&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let s=55296|o>>10&1023;n+=String.fromCharCode(s),o=56320|o&1023}else o=(a&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(o)}return ab.bytes=t-e,n}function Sf(r){return typeof r=="string"?Dz(r):r.byteLength}function VC(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):Y0(r)}function WC(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return Y0(e,r,t),Y0.bytes}function ahe(r,e,t){let n="";for(let i=e;i<t;){let a=r[i++];n+=Rz[a]}return n}function Sq(r){return r.length>>>1}function che(r,e,t,n){let i=0;for(;t<n;){let a=e.substr(i,2),o=R0[a];if(o===void 0)return;r[t++]=o,i+=2}return r}function Xo(r,e,t,n,i){return t<0&&(n-=t,t=0),n<0&&(n=0),i<0?new Uint8Array(0):t>=e.length||n>=i?0:fhe(r,e,t,n,i)}function fhe(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let a=i-n,o=r.length-n;return a>o&&(a=o),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,a)),e.set(r,t),a}function Hr({bytes:r=0,encode:e,decode:t,encodingLength:n}){return e.bytes=r,t.bytes=r,{encode:e,decode:t,encodingLength:n||(()=>r)}}function lC(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function ZR(r){switch(r.toUpperCase()){case"A":return $z;case"PTR":return zy;case"CNAME":return zy;case"DNAME":return zy;case"TXT":return T2;case"NULL":return I2;case"AAAA":return $2;case"SRV":return R2;case"HINFO":return D2;case"CAA":return vf;case"NS":return _2;case"SOA":return A2;case"MX":return C2;case"OPT":return bf;case"DNSKEY":return Rd;case"RRSIG":return C0;case"RP":return $0;case"NSEC":return B0;case"NSEC3":return O0;case"SSHFP":return Uy;case"DS":return j0}return k2}function W2(r,e){if(r.questions)throw new Error("Only one .question object expected instead of a .questions array!");let t=Object.assign({type:e},r);return t.question&&(t.questions=[t.question],delete t.question),t}function Bz(r){let e=Y2(r),t=new Uint8Array(2+e.byteLength);return ot(t,e.byteLength),Xo(e,t,2,0,e.length),Bz.bytes=t.byteLength,t}function Oz(r){let e=qt(r,0);if(r.byteLength<e+2)return null;let t=uC(r.slice(2));return Oz.bytes=uC.bytes,t}function Ly(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function M0(r,e,t,n){for(let i=0;i<r.length;i++)e.encode(r[i],t,n),n+=e.encode.bytes;return n}function g2(r,e,t,n){for(let i=0;i<r.length;i++)r[i]=e.decode(t,n),n+=e.decode.bytes;return n}function jz(r,e){let t=st.uint8Array(r).toBase32Z();return new URL(t,e).href}async function whe({gatewayUri:r,publicKeyBytes:e}){let t=st.uint8Array(e).toBase32Z(),n=jz(e,r),i;try{if(i=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!i.ok)throw new nt("notFound",`Pkarr record not found for: ${t}`)}catch(o){throw o instanceof nt?o:new nt("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await i.arrayBuffer();if(!a)throw new nt("notFound",`Pkarr record not found for: ${t}`);if(a.byteLength<72)throw new nt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new nt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function vhe({gatewayUri:r,bep44Message:e}){let t=st.uint8Array(e.k).toBase32Z(),n=jz(e.k,r),i=new Uint8Array(e.v.length+72);i.set(e.sig,0),new DataView(i.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),i.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:i,signal:AbortSignal.timeout(3e4)})}catch(o){throw new nt("internalError",`Failed to put Pkarr record for identifier ${t}: ${o.message}`)}return a.ok}async function bhe({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=Y2(r),a=_z.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new nt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await t.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:i}}async function Phe({bep44Message:r}){let e=await is.bytesToPublicKey({publicKeyBytes:r.k}),t=_z.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await is.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new nt("invalidSignature","Invalid signature for DHT BEP44 message");return uC(r.v)}async function Kz({didUri:r}){let e=JC({didUri:r});return await is.bytesToPublicKey({publicKeyBytes:e})}function JC({didUri:r}){let e=Jn.parse(r);if(!e)throw new nt("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==Mz)throw new nt("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=st.base32Z(e.id).toUint8Array()}catch{throw new nt("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new nt("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function xhe({identityKey:r}){let e=await is.publicKeyToBytes({publicKey:r}),t=st.uint8Array(e).toBase32Z();return`did:${Mz}:${t}`}function ZC(r){let e={Ed25519:is,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await xs.publicKeyToBytes({publicKey:t});return await xs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:xs.bytesToPublicKey,privateKeyToBytes:xs.privateKeyToBytes,bytesToPrivateKey:xs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await ns.publicKeyToBytes({publicKey:t});return await ns.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ns.bytesToPublicKey,privateKeyToBytes:ns.privateKeyToBytes,bytesToPrivateKey:ns.bytesToPrivateKey},X25519:Oy}[r];if(!e)throw new nt("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function Nz({newDid:r,previousDidProof:e}){let t=await Kz({didUri:e.previousDid}),n=JC({didUri:r}),i=st.base64Url(e.signature).toUint8Array();if(!await is.verify({key:t,data:n,signature:i}))throw new nt("invalidPreviousDidProof","The previous DID proof is invalid.")}function X0(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return st.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>X0(e)).join("");throw new nt("internalError","Pkarr returned DNS TXT record with invalid data type")}function K0(r){return X0(r).split(B2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function qz(r){if(r.length<=255)return r;let e=[];for(let t=0;t<r.length;t+=255)e.push(r.slice(t,t+255));return e}async function She({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let s=X0(a.data);t.alsoKnownAs=s.split(Js);break}case o.startsWith("cnt"):{let s=X0(a.data);t.controller=s.includes(Js)?s.split(Js):s;break}case o.startsWith("k"):{let{id:s,t:c,k:l,c:d,a:u}=K0(a.data),f=st.base64Url(l).toUint8Array(),p=GC[Number(c)],h=await ZC(p).bytesToPublicKey({publicKeyBytes:f});h.alg=u||Lz[Number(c)];let m=o==="k0"?"0":s!==void 0?s:await _r({jwk:h});t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??r,publicKeyJwk:h}),i.set(o,y);break}case o.startsWith("s"):{let{id:s,t:c,se:l,...d}=K0(a.data),u=l.includes(Js)?l.split(Js):[l],f=Object.fromEntries(Object.entries(d).map(([p,h])=>[p,h.includes(Js)?h.split(Js):h]));t.service??=[],t.service.push({...f,id:`${r}#${s}`,type:c,serviceEndpoint:u});break}case o.startsWith("typ"):{let{id:s}=K0(a.data);n.types=s.split(Js).map(c=>Number(c));break}case o.startsWith("did"):{let s=p=>p.split(Js).map(h=>i.get(h)).filter(h=>typeof h=="string"),{auth:c,asm:l,del:d,inv:u,agm:f}=K0(a.data);c&&(t.authentication=s(c)),l&&(t.assertionMethod=s(l)),d&&(t.capabilityDelegation=s(d)),u&&(t.capabilityInvocation=s(u)),f&&(t.keyAgreement=s(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function khe({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],a=[],o=new Map,s=[],c=[];if(n!==void 0){let{signature:d,previousDid:u}=n;await Nz({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:mf,data:`id=${u};s=${d}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:mf,data:r.alsoKnownAs.join(Js)}),r.controller){let d=Array.isArray(r.controller)?r.controller.join(Js):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:mf,data:d})}for(let[d,u]of r.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let p=u.id.split("#").pop();o.set(p,f);let h=u.publicKeyJwk;if(!(h?.crv&&h.crv in Uz))throw new nt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${h?.crv??"undefined"}`);let m=GC[h.crv],y=await ZC(h.crv).publicKeyToBytes({publicKey:h}),v=st.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];p!=="0"&&await _r({jwk:h})!==p&&w.unshift(`id=${p}`),h.alg!==Lz[m]&&w.push(`a=${h.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:mf,data:w.join(B2)})}r.service?.forEach((d,u)=>{let f=`s${u}`;s.push(f);let{id:p,type:h,serviceEndpoint:m,...y}=d;p=Zs(p),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:p,t:h,se:m,...y}).map(([x,_])=>`${x}=${_}`).join(B2),w=qz(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:mf,data:w})});let l=[`v=${Ehe}`];if(c.length&&l.push(`vm=${c.join(Js)}`),Object.keys(tE).forEach(d=>{let u=r[d]?.map(f=>o.get(f.split("#").pop()));if(u){let f=wz[d];l.push(`${f}=${u.join(Js)}`)}}),s.length&&l.push(`svc=${s.join(Js)}`),e.types?.length){let d=e.types.map(u=>typeof u=="string"?gz[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:mf,data:`id=${d.join(Js)}`})}i.push({type:"TXT",name:"_did."+Aq(r.id)+".",ttl:mf,data:l.join(B2)});for(let d of t||[])a.push({type:"NS",name:"_did."+Aq(r.id)+".",ttl:mf,data:d+"."});return{id:0,type:"response",flags:yhe,answers:[...i,...a]}}function Aq(r){return r.split(":")[2]}function Gz(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nhe;)e[t++]=r&255|Rq,r/=128;for(;r&Khe;)e[t++]=r&255|Rq,r>>>=7;return e[t]=r|0,Gz.bytes=t-n+1,e}function mC(r,n){var t=0,n=n||0,i=0,a=n,o,s=r.length;do{if(a>=s)throw mC.bytes=0,new RangeError("Could not decode varint");o=r[a++],t+=i<28?(o&Cq)<<i:(o&Cq)*Math.pow(2,i),i+=7}while(o>=Lhe);return mC.bytes=a-n,t}function pme(r){r=n6(r);let e=Gy+8;(r.length<e||r.length>1024)&&Ii("expected proper params");let t=et(pE(r),r6-1n)+1n;return s6(t)}function Eme(r){let e=r.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let t=e.split(".");if(t.length===4){let i=t.map(Number);if(i.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=i;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var cde,bC,dde,lde,ude,fde,er,PC,pde,hh,hde,mde,Od,yde,gde,xC,r7,n7,i7,wde,vde,bde,Pde,eE,EC,ah,xde,Ede,s7,Sde,kde,o7,_de,Ade,Tde,N9,a7,Ide,c7,d7,Dde,Rde,Cde,l7,$de,Bde,u7,tE,Di,ts,Jn,nt,Ode,Ka,wo,jde,Kde,Nde,Ude,KNe,Lde,SC,qde,zde,Fde,m7,Gde,y7,g7,Hde,Vde,Qo,x2,NNe,UNe,LNe,qNe,zNe,FNe,GNe,U9,ja,HNe,VNe,WNe,$l,JNe,P0,L9,h2,eh,st,z0,Zde,Yde,T0,Xde,q9,Qde,ele,tle,rle,nle,z9,ile,sle,ole,ale,cle,dle,lle,ule,fle,ple,hle,mle,q2,z2,G0,H0,yle,gle,wle,kC,F9,G9,tC,ZNe,vle,ble,Ple,x0,xle,H9,Ele,Ua,YNe,of,Sle,rE,b7,P7,nE,kle,_le,Bl,Cle,AC,zR,W9,$le,FR,GR,kd,Mle,T7,XNe,D7,Nle,Ule,Lle,af,cf,qle,R7,yi,gn,nh,zle,rC,Z9,Y9,QNe,Fle,Vle,Wle,eue,HR,rue,nue,oh,Ul,Oa,eUe,X9,tUe,M7,K7,U7,Q9,cue,iC,eq,sC,Jo,rUe,nUe,E2,VR,_d,iUe,pue,sUe,gue,wue,vue,bue,df,lf,Pue,V0,Eue,z7,Sue,rq,Qi,_ue,ns,F7,Aue,Tue,Iue,Da,es,Due,xs,Ol,nq,m2,oC,Cue,$ue,Bue,Oue,jue,Mue,Kue,Nue,Uue,Lue,que,zue,Fue,Hue,Vue,Wue,Jue,Zue,Yue,Xue,Lt,Que,efe,uf,ff,tfe,H7,_c,Vo,y2,rfe,nfe,E0,WR,W0,iq,oUe,afe,aC,cfe,sq,dfe,lfe,oq,Na,J0,th,aUe,cUe,I0,hfe,dUe,lUe,uUe,fUe,pUe,hUe,mUe,yUe,gUe,wUe,Ra,mfe,is,jl,yfe,gfe,wfe,pf,vfe,Oy,S0,bfe,Ml,JR,Ic,Pfe,xfe,Se,tt,tb,kfe,_fe,Afe,Tfe,Kl,Ife,Dfe,Rfe,Cfe,X7,$fe,kn,Q7,rb,ss,OC,ez,cq,Wfe,tpe,tz,rz,nz,iz,sz,$a,Ac,je,Gl,_pe,Tpe,Ipe,dq,hf,Ef,vUe,bUe,PUe,xUe,EUe,SUe,kUe,_Ue,AUe,TUe,IUe,DUe,RUe,uq,Es,Ma,fq,pq,CUe,$Ue,BUe,OUe,hq,mq,yq,gq,FC,Ss,sb,gz,GC,wz,wq,vz,vq,jpe,Mpe,bq,Kpe,k0,Npe,bz,Upe,Fl,Pq,xq,jUe,aE,xz,Ez,Lpe,qpe,zpe,Fpe,Gpe,HC,Hpe,kz,Xpe,_z,Qpe,ehe,Cd,xf,ph,R0,Rz,dhe,lhe,uhe,Ll,qt,ql,ot,phe,kq,dC,hhe,Cz,mhe,Ze,mi,jy,k2,_2,A2,T2,I2,D2,zy,R2,vf,C2,$z,$2,_q,Nl,bf,Rd,C0,$0,Yo,B0,O0,j0,Uy,Ba,Fy,yhe,os,J2,Z2,Y2,uC,ghe,Mz,Ehe,mf,B2,Js,Uz,Lz,Tq,zz,vo,Iq,qy,Hn,Vn,MUe,_he,Ahe,The,Ihe,Fz,Dhe,Rhe,Che,$he,lE,KUe,NUe,Dq,UUe,Wy,Bhe,pC,Dd,Wo,YC,Tc,Ohe,Q0,jhe,Rq,Mhe,Khe,Nhe,Uhe,Lhe,Cq,qhe,zhe,Fhe,Ghe,Hhe,Vhe,Whe,Jhe,Zhe,Yhe,Xhe,Qhe,X2,$q,Bq,Oq,jq,eme,Hz,Vz,tme,Wz,Mq,LUe,_0,Zo,yC,w2,gC,By,v2,Jz,Kq,rme,rs,j2,wC,vC,b2,go,Yz,XC,Jy,nme,lt,Nq,Uq,Zy,Q2,M2,Xz,QC,e6,ime,sme,Lq,Qz,Ad,ome,qq,ame,YR,zq,cme,ih,dme,lme,t6,lh,r6,eF,tF,rF,Gy,Fq,Ii,uE,nF,XR,iF,sF,eb,n6,et,Gq,Hq,Yy,F0,K2,oF,i6,fE,pE,Vq,s6,Wq,Jq,aF,ume,fme,Zq,N2,hme,sh,mme,yme,Yq,Xq,A0,gme,wme,Qq,vme,cF,bo,bme,U2,P2,Pme,e7,dF,cb,xme,lF,uF,Sme,kme,hE,_me,mE,Ame,tg,ea=G(()=>{"use strict";g();cde=Object.create,bC=Object.defineProperty,dde=Object.getOwnPropertyDescriptor,lde=Object.getOwnPropertyNames,ude=Object.getPrototypeOf,fde=Object.prototype.hasOwnProperty,er=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),PC=(r,e)=>{for(var t in e)bC(r,t,{get:e[t],enumerable:!0})},pde=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of lde(e))!fde.call(r,i)&&i!==t&&bC(r,i,{get:()=>e[i],enumerable:!(n=dde(e,i))||n.enumerable});return r},hh=(r,e,t)=>(t=r!=null?cde(ude(r)):{},pde(e||!r||!r.__esModule?bC(t,"default",{value:r,enumerable:!0}):t,r)),hde=er((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),a=s=>s===1/0||i(s),o=class t7{constructor({max:c=1/0,ttl:l,updateAgeOnGet:d=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:p,noDisposeOnSet:h=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!a(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!h,p!==void 0){if(typeof p!="function")throw new TypeError("dispose must be function if set");this.dispose=p}this.timer=void 0,this.timerExpiration=void 0}setTimer(c,l){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==t7.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,d]of c)this.dispose(d,l,"delete")}setTTL(c,l=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let u=this.expirations[d];!u||u.length<=1?delete this.expirations[d]:this.expirations[d]=u.filter(f=>f!==c)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(c,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(c)}else this.expirationMap.set(c,1/0)}set(c,l,{ttl:d=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){u||this.setTTL(c,d);let p=this.data.get(c);p!==l&&(this.data.set(c,l),f||this.dispose(p,c,"set"))}else this.setTTL(c,d),this.data.set(c,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let l=this.expirationMap.get(c);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(c,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(c);if(u&&this.getRemainingTTL(c)===0){this.delete(c);return}return l&&this.setTTL(c,d),f}dispose(c,l){}delete(c){let l=this.expirationMap.get(c);if(l!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let l=this.expirations[c];if(this.size-l.length>=this.max){delete this.expirations[c];let d=[];for(let u of l)d.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of d)this.dispose(f,u,"evict")}else{let d=this.size-this.max,u=[];for(let f of l.splice(0,d))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>c)return;let d=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of d)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let l of this.expirations[c])yield[l,this.data.get(l)]}*keys(){for(let c in this.expirations)for(let l of this.expirations[c])yield l}*values(){for(let c in this.expirations)for(let l of this.expirations[c])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=o}),mde=er(r=>{"use strict";r.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}}),Od=er((r,e)=>{"use strict";e.exports=class extends Error{constructor(t,n){super(t||""),typeof n=="object"&&n!==null&&(n.code&&(this.code=String(n.code)),n.expected&&(this.expected=!0),n.transient&&(this.transient=!0),n.cause&&(this.cause=n.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}}),yde=er(r=>{"use strict";r.byteLength=c,r.toByteArray=d,r.fromByteArray=p;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=i.length;a<o;++a)e[a]=i[a],t[i.charCodeAt(a)]=a;var a,o;t[45]=62,t[95]=63;function s(h){var m=h.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=h.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function c(h){var m=s(h),y=m[0],v=m[1];return(y+v)*3/4-v}function l(h,m,y){return(m+y)*3/4-y}function d(h){var m,y=s(h),v=y[0],w=y[1],x=new n(l(h,v,w)),_=0,A=w>0?v-4:v,D;for(D=0;D<A;D+=4)m=t[h.charCodeAt(D)]<<18|t[h.charCodeAt(D+1)]<<12|t[h.charCodeAt(D+2)]<<6|t[h.charCodeAt(D+3)],x[_++]=m>>16&255,x[_++]=m>>8&255,x[_++]=m&255;return w===2&&(m=t[h.charCodeAt(D)]<<2|t[h.charCodeAt(D+1)]>>4,x[_++]=m&255),w===1&&(m=t[h.charCodeAt(D)]<<10|t[h.charCodeAt(D+1)]<<4|t[h.charCodeAt(D+2)]>>2,x[_++]=m>>8&255,x[_++]=m&255),x}function u(h){return e[h>>18&63]+e[h>>12&63]+e[h>>6&63]+e[h&63]}function f(h,m,y){for(var v,w=[],x=m;x<y;x+=3)v=(h[x]<<16&16711680)+(h[x+1]<<8&65280)+(h[x+2]&255),w.push(u(v));return w.join("")}function p(h){for(var m,y=h.length,v=y%3,w=[],x=16383,_=0,A=y-v;_<A;_+=x)w.push(f(h,_,_+x>A?A:_+x));return v===1?(m=h[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(h[y-2]<<8)+h[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),gde=er(r=>{r.read=function(e,t,n,i,a){var o,s,c=a*8-i-1,l=(1<<c)-1,d=l>>1,u=-7,f=n?a-1:0,p=n?-1:1,h=e[t+f];for(f+=p,o=h&(1<<-u)-1,h>>=-u,u+=c;u>0;o=o*256+e[t+f],f+=p,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=i;u>0;s=s*256+e[t+f],f+=p,u-=8);if(o===0)o=1-d;else{if(o===l)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(h?-1:1)*s*Math.pow(2,o-i)},r.write=function(e,t,n,i,a,o){var s,c,l,d=o*8-a-1,u=(1<<d)-1,f=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:o-1,m=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+f>=1?t+=p/l:t+=p*Math.pow(2,1-f),t*l>=2&&(s++,l/=2),s+f>=u?(c=0,s=u):s+f>=1?(c=(t*l-1)*Math.pow(2,a),s=s+f):(c=t*Math.pow(2,f-1)*Math.pow(2,a),s=0));a>=8;e[n+h]=c&255,h+=m,c/=256,a-=8);for(s=s<<a|c,d+=a;d>0;e[n+h]=s&255,h+=m,s/=256,d-=8);e[n+h-m]|=y*128}}),xC=er(r=>{"use strict";var e=yde(),t=gde(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=s,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(T){if(T>i)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,s.prototype),M}function s(T,M,U){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(T)}return c(T,M,U)}s.poolSize=8192;function c(T,M,U){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return h(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(_e(T,ArrayBuffer)||T&&_e(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(_e(T,SharedArrayBuffer)||T&&_e(T.buffer,SharedArrayBuffer)))return m(T,M,U);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return s.from(te,M,U);let ce=y(T);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return s.from(T[Symbol.toPrimitive]("string"),M,U);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}s.from=function(T,M,U){return c(T,M,U)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,U){return l(T),T<=0?o(T):M!==void 0?typeof U=="string"?o(T).fill(M,U):o(T).fill(M):o(T)}s.alloc=function(T,M,U){return d(T,M,U)};function u(T){return l(T),o(T<0?0:v(T)|0)}s.allocUnsafe=function(T){return u(T)},s.allocUnsafeSlow=function(T){return u(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!s.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let U=x(T,M)|0,te=o(U),ce=te.write(T,M);return ce!==U&&(te=te.slice(0,ce)),te}function p(T){let M=T.length<0?0:v(T.length)|0,U=o(M);for(let te=0;te<M;te+=1)U[te]=T[te]&255;return U}function h(T){if(_e(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return p(T)}function m(T,M,U){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(U||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&U===void 0?te=new Uint8Array(T):U===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,U),Object.setPrototypeOf(te,s.prototype),te}function y(T){if(s.isBuffer(T)){let M=v(T.length)|0,U=o(M);return U.length===0||T.copy(U,0,0,M),U}if(T.length!==void 0)return typeof T.length!="number"||at(T.length)?o(0):p(T);if(T.type==="Buffer"&&Array.isArray(T.data))return p(T.data)}function v(T){if(T>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return T|0}function w(T){return+T!=T&&(T=0),s.alloc(+T)}s.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==s.prototype},s.compare=function(T,M){if(_e(T,Uint8Array)&&(T=s.from(T,T.offset,T.byteLength)),_e(M,Uint8Array)&&(M=s.from(M,M.offset,M.byteLength)),!s.isBuffer(T)||!s.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let U=T.length,te=M.length;for(let ce=0,ge=Math.min(U,te);ce<ge;++ce)if(T[ce]!==M[ce]){U=T[ce],te=M[ce];break}return U<te?-1:te<U?1:0},s.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return s.alloc(0);let U;if(M===void 0)for(M=0,U=0;U<T.length;++U)M+=T[U].length;let te=s.allocUnsafe(M),ce=0;for(U=0;U<T.length;++U){let ge=T[U];if(_e(ge,Uint8Array))ce+ge.length>te.length?(s.isBuffer(ge)||(ge=s.from(ge)),ge.copy(te,ce)):Uint8Array.prototype.set.call(te,ge,ce);else if(s.isBuffer(ge))ge.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=ge.length}return te};function x(T,M){if(s.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||_e(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let U=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&U===0)return 0;let ce=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return U;case"utf8":case"utf-8":return Pe(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U*2;case"hex":return U>>>1;case"base64":return Je(T).length;default:if(ce)return te?-1:Pe(T).length;M=(""+M).toLowerCase(),ce=!0}}s.byteLength=x;function _(T,M,U){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((U===void 0||U>this.length)&&(U=this.length),U<=0)||(U>>>=0,M>>>=0,U<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,M,U);case"utf8":case"utf-8":return R(this,M,U);case"ascii":return S(this,M,U);case"latin1":case"binary":return E(this,M,U);case"base64":return Y(this,M,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,M,U);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}s.prototype._isBuffer=!0;function A(T,M,U){let te=T[M];T[M]=T[U],T[U]=te}s.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)A(this,M,M+1);return this},s.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)A(this,M,M+3),A(this,M+1,M+2);return this},s.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)A(this,M,M+7),A(this,M+1,M+6),A(this,M+2,M+5),A(this,M+3,M+4);return this},s.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):_.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(T){if(!s.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:s.compare(this,T)===0},s.prototype.inspect=function(){let T="",M=r.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(T,M,U,te,ce){if(_e(T,Uint8Array)&&(T=s.from(T,T.offset,T.byteLength)),!s.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),U===void 0&&(U=T?T.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),M<0||U>T.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&M>=U)return 0;if(te>=ce)return-1;if(M>=U)return 1;if(M>>>=0,U>>>=0,te>>>=0,ce>>>=0,this===T)return 0;let ge=ce-te,ke=U-M,Vt=Math.min(ge,ke),ni=this.slice(te,ce),Vr=T.slice(M,U);for(let Ar=0;Ar<Vt;++Ar)if(ni[Ar]!==Vr[Ar]){ge=ni[Ar],ke=Vr[Ar];break}return ge<ke?-1:ke<ge?1:0};function D(T,M,U,te,ce){if(T.length===0)return-1;if(typeof U=="string"?(te=U,U=0):U>2147483647?U=2147483647:U<-2147483648&&(U=-2147483648),U=+U,at(U)&&(U=ce?0:T.length-1),U<0&&(U=T.length+U),U>=T.length){if(ce)return-1;U=T.length-1}else if(U<0)if(ce)U=0;else return-1;if(typeof M=="string"&&(M=s.from(M,te)),s.isBuffer(M))return M.length===0?-1:N(T,M,U,te,ce);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(T,M,U):Uint8Array.prototype.lastIndexOf.call(T,M,U):N(T,[M],U,te,ce);throw new TypeError("val must be string, number or Buffer")}function N(T,M,U,te,ce){let ge=1,ke=T.length,Vt=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;ge=2,ke/=2,Vt/=2,U/=2}function ni(Ar,gr){return ge===1?Ar[gr]:Ar.readUInt16BE(gr*ge)}let Vr;if(ce){let Ar=-1;for(Vr=U;Vr<ke;Vr++)if(ni(T,Vr)===ni(M,Ar===-1?0:Vr-Ar)){if(Ar===-1&&(Ar=Vr),Vr-Ar+1===Vt)return Ar*ge}else Ar!==-1&&(Vr-=Vr-Ar),Ar=-1}else for(U+Vt>ke&&(U=ke-Vt),Vr=U;Vr>=0;Vr--){let Ar=!0;for(let gr=0;gr<Vt;gr++)if(ni(T,Vr+gr)!==ni(M,gr)){Ar=!1;break}if(Ar)return Vr}return-1}s.prototype.includes=function(T,M,U){return this.indexOf(T,M,U)!==-1},s.prototype.indexOf=function(T,M,U){return D(this,T,M,U,!0)},s.prototype.lastIndexOf=function(T,M,U){return D(this,T,M,U,!1)};function $(T,M,U,te){U=Number(U)||0;let ce=T.length-U;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let ge=M.length;te>ge/2&&(te=ge/2);let ke;for(ke=0;ke<te;++ke){let Vt=parseInt(M.substr(ke*2,2),16);if(at(Vt))return ke;T[U+ke]=Vt}return ke}function z(T,M,U,te){return Bt(Pe(M,T.length-U),T,U,te)}function L(T,M,U,te){return Bt(Ne(M),T,U,te)}function j(T,M,U,te){return Bt(Je(M),T,U,te)}function H(T,M,U,te){return Bt(He(M,T.length-U),T,U,te)}s.prototype.write=function(T,M,U,te){if(M===void 0)te="utf8",U=this.length,M=0;else if(U===void 0&&typeof M=="string")te=M,U=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(U)?(U=U>>>0,te===void 0&&(te="utf8")):(te=U,U=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-M;if((U===void 0||U>ce)&&(U=ce),T.length>0&&(U<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return $(this,T,M,U);case"utf8":case"utf-8":return z(this,T,M,U);case"ascii":case"latin1":case"binary":return L(this,T,M,U);case"base64":return j(this,T,M,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,T,M,U);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Y(T,M,U){return M===0&&U===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,U))}function R(T,M,U){U=Math.min(T.length,U);let te=[],ce=M;for(;ce<U;){let ge=T[ce],ke=null,Vt=ge>239?4:ge>223?3:ge>191?2:1;if(ce+Vt<=U){let ni,Vr,Ar,gr;switch(Vt){case 1:ge<128&&(ke=ge);break;case 2:ni=T[ce+1],(ni&192)===128&&(gr=(ge&31)<<6|ni&63,gr>127&&(ke=gr));break;case 3:ni=T[ce+1],Vr=T[ce+2],(ni&192)===128&&(Vr&192)===128&&(gr=(ge&15)<<12|(ni&63)<<6|Vr&63,gr>2047&&(gr<55296||gr>57343)&&(ke=gr));break;case 4:ni=T[ce+1],Vr=T[ce+2],Ar=T[ce+3],(ni&192)===128&&(Vr&192)===128&&(Ar&192)===128&&(gr=(ge&15)<<18|(ni&63)<<12|(Vr&63)<<6|Ar&63,gr>65535&&gr<1114112&&(ke=gr))}}ke===null?(ke=65533,Vt=1):ke>65535&&(ke-=65536,te.push(ke>>>10&1023|55296),ke=56320|ke&1023),te.push(ke),ce+=Vt}return P(te)}var C=4096;function P(T){let M=T.length;if(M<=C)return String.fromCharCode.apply(String,T);let U="",te=0;for(;te<M;)U+=String.fromCharCode.apply(String,T.slice(te,te+=C));return U}function S(T,M,U){let te="";U=Math.min(T.length,U);for(let ce=M;ce<U;++ce)te+=String.fromCharCode(T[ce]&127);return te}function E(T,M,U){let te="";U=Math.min(T.length,U);for(let ce=M;ce<U;++ce)te+=String.fromCharCode(T[ce]);return te}function k(T,M,U){let te=T.length;(!M||M<0)&&(M=0),(!U||U<0||U>te)&&(U=te);let ce="";for(let ge=M;ge<U;++ge)ce+=It[T[ge]];return ce}function I(T,M,U){let te=T.slice(M,U),ce="";for(let ge=0;ge<te.length-1;ge+=2)ce+=String.fromCharCode(te[ge]+te[ge+1]*256);return ce}s.prototype.slice=function(T,M){let U=this.length;T=~~T,M=M===void 0?U:~~M,T<0?(T+=U,T<0&&(T=0)):T>U&&(T=U),M<0?(M+=U,M<0&&(M=0)):M>U&&(M=U),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,s.prototype),te};function K(T,M,U){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>U)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T],ce=1,ge=0;for(;++ge<M&&(ce*=256);)te+=this[T+ge]*ce;return te},s.prototype.readUintBE=s.prototype.readUIntBE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T+--M],ce=1;for(;M>0&&(ce*=256);)te+=this[T+--M]*ce;return te},s.prototype.readUint8=s.prototype.readUInt8=function(T,M){return T=T>>>0,M||K(T,1,this.length),this[T]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||K(T,2,this.length),this[T]|this[T+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||K(T,2,this.length),this[T]<<8|this[T+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||K(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},s.prototype.readBigUInt64LE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ce=this[++T]+this[++T]*2**8+this[++T]*2**16+U*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),s.prototype.readBigUInt64BE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ce=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+U;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),s.prototype.readIntLE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T],ce=1,ge=0;for(;++ge<M&&(ce*=256);)te+=this[T+ge]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*M)),te},s.prototype.readIntBE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=M,ce=1,ge=this[T+--te];for(;te>0&&(ce*=256);)ge+=this[T+--te]*ce;return ce*=128,ge>=ce&&(ge-=Math.pow(2,8*M)),ge},s.prototype.readInt8=function(T,M){return T=T>>>0,M||K(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},s.prototype.readInt16LE=function(T,M){T=T>>>0,M||K(T,2,this.length);let U=this[T]|this[T+1]<<8;return U&32768?U|4294901760:U},s.prototype.readInt16BE=function(T,M){T=T>>>0,M||K(T,2,this.length);let U=this[T+1]|this[T]<<8;return U&32768?U|4294901760:U},s.prototype.readInt32LE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},s.prototype.readInt32BE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},s.prototype.readBigInt64LE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(U<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),s.prototype.readBigInt64BE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+U)}),s.prototype.readFloatLE=function(T,M){return T=T>>>0,M||K(T,4,this.length),t.read(this,T,!0,23,4)},s.prototype.readFloatBE=function(T,M){return T=T>>>0,M||K(T,4,this.length),t.read(this,T,!1,23,4)},s.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||K(T,8,this.length),t.read(this,T,!0,52,8)},s.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||K(T,8,this.length),t.read(this,T,!1,52,8)};function F(T,M,U,te,ce,ge){if(!s.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ce||M<ge)throw new RangeError('"value" argument is out of bounds');if(U+te>T.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(T,M,U,te){if(T=+T,M=M>>>0,U=U>>>0,!te){let ke=Math.pow(2,8*U)-1;F(this,T,M,U,ke,0)}let ce=1,ge=0;for(this[M]=T&255;++ge<U&&(ce*=256);)this[M+ge]=T/ce&255;return M+U},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(T,M,U,te){if(T=+T,M=M>>>0,U=U>>>0,!te){let ke=Math.pow(2,8*U)-1;F(this,T,M,U,ke,0)}let ce=U-1,ge=1;for(this[M+ce]=T&255;--ce>=0&&(ge*=256);)this[M+ce]=T/ge&255;return M+U},s.prototype.writeUint8=s.prototype.writeUInt8=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,1,255,0),this[M]=T&255,M+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function V(T,M,U,te,ce){le(M,te,ce,T,U,7);let ge=Number(M&BigInt(4294967295));T[U++]=ge,ge=ge>>8,T[U++]=ge,ge=ge>>8,T[U++]=ge,ge=ge>>8,T[U++]=ge;let ke=Number(M>>BigInt(32)&BigInt(4294967295));return T[U++]=ke,ke=ke>>8,T[U++]=ke,ke=ke>>8,T[U++]=ke,ke=ke>>8,T[U++]=ke,U}function W(T,M,U,te,ce){le(M,te,ce,T,U,7);let ge=Number(M&BigInt(4294967295));T[U+7]=ge,ge=ge>>8,T[U+6]=ge,ge=ge>>8,T[U+5]=ge,ge=ge>>8,T[U+4]=ge;let ke=Number(M>>BigInt(32)&BigInt(4294967295));return T[U+3]=ke,ke=ke>>8,T[U+2]=ke,ke=ke>>8,T[U+1]=ke,ke=ke>>8,T[U]=ke,U+8}s.prototype.writeBigUInt64LE=$t(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=$t(function(T,M=0){return W(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(T,M,U,te){if(T=+T,M=M>>>0,!te){let Vt=Math.pow(2,8*U-1);F(this,T,M,U,Vt-1,-Vt)}let ce=0,ge=1,ke=0;for(this[M]=T&255;++ce<U&&(ge*=256);)T<0&&ke===0&&this[M+ce-1]!==0&&(ke=1),this[M+ce]=(T/ge>>0)-ke&255;return M+U},s.prototype.writeIntBE=function(T,M,U,te){if(T=+T,M=M>>>0,!te){let Vt=Math.pow(2,8*U-1);F(this,T,M,U,Vt-1,-Vt)}let ce=U-1,ge=1,ke=0;for(this[M+ce]=T&255;--ce>=0&&(ge*=256);)T<0&&ke===0&&this[M+ce+1]!==0&&(ke=1),this[M+ce]=(T/ge>>0)-ke&255;return M+U},s.prototype.writeInt8=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},s.prototype.writeInt16LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},s.prototype.writeInt16BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},s.prototype.writeInt32LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},s.prototype.writeInt32BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},s.prototype.writeBigInt64LE=$t(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=$t(function(T,M=0){return W(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(T,M,U,te,ce,ge){if(U+te>T.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("Index out of range")}function Q(T,M,U,te,ce){return M=+M,U=U>>>0,ce||J(T,M,U,4,34028234663852886e22,-34028234663852886e22),t.write(T,M,U,te,23,4),U+4}s.prototype.writeFloatLE=function(T,M,U){return Q(this,T,M,!0,U)},s.prototype.writeFloatBE=function(T,M,U){return Q(this,T,M,!1,U)};function q(T,M,U,te,ce){return M=+M,U=U>>>0,ce||J(T,M,U,8,17976931348623157e292,-17976931348623157e292),t.write(T,M,U,te,52,8),U+8}s.prototype.writeDoubleLE=function(T,M,U){return q(this,T,M,!0,U)},s.prototype.writeDoubleBE=function(T,M,U){return q(this,T,M,!1,U)},s.prototype.copy=function(T,M,U,te){if(!s.isBuffer(T))throw new TypeError("argument should be a Buffer");if(U||(U=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<U&&(te=U),te===U||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-U&&(te=T.length-M+U);let ce=te-U;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,U,te):Uint8Array.prototype.set.call(T,this.subarray(U,te),M),ce},s.prototype.fill=function(T,M,U,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,U=this.length):typeof U=="string"&&(te=U,U=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!s.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let ge=T.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(T=ge)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<U)throw new RangeError("Out of range index");if(U<=M)return this;M=M>>>0,U=U===void 0?this.length:U>>>0,T||(T=0);let ce;if(typeof T=="number")for(ce=M;ce<U;++ce)this[ce]=T;else{let ge=s.isBuffer(T)?T:s.from(T,te),ke=ge.length;if(ke===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ce=0;ce<U-M;++ce)this[ce+M]=ge[ce%ke]}return this};var ee={};function se(T,M,U){ee[T]=class extends U{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,U){let te=`The value of "${T}" is out of range.`,ce=U;return Number.isInteger(U)&&Math.abs(U)>2**32?ce=ne(String(U)):typeof U=="bigint"&&(ce=String(U),(U>BigInt(2)**BigInt(32)||U<-(BigInt(2)**BigInt(32)))&&(ce=ne(ce)),ce+="n"),te+=` It must be ${M}. Received ${ce}`,te},RangeError);function ne(T){let M="",U=T.length,te=T[0]==="-"?1:0;for(;U>=te+4;U-=3)M=`_${T.slice(U-3,U)}${M}`;return`${T.slice(0,U)}${M}`}function X(T,M,U){ue(M,"offset"),(T[M]===void 0||T[M+U]===void 0)&&pe(M,T.length-(U+1))}function le(T,M,U,te,ce,ge){if(T>U||T<M){let ke=typeof M=="bigint"?"n":"",Vt;throw ge>3?M===0||M===BigInt(0)?Vt=`>= 0${ke} and < 2${ke} ** ${(ge+1)*8}${ke}`:Vt=`>= -(2${ke} ** ${(ge+1)*8-1}${ke}) and < 2 ** ${(ge+1)*8-1}${ke}`:Vt=`>= ${M}${ke} and <= ${U}${ke}`,new ee.ERR_OUT_OF_RANGE("value",Vt,T)}X(te,ce,ge)}function ue(T,M){if(typeof T!="number")throw new ee.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,U){throw Math.floor(T)!==T?(ue(T,U),new ee.ERR_OUT_OF_RANGE(U||"offset","an integer",T)):M<0?new ee.ERR_BUFFER_OUT_OF_BOUNDS:new ee.ERR_OUT_OF_RANGE(U||"offset",`>= ${U?1:0} and <= ${M}`,T)}var xe=/[^+/0-9A-Za-z-_]/g;function de(T){if(T=T.split("=")[0],T=T.trim().replace(xe,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Pe(T,M){M=M||1/0;let U,te=T.length,ce=null,ge=[];for(let ke=0;ke<te;++ke){if(U=T.charCodeAt(ke),U>55295&&U<57344){if(!ce){if(U>56319){(M-=3)>-1&&ge.push(239,191,189);continue}else if(ke+1===te){(M-=3)>-1&&ge.push(239,191,189);continue}ce=U;continue}if(U<56320){(M-=3)>-1&&ge.push(239,191,189),ce=U;continue}U=(ce-55296<<10|U-56320)+65536}else ce&&(M-=3)>-1&&ge.push(239,191,189);if(ce=null,U<128){if((M-=1)<0)break;ge.push(U)}else if(U<2048){if((M-=2)<0)break;ge.push(U>>6|192,U&63|128)}else if(U<65536){if((M-=3)<0)break;ge.push(U>>12|224,U>>6&63|128,U&63|128)}else if(U<1114112){if((M-=4)<0)break;ge.push(U>>18|240,U>>12&63|128,U>>6&63|128,U&63|128)}else throw new Error("Invalid code point")}return ge}function Ne(T){let M=[];for(let U=0;U<T.length;++U)M.push(T.charCodeAt(U)&255);return M}function He(T,M){let U,te,ce,ge=[];for(let ke=0;ke<T.length&&!((M-=2)<0);++ke)U=T.charCodeAt(ke),te=U>>8,ce=U%256,ge.push(ce),ge.push(te);return ge}function Je(T){return e.toByteArray(de(T))}function Bt(T,M,U,te){let ce;for(ce=0;ce<te&&!(ce+U>=M.length||ce>=T.length);++ce)M[ce+U]=T[ce];return ce}function _e(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function at(T){return T!==T}var It=function(){let T="0123456789abcdef",M=new Array(256);for(let U=0;U<16;++U){let te=U*16;for(let ce=0;ce<16;++ce)M[te+ce]=T[U]+T[ce]}return M}();function $t(T){return typeof BigInt>"u"?Ht:T}function Ht(){throw new Error("BigInt not supported")}}),r7=er((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),n7=er(r=>{"use strict";var e=Od(),t=new Set(["buffer","view","utf8"]),n=class{constructor(i){if(this.encode=i.encode||this.encode,this.decode=i.decode||this.decode,this.name=i.name||this.name,this.format=i.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!t.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");i.createViewTranscoder&&(this.createViewTranscoder=i.createViewTranscoder),i.createBufferTranscoder&&(this.createBufferTranscoder=i.createBufferTranscoder),i.createUTF8Transcoder&&(this.createUTF8Transcoder=i.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};r.Encoding=n}),i7=er(r=>{"use strict";var{Buffer:e}=xC()||{},{Encoding:t}=n7(),n=r7(),i=class extends t{constructor(s){super({...s,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:s=>this.decode(e.from(s.buffer,s.byteOffset,s.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends t{constructor(s){super({...s,format:"view"})}createBufferTranscoder(){return new i({encode:s=>{let c=this.encode(s);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends t{constructor(s){super({...s,format:"utf8"})}createBufferTranscoder(){return new i({encode:s=>e.from(this.encode(s),"utf8"),decode:s=>this.decode(s.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:s,textDecoder:c}=n();return new a({encode:l=>s.encode(this.encode(l)),decode:l=>this.decode(c.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=a,r.UTF8Format=o}),wde=er(r=>{"use strict";var{Buffer:e}=xC()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=r7()(),{BufferFormat:i,ViewFormat:a,UTF8Format:o}=i7(),s=c=>c;r.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:s,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:s,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),r.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:s,name:"view",createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:s,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),r.base64=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),vde=er(r=>{"use strict";var e=Od(),t=wde(),{Encoding:n}=n7(),{BufferFormat:i,ViewFormat:a,UTF8Format:o}=i7(),s=Symbol("formats"),c=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(v=>l.has(v)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[s]=new Set(y);for(let v in t)try{this.encoding(v)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let v=this[c].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=h[y],!v)throw new e(`Encoding '${y}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof y!="object"||y===null)throw new TypeError("First argument 'encoding' must be a string or object");v=u(y)}let{name:w,format:x}=v;if(!this[s].has(x))if(this[s].has("view"))v=v.createViewTranscoder();else if(this[s].has("buffer"))v=v.createBufferTranscoder();else if(this[s].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,v.name,v.commonName])this[c].set(_,v)}return v}};r.Transcoder=d;function u(y){if(y instanceof n)return y;let v="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||v||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new o({...y,name:w});case"buffer":return new i({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var p={binary:t.buffer,"utf-8":t.utf8},h={...t,...p},m=0}),bde=er((r,e)=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function o(l,d,u,f,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new a(u,f||l,p),m=n?n+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],h]:l._events[m].push(h):(l._events[m]=h,l._eventsCount++),l}function s(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)t.call(d,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},c.prototype.listeners=function(l){var d=n?n+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,p=u.length,h=new Array(p);f<p;f++)h[f]=u[f].fn;return h},c.prototype.listenerCount=function(l){var d=n?n+l:l,u=this._events[d];return u?u.fn?1:u.length:0},c.prototype.emit=function(l,d,u,f,p,h){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,x;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,u),!0;case 4:return y.fn.call(y.context,d,u,f),!0;case 5:return y.fn.call(y.context,d,u,f,p),!0;case 6:return y.fn.call(y.context,d,u,f,p,h),!0}for(x=1,w=new Array(v-1);x<v;x++)w[x-1]=arguments[x];y.fn.apply(y.context,w)}else{var _=y.length,A;for(x=0;x<_;x++)switch(y[x].once&&this.removeListener(l,y[x].fn,void 0,!0),v){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,d);break;case 3:y[x].fn.call(y[x].context,d,u);break;case 4:y[x].fn.call(y[x].context,d,u,f);break;default:if(!w)for(A=1,w=new Array(v-1);A<v;A++)w[A-1]=arguments[A];y[x].fn.apply(y[x].context,w)}}return!0},c.prototype.on=function(l,d,u){return o(this,l,d,u,!1)},c.prototype.once=function(l,d,u){return o(this,l,d,u,!0)},c.prototype.removeListener=function(l,d,u,f){var p=n?n+l:l;if(!this._events[p])return this;if(!d)return s(this,p),this;var h=this._events[p];if(h.fn)h.fn===d&&(!f||h.once)&&(!u||h.context===u)&&s(this,p);else{for(var m=0,y=[],v=h.length;m<v;m++)(h[m].fn!==d||f&&!h[m].once||u&&h[m].context!==u)&&y.push(h[m]);y.length?this._events[p]=y.length===1?y[0]:y:s(this,p)}return this},c.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&s(this,d)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),Pde=er((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),eE=er(r=>{"use strict";var e=Pde();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(a,o){t=function(s,c){s?o(s):a(c)}});t[n!==void 0?n:"promise"]=i}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t},r.fromPromise=function(t,n){if(n===void 0)return t;t.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),EC=er(r=>{"use strict";r.getCallback=function(e,t){return typeof e=="function"?e:t},r.getOptions=function(e,t){return typeof e=="object"&&e!==null?e:t!==void 0?t:{}}}),ah=er(r=>{"use strict";var{fromCallback:e}=eE(),t=Od(),{getOptions:n,getCallback:i}=EC(),a=Symbol("promise"),o=Symbol("callback"),s=Symbol("working"),c=Symbol("handleOne"),l=Symbol("handleMany"),d=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),p=Symbol("closing"),h=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),x=Symbol("abortOnClose"),_=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),z=Object.freeze({}),L=()=>{},j=!1,H=class{constructor(S,E,k){if(typeof S!="object"||S===null){let I=S===null?"null":typeof S;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof E!="object"||E===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[s]=!1,this[p]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[l]=this[l].bind(this),this[h]=this[h].bind(this),this[v]=E[v],this[w]=E[w],this[_]=k,this[N]=Number.isInteger(E.limit)&&E.limit>=0?E.limit:1/0,this[$]=0,this[x]=!!E.abortOnClose,this.db=S,this.db.attachResource(this),this.nextTick=S.nextTick}get count(){return this[$]}get limit(){return this[N]}next(S){let E;if(S===void 0)E=new Promise((k,I)=>{S=(K,F,V)=>{K?I(K):this[_]?F===void 0&&V===void 0?k():k([F,V]):k(F)}});else if(typeof S!="function")throw new TypeError("Callback must be a function");return this[p]?this.nextTick(S,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(S,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[s]=!0,this[o]=S,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),E}_next(S){this.nextTick(S)}nextv(S,E,k){return k=i(E,k),k=e(k,a),E=n(E,z),Number.isInteger(S)?(this[p]?this.nextTick(k,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(k,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(S<1&&(S=1),this[N]<1/0&&(S=Math.min(S,this[N]-this[$])),this[s]=!0,this[o]=k,S<=0?this.nextTick(this[l],null,[]):this._nextv(S,E,this[l])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(S,E,k){let I=[],K=(F,V,W)=>{if(F)return k(F);if(this[_]?V===void 0&&W===void 0:V===void 0)return k(null,I);I.push(this[_]?[V,W]:V),I.length===S?k(null,I):this._next(K)};this._next(K)}all(S,E){return E=i(S,E),E=e(E,a),S=n(S,z),this[p]?this.nextTick(E,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(E,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[s]=!0,this[o]=E,this[d]=!0,this[$]>=this[N]?this.nextTick(this[l],null,[]):this._all(S,this[l])),E[a]}_all(S,E){let k=this[$],I=[],K=()=>{let V=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;V<=0?this.nextTick(E,null,I):this._nextv(V,z,F)},F=(V,W)=>{V?E(V):W.length===0?E(null,I):(I.push.apply(I,W),k+=W.length,K())};K()}[u](){let S=this[o];return this[x]&&S===null?L:(this[s]=!1,this[o]=null,this[p]&&this._close(this[h]),S)}[f](S,E,k){this[d]?this.close(S.bind(null,E,k)):S(E,k)}seek(S,E){if(E=n(E,z),!this[p]){if(this[s])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(E.keyEncoding||this[v]),I=k.format;E.keyEncoding!==I&&(E={...E,keyEncoding:I});let K=this.db.prefixKey(k.encode(S),I);this._seek(K,E)}}}_seek(S,E){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(S){return S=e(S,a),this[m]?this.nextTick(S):this[p]?this[y].push(S):(this[p]=!0,this[y].push(S),this[s]?this[x]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[h])),S[a]}_close(S){this.nextTick(S)}[h](){this[m]=!0,this.db.detachResource(this);let S=this[y];this[y]=[];for(let E of S)E()}async*[Symbol.asyncIterator](){try{let S;for(;(S=await this.next())!==void 0;)yield S}finally{this[m]||await this.close()}}},Y=class extends H{constructor(S,E){super(S,E,!0),this[A]=E.keys!==!1,this[D]=E.values!==!1}[c](S,E,k){let I=this[u]();if(S)return I(S);try{E=this[A]&&E!==void 0?this[v].decode(E):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(K){return I(new P("entry",K))}E===void 0&&k===void 0||this[$]++,I(null,E,k)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I of E){let K=I[0],F=I[1];I[0]=this[A]&&K!==void 0?this[v].decode(K):void 0,I[1]=this[D]&&F!==void 0?this[w].decode(F):void 0}}catch(I){return this[f](k,new P("entries",I))}this[$]+=E.length,this[f](k,null,E)}end(S){return!j&&typeof console<"u"&&(j=!0,console.warn(new t("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(S)}},R=class extends H{constructor(S,E){super(S,E,!1)}[c](S,E){let k=this[u]();if(S)return k(S);try{E=E!==void 0?this[v].decode(E):void 0}catch(I){return k(new P("key",I))}E!==void 0&&this[$]++,k(null,E)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I=0;I<E.length;I++){let K=E[I];E[I]=K!==void 0?this[v].decode(K):void 0}}catch(I){return this[f](k,new P("keys",I))}this[$]+=E.length,this[f](k,null,E)}},C=class extends H{constructor(S,E){super(S,E,!1)}[c](S,E){let k=this[u]();if(S)return k(S);try{E=E!==void 0?this[w].decode(E):void 0}catch(I){return k(new P("value",I))}E!==void 0&&this[$]++,k(null,E)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I=0;I<E.length;I++){let K=E[I];E[I]=K!==void 0?this[w].decode(K):void 0}}catch(I){return this[f](k,new P("values",I))}this[$]+=E.length,this[f](k,null,E)}},P=class extends t{constructor(S,E){super(`Iterator could not decode ${S}`,{code:"LEVEL_DECODE_ERROR",cause:E})}};for(let S of["_ended property","_nexting property","_end method"])Object.defineProperty(Y.prototype,S.split(" ")[0],{get(){throw new t(`The ${S} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${S} has been removed`,{code:"LEVEL_LEGACY"})}});Y.keyEncoding=v,Y.valueEncoding=w,r.AbstractIterator=Y,r.AbstractKeyIterator=R,r.AbstractValueIterator=C}),xde=er(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=ah(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),s=class extends e{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends t{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let l of[s,c]){let d=l===s,u=d?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,p,h){let m=this[i];f?m(f):m(null,d?p:h)},l.prototype._nextv=function(f,p,h){this[i]=h,this[n].nextv(f,p,this[o])},l.prototype._all=function(f,p){this[i]=p,this[n].all(f,this[o])},l.prototype[o]=function(f,p){let h=this[i];f?h(f):h(null,p.map(u))},l.prototype._seek=function(f,p){this[n].seek(f,p)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=s,r.DefaultValueIterator=c}),Ede=er(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=ah(),i=Od(),a=Symbol("nut"),o=Symbol("undefer"),s=Symbol("factory"),c=class extends e{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.iterator(f),this.db.defer(()=>this[o]())}},l=class extends t{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.values(f),this.db.defer(()=>this[o]())}};for(let u of[c,l,d])u.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[s]())},u.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new i("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._nextv=function(f,p,h){this[a]!==null?this[a].nextv(f,p,h):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,p,h)):this.nextTick(h,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,p){this[a]!==null?this[a].all(p):this.db.status==="opening"?this.db.defer(()=>this._all(f,p)):this.nextTick(p,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,p){this[a]!==null?this[a]._seek(f,p):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,p))},u.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=c,r.DeferredKeyIterator=l,r.DeferredValueIterator=d}),s7=er(r=>{"use strict";var{fromCallback:e}=eE(),t=Od(),{getCallback:n,getOptions:i}=EC(),a=Symbol("promise"),o=Symbol("status"),s=Symbol("operations"),c=Symbol("finishClose"),l=Symbol("closeCallbacks"),d=class{constructor(u){if(typeof u!="object"||u===null){let f=u===null?"null":typeof u;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[s]=[],this[l]=[],this[o]="open",this[c]=this[c].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[s].length}put(u,f,p){if(this[o]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u)||this.db._checkValue(f);if(h)throw h;let m=p&&p.sublevel!=null?p.sublevel:this.db,y=p,v=m.keyEncoding(p&&p.keyEncoding),w=m.valueEncoding(p&&p.valueEncoding),x=v.format;p={...p,keyEncoding:x,valueEncoding:w.format},m!==this.db&&(p.sublevel=null);let _=m.prefixKey(v.encode(u),x),A=w.encode(f);return this._put(_,A,p),this[s].push({...y,type:"put",key:u,value:f}),this}_put(u,f,p){}del(u,f){if(this[o]!=="open")throw new t("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u);if(p)throw p;let h=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=h.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},h!==this.db&&(f.sublevel=null),this._del(h.prefixKey(y.encode(u),v),f),this[s].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[o]!=="open")throw new t("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[s]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,a),u=i(u),this[o]!=="open"?this.nextTick(f,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(f):(this[o]="writing",this._write(u,p=>{this[o]="closing",this[l].push(()=>f(p)),p||this.db.emit("batch",this[s]),this._close(this[c])})),f[a]}_write(u,f){}close(u){return u=e(u,a),this[o]==="closing"?this[l].push(u):this[o]==="closed"?this.nextTick(u):(this[l].push(u),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),u[a]}_close(u){this.nextTick(u)}[c](){this[o]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=d}),Sde=er(r=>{"use strict";var{AbstractChainedBatch:e}=s7(),t=Od(),n=Symbol("encoded"),i=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,s){this[n].push({...s,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};r.DefaultChainedBatch=i}),kde=er((r,e)=>{"use strict";var t=Od(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let s={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new t(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(c)?s[c]=o.encode(a[c]):s[c]=a[c]}return s.reverse=!!s.reverse,s.limit=Number.isInteger(s.limit)&&s.limit>=0?s.limit:-1,s}}),o7=er((r,e)=>{var t;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(t||(t=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),_de=er((r,e)=>{"use strict";var t=o7();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),Ade=er(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=ah(),i=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),s=Symbol("handleMany"),c=Symbol("callback"),l=class extends e{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[o]=this[o].bind(this),this[s]=this[s].bind(this),this[c]=null}[o](f,p,h){let m=this[c];if(f)return m(f);p!==void 0&&(p=this[i](p)),m(f,p,h)}[s](f,p){let h=this[c];if(f)return h(f);for(let m of p){let y=m[0];y!==void 0&&(m[0]=this[i](y))}h(f,p)}},d=class extends t{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[o]=this[o].bind(this),this[s]=this[s].bind(this),this[c]=null}[o](f,p){let h=this[c];if(f)return h(f);p!==void 0&&(p=this[i](p)),h(f,p)}[s](f,p){let h=this[c];if(f)return h(f);for(let m=0;m<p.length;m++){let y=p[m];y!==void 0&&(p[m]=this[i](y))}h(f,p)}},u=class extends n{constructor(f,p,h){super(f,p),this[a]=h}};for(let f of[l,d])f.prototype._next=function(p){this[c]=p,this[a].next(this[o])},f.prototype._nextv=function(p,h,m){this[c]=m,this[a].nextv(p,h,this[s])},f.prototype._all=function(p,h){this[c]=h,this[a].all(p,this[s])};for(let f of[u])f.prototype._next=function(p){this[a].next(p)},f.prototype._nextv=function(p,h,m){this[a].nextv(p,h,m)},f.prototype._all=function(p,h){this[a].all(p,h)};for(let f of[l,d,u])f.prototype._seek=function(p,h){this[a].seek(p,h)},f.prototype._close=function(p){this[a].close(p)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=d,r.AbstractSublevelValueIterator=u}),Tde=er((r,e)=>{"use strict";var t=Od(),{Buffer:n}=xC()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Ade(),s=Symbol("prefix"),c=Symbol("upperBound"),l=Symbol("prefixRange"),d=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,p={separator:"!"};e.exports=function({AbstractLevel:x}){class _ extends x{static defaults(D){if(typeof D=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?p:D.separator?D:{...D,separator:"!"}}constructor(D,N,$){let{separator:z,manifest:L,...j}=_.defaults($);N=w(N,z);let H=z.charCodeAt(0)+1,Y=D[d]||D;if(!f.encode(N).every(P=>P>H&&P<127))throw new t(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(h(Y,L),j);let R=(D.prefix||"")+z+N+z,C=R.slice(0,-1)+String.fromCharCode(H);this[d]=Y,this[s]=new y(R),this[c]=new y(C),this[u]=new v,this.nextTick=Y.nextTick}prefixKey(D,N){if(N==="utf8")return this[s].utf8+D;if(D.byteLength===0)return this[s][N];if(N==="view"){let $=this[s].view,z=new Uint8Array($.byteLength+D.byteLength);return z.set($,0),z.set(D,$.byteLength),z}else{let $=this[s].buffer;return n.concat([$,D],$.byteLength+D.byteLength)}}[l](D,N){D.gte!==void 0?D.gte=this.prefixKey(D.gte,N):D.gt!==void 0?D.gt=this.prefixKey(D.gt,N):D.gte=this[s][N],D.lte!==void 0?D.lte=this.prefixKey(D.lte,N):D.lt!==void 0?D.lt=this.prefixKey(D.lt,N):D.lte=this[c][N]}get prefix(){return this[s].utf8}get db(){return this[d]}_open(D,N){this[d].open({passive:!0},N)}_put(D,N,$,z){this[d].put(D,N,$,z)}_get(D,N,$){this[d].get(D,N,$)}_getMany(D,N,$){this[d].getMany(D,N,$)}_del(D,N,$){this[d].del(D,N,$)}_batch(D,N,$){this[d].batch(D,N,$)}_clear(D,N){this[l](D,D.keyEncoding),this[d].clear(D,N)}_iterator(D){this[l](D,D.keyEncoding);let N=this[d].iterator(D),$=this[u].get(this[s].utf8.length,D.keyEncoding);return new i(this,D,N,$)}_keys(D){this[l](D,D.keyEncoding);let N=this[d].keys(D),$=this[u].get(this[s].utf8.length,D.keyEncoding);return new a(this,D,N,$)}_values(D){this[l](D,D.keyEncoding);let N=this[d].values(D);return new o(this,D,N)}}return{AbstractSublevel:_}};var h=function(x,_){return{...x.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(x,"utf8"),buffer:m(x,"buffer"),view:m(x,"view")}}},m=function(x,_){return x.supports.encodings[_]?x.keyEncoding(_).name===_:!1},y=class{constructor(x){this.utf8=x,this.view=f.encode(x),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(x,_){let A=this.cache.get(_);return A===void 0&&(_==="view"?A=(function(D,N){return N.subarray(D)}).bind(null,x):A=(function(D,N){return N.slice(D)}).bind(null,x),this.cache.set(_,A)),A}},w=function(x,_){let A=0,D=x.length;for(;A<D&&x[A]===_;)A++;for(;D>A&&x[D-1]===_;)D--;return x.slice(A,D)}}),N9=er(r=>{"use strict";var{supports:e}=mde(),{Transcoder:t}=vde(),{EventEmitter:n}=bde(),{fromCallback:i}=eE(),a=Od(),{AbstractIterator:o}=ah(),{DefaultKeyIterator:s,DefaultValueIterator:c}=xde(),{DeferredIterator:l,DeferredKeyIterator:d,DeferredValueIterator:u}=Ede(),{DefaultChainedBatch:f}=Sde(),{getCallback:p,getOptions:h}=EC(),m=kde(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),x=Symbol("closeResources"),_=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),j=Symbol("keyEncoding"),H=Symbol("valueEncoding"),Y=()=>{},R=class extends n{constructor(E,k){if(super(),typeof E!="object"||E===null)throw new TypeError("The first argument 'manifest' must be an object");k=h(k);let{keyEncoding:I,valueEncoding:K,passive:F,...V}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[N]=V,this[$]="opening",this.supports=e(E,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:E.snapshots!==!1,permanence:E.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:E.encodings||{},events:Object.assign({},E.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(S(this)),this[j]=this[L].encoding(I||"utf8"),this[H]=this[L].encoding(K||"utf8");for(let W of this[L].encodings())this.supports.encodings[W.commonName]||(this.supports.encodings[W.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[j].commonName,valueEncoding:this[H].commonName}),key:Object.freeze({keyEncoding:this[j].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},Y)})}get status(){return this[$]}keyEncoding(E){return this[L].encoding(E??this[j])}valueEncoding(E){return this[L].encoding(E??this[H])}open(E,k){k=p(E,k),k=i(k,y),E={...this[N],...h(E)},E.createIfMissing=E.createIfMissing!==!1,E.errorIfExists=!!E.errorIfExists;let I=K=>{this[$]==="closing"||this[$]==="opening"?this.once(v,K?()=>I(K):I):this[$]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:K})):k()};return E.passive?this[$]==="opening"?this.once(v,I):this.nextTick(I):this[$]==="closed"||this[D]?(this[D]=!1,this[$]="opening",this.emit("opening"),this._open(E,K=>{if(K){this[$]="closed",this[x](()=>{this.emit(v),I(K)}),this[A]();return}this[$]="open",this[A](),this.emit(v),this[$]==="open"&&this.emit("open"),this[$]==="open"&&this.emit("ready"),I()})):this[$]==="open"?this.nextTick(I):this.once(v,()=>this.open(E,k)),k[y]}_open(E,k){this.nextTick(k)}close(E){E=i(E,y);let k=I=>{this[$]==="opening"||this[$]==="closing"?this.once(v,I?k(I):k):this[$]!=="closed"?E(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):E()};if(this[$]==="open"){this[$]="closing",this.emit("closing");let I=K=>{this[$]="open",this[A](),this.emit(v),k(K)};this[x](()=>{this._close(K=>{if(K)return I(K);this[$]="closed",this[A](),this.emit(v),this[$]==="closed"&&this.emit("closed"),k()})})}else this[$]==="closed"?this.nextTick(k):this.once(v,()=>this.close(E));return E[y]}[x](E){if(this[w].size===0)return this.nextTick(E);let k=this[w].size,I=!0,K=()=>{--k===0&&(I?this.nextTick(E):E())};for(let F of this[w])F.close(K);I=!1,this[w].clear()}_close(E){this.nextTick(E)}get(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[$]==="opening")return this.defer(()=>this.get(E,k,I)),I[y];if(P(this,I))return I[y];let K=this._checkKey(E);if(K)return this.nextTick(I,K),I[y];let F=this.keyEncoding(k.keyEncoding),V=this.valueEncoding(k.valueEncoding),W=F.format,J=V.format;return(k.keyEncoding!==W||k.valueEncoding!==J)&&(k=Object.assign({},k,{keyEncoding:W,valueEncoding:J})),this._get(this.prefixKey(F.encode(E),W),k,(Q,q)=>{if(Q)return(Q.code==="LEVEL_NOT_FOUND"||Q.notFound||/NotFound/i.test(Q))&&(Q.code||(Q.code="LEVEL_NOT_FOUND"),Q.notFound||(Q.notFound=!0),Q.status||(Q.status=404)),I(Q);try{q=V.decode(q)}catch(ee){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:ee}))}I(null,q)}),I[y]}_get(E,k,I){this.nextTick(I,new Error("NotFound"))}getMany(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[$]==="opening")return this.defer(()=>this.getMany(E,k,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(E))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(E.length===0)return this.nextTick(I,null,[]),I[y];let K=this.keyEncoding(k.keyEncoding),F=this.valueEncoding(k.valueEncoding),V=K.format,W=F.format;(k.keyEncoding!==V||k.valueEncoding!==W)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:W}));let J=new Array(E.length);for(let Q=0;Q<E.length;Q++){let q=E[Q],ee=this._checkKey(q);if(ee)return this.nextTick(I,ee),I[y];J[Q]=this.prefixKey(K.encode(q),V)}return this._getMany(J,k,(Q,q)=>{if(Q)return I(Q);try{for(let ee=0;ee<q.length;ee++)q[ee]!==void 0&&(q[ee]=F.decode(q[ee]))}catch(ee){return I(new a(`Could not decode one or more of ${q.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:ee}))}I(null,q)}),I[y]}_getMany(E,k,I){this.nextTick(I,null,new Array(E.length).fill(void 0))}put(E,k,I,K){if(K=p(I,K),K=i(K,y),I=h(I,this[z].entry),this[$]==="opening")return this.defer(()=>this.put(E,k,I,K)),K[y];if(P(this,K))return K[y];let F=this._checkKey(E)||this._checkValue(k);if(F)return this.nextTick(K,F),K[y];let V=this.keyEncoding(I.keyEncoding),W=this.valueEncoding(I.valueEncoding),J=V.format,Q=W.format;(I.keyEncoding!==J||I.valueEncoding!==Q)&&(I=Object.assign({},I,{keyEncoding:J,valueEncoding:Q}));let q=this.prefixKey(V.encode(E),J),ee=W.encode(k);return this._put(q,ee,I,se=>{if(se)return K(se);this.emit("put",E,k),K()}),K[y]}_put(E,k,I,K){this.nextTick(K)}del(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].key),this[$]==="opening")return this.defer(()=>this.del(E,k,I)),I[y];if(P(this,I))return I[y];let K=this._checkKey(E);if(K)return this.nextTick(I,K),I[y];let F=this.keyEncoding(k.keyEncoding),V=F.format;return k.keyEncoding!==V&&(k=Object.assign({},k,{keyEncoding:V})),this._del(this.prefixKey(F.encode(E),V),k,W=>{if(W)return I(W);this.emit("del",E),I()}),I[y]}_del(E,k,I){this.nextTick(I)}batch(E,k,I){if(!arguments.length){if(this[$]==="opening")return new f(this);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof E=="function"?I=E:I=p(k,I),I=i(I,y),k=h(k,this[z].empty),this[$]==="opening")return this.defer(()=>this.batch(E,k,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(E))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(E.length===0)return this.nextTick(I),I[y];let K=new Array(E.length),{keyEncoding:F,valueEncoding:V,...W}=k;for(let J=0;J<E.length;J++){if(typeof E[J]!="object"||E[J]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Q=Object.assign({},E[J]);if(Q.type!=="put"&&Q.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let q=this._checkKey(Q.key);if(q)return this.nextTick(I,q),I[y];let ee=Q.sublevel!=null?Q.sublevel:this,se=ee.keyEncoding(Q.keyEncoding||F),ne=se.format;if(Q.key=ee.prefixKey(se.encode(Q.key),ne),Q.keyEncoding=ne,Q.type==="put"){let X=this._checkValue(Q.value);if(X)return this.nextTick(I,X),I[y];let le=ee.valueEncoding(Q.valueEncoding||V);Q.value=le.encode(Q.value),Q.valueEncoding=le.format}ee!==this&&(Q.sublevel=null),K[J]=Q}return this._batch(K,W,J=>{if(J)return I(J);this.emit("batch",E),I()}),I[y]}_batch(E,k,I){this.nextTick(I)}sublevel(E,k){return this._sublevel(E,C.defaults(k))}_sublevel(E,k){return new C(this,E,k)}prefixKey(E,k){return E}clear(E,k){if(k=p(E,k),k=i(k,y),E=h(E,this[z].empty),this[$]==="opening")return this.defer(()=>this.clear(E,k)),k[y];if(P(this,k))return k[y];let I=E,K=this.keyEncoding(E.keyEncoding);return E=m(E,K),E.keyEncoding=K.format,E.limit===0?this.nextTick(k):this._clear(E,F=>{if(F)return k(F);this.emit("clear",I),k()}),k[y]}_clear(E,k){this.nextTick(k)}iterator(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E.keys=E.keys!==!1,E.values=E.values!==!1,E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new l(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(E)}_iterator(E){return new o(this,E)}keys(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new d(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(E)}_keys(E){return new s(this,E)}values(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new u(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(E)}_values(E){return new c(this,E)}defer(E){if(typeof E!="function")throw new TypeError("The first argument must be a function");this[_].push(E)}[A](){if(this[_].length===0)return;let E=this[_];this[_]=[];for(let k of E)k()}attachResource(E){if(typeof E!="object"||E===null||typeof E.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(E)}detachResource(E){this[w].delete(E)}_chainedBatch(){return new f(this)}_checkKey(E){if(E==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(E){if(E==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=_de();var{AbstractSublevel:C}=Tde()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=C;var P=function(E,k){return E[$]!=="open"?(E.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},S=function(E){return Object.keys(E.supports.encodings).filter(k=>!!E.supports.encodings[k])}}),a7=er(r=>{"use strict";r.AbstractLevel=N9().AbstractLevel,r.AbstractSublevel=N9().AbstractSublevel,r.AbstractIterator=ah().AbstractIterator,r.AbstractKeyIterator=ah().AbstractKeyIterator,r.AbstractValueIterator=ah().AbstractValueIterator,r.AbstractChainedBatch=s7().AbstractChainedBatch}),Ide=er((r,e)=>{e.exports=n;var t=o7();function n(i,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let s,c,l,d,u,f=!0,p;Array.isArray(i)?(s=[],l=c=i.length):(d=Object.keys(i),s={},l=c=d.length);function h(y){function v(){o&&o(y,s),o=null}f?t(v):v()}function m(y,v,w){if(s[y]=w,v&&(u=!0),--l===0||v)h(v);else if(!u&&p<c){let x;d?(x=d[p],p+=1,i[x](function(_,A){m(x,_,A)})):(x=p,p+=1,i[x](function(_,A){m(x,_,A)}))}}p=a,l?d?d.some(function(y,v){return i[y](function(w,x){m(y,w,x)}),v===a-1}):i.some(function(y,v){return y(function(w,x){m(v,w,x)}),v===a-1}):h(null),f=!1}}),c7=er((r,e)=>{"use strict";e.exports=function(t){let n=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,i=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,a=t.gte===void 0,o=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):i!==void 0?IDBKeyRange.upperBound(i,o):null}}),d7=er((r,e)=>{"use strict";var t=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):t.encode(n)}}),Dde=er(r=>{"use strict";var{AbstractIterator:e}=a7(),t=c7(),n=d7(),i=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),s=Symbol("currentOptions"),c=Symbol("position"),l=Symbol("location"),d=Symbol("first"),u={},f=class extends e{constructor(h,m,y){super(h,y),this[i]=[],this[a]=this.limit===0,this[o]=y,this[s]={...y},this[c]=void 0,this[l]=m,this[d]=!0}_nextv(h,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return h=Math.min(h,this[i].length),this.nextTick(y,null,this[i].splice(0,h));this[c]!==void 0&&(this[o].reverse?(this[s].lt=this[c],this[s].lte=void 0):(this[s].gt=this[c],this[s].gte=void 0));let v;try{v=t(this[s])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),x=w.objectStore(this[l]),_=[];if(this[o].reverse){let A=!this[o].values&&x.openKeyCursor?"openKeyCursor":"openCursor";x[A](v,"prev").onsuccess=D=>{let N=D.target.result;if(N){let{key:$,value:z}=N;this[c]=$,_.push([this[o].keys&&$!==void 0?n($):void 0,this[o].values&&z!==void 0?n(z):void 0]),_.length<h?N.continue():p(w)}else this[a]=!0}}else{let A,D,N=()=>{if(A===void 0||D===void 0)return;let $=Math.max(A.length,D.length);$===0||h===1/0?this[a]=!0:this[c]=A[$-1],_.length=$;for(let z=0;z<$;z++){let L=A[z],j=D[z];_[z]=[this[o].keys&&L!==void 0?n(L):void 0,this[o].values&&j!==void 0?n(j):void 0]}p(w)};this[o].keys||h<1/0?x.getAllKeys(v,h<1/0?h:void 0).onsuccess=$=>{A=$.target.result,N()}:(A=[],this.nextTick(N)),this[o].values?x.getAll(v,h<1/0?h:void 0).onsuccess=$=>{D=$.target.result,N()}:(D=[],this.nextTick(N))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(h){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(h,null,m,y)}else if(this[a])this.nextTick(h);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return h(y);this[i]=v,this._next(h)})}}_all(h,m){this[d]=!1;let y=this[i].splice(0,this[i].length),v=this.limit-this.count-y.length;if(v<=0)return this.nextTick(m,null,y);this._nextv(v,u,(w,x)=>{if(w)return m(w);y.length>0&&(x=y.concat(x)),m(null,x)})}_seek(h,m){this[d]=!0,this[i]=[],this[a]=!1,this[c]=void 0,this[s]={...this[o]};let y;try{y=t(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(h)?this[a]=!0:this[o].reverse?this[s].lte=h:this[s].gte=h}};r.Iterator=f;function p(h){typeof h.commit=="function"&&h.commit()}}),Rde=er((r,e)=>{"use strict";e.exports=function(t,n,i,a,o){if(a.limit===0)return t.nextTick(o);let s=t.db.transaction([n],"readwrite"),c=s.objectStore(n),l=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";c[d](i,u).onsuccess=function(f){let p=f.target.result;p&&(c.delete(p.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&p.continue()})}}}),Cde=er(r=>{"use strict";var{AbstractLevel:e}=a7(),t=Od(),n=Ide(),{fromCallback:i}=eE(),{Iterator:a}=Dde(),o=d7(),s=Rde(),c=c7(),l="level-js-",d=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),p=Symbol("version"),h=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,x,_){if(typeof x=="function"||typeof _=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...N}=x||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=A??l,this[p]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[p]}get db(){return this[d]}get type(){return"browser-level"}_open(w,x){let _=indexedDB.open(this[u]+this[f],this[p]);_.onerror=function(){x(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,x()},_.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[h](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,x){let _=w.transaction;_.onabort=function(){x(_.error||new Error("aborted by user"))},_.oncomplete=function(){x(null,w.result)}}_get(w,x,_){let A=this[h]("readonly"),D;try{D=A.get(w)}catch(N){return this.nextTick(_,N)}this[m](D,function(N,$){if(N)return _(N);if($===void 0)return _(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(w,x,_){let A=this[h]("readonly"),D=w.map(N=>$=>{let z;try{z=A.get(N)}catch(L){return $(L)}z.onsuccess=()=>{let L=z.result;$(null,L===void 0?L:o(L))},z.onerror=L=>{L.stopPropagation(),$(z.error)}});n(D,16,_)}_del(w,x,_){let A=this[h]("readwrite"),D;try{D=A.delete(w)}catch(N){return this.nextTick(_,N)}this[m](D,_)}_put(w,x,_,A){let D=this[h]("readwrite"),N;try{N=D.put(x,w)}catch($){return this.nextTick(A,$)}this[m](N,A)}_iterator(w){return new a(this,this[f],w)}_batch(w,x,_){let A=this[h]("readwrite"),D=A.transaction,N=0,$;D.onabort=function(){_($||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function z(){let L=w[N++],j=L.key,H;try{H=L.type==="del"?A.delete(j):A.put(L.value,j)}catch(Y){$=Y,D.abort();return}N<w.length?H.onsuccess=z:typeof D.commit=="function"&&D.commit()}z()}_clear(w,x){let _,A;try{_=c(w)}catch{return this.nextTick(x)}if(w.limit>=0)return s(this,this[f],_,w,x);try{let D=this[h]("readwrite");A=_?D.delete(_):D.clear()}catch(D){return this.nextTick(x,D)}this[m](A,x)}_close(w){this[d].close(),this.nextTick(w)}};v.destroy=function(w,x,_){typeof x=="function"&&(_=x,x=l),_=i(_,y);let A=indexedDB.deleteDatabase(x+w);return A.onsuccess=function(){_()},A.onerror=function(D){_(D)},_[y]},r.BrowserLevel=v}),l7=er(r=>{r.Level=Cde().BrowserLevel}),$de=er((r,e)=>{(function(t,n){typeof r=="object"&&typeof e<"u"?n(r):typeof define=="function"&&define.amd?define(["exports"],n):n(t.URI=t.URI||{})})(r,function(t){"use strict";function n(){for(var Z=arguments.length,oe=Array(Z),ae=0;ae<Z;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var be=oe.length-1,Ee=1;Ee<be;++Ee)oe[Ee]=oe[Ee].slice(1,-1);return oe[be]=oe[be].slice(1),oe.join("")}else return oe[0]}function i(Z){return"(?:"+Z+")"}function a(Z){return Z===void 0?"undefined":Z===null?"null":Object.prototype.toString.call(Z).split(" ").pop().split("]").shift().toLowerCase()}function o(Z){return Z.toUpperCase()}function s(Z){return Z!=null?Z instanceof Array?Z:typeof Z.length!="number"||Z.split||Z.setInterval||Z.call?[Z]:Array.prototype.slice.call(Z):[]}function c(Z,oe){var ae=Z;if(oe)for(var be in oe)ae[be]=oe[be];return ae}function l(Z){var oe="[A-Za-z]",ae="[\\x0D]",be="[0-9]",Ee="[\\x22]",We=n(be,"[A-Fa-f]"),Nt="[\\x0A]",Pr="[\\x20]",Qr=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),en="[\\:\\/\\?\\#\\[\\]\\@]",pr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",An=n(en,pr),Qn=Z?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",wn=Z?"[\\uE000-\\uF8FF]":"[]",Cr=n(oe,be,"[\\-\\.\\_\\~]",Qn),Tr=i(oe+n(oe,be,"[\\+\\-\\.]")+"*"),cs=i(i(Qr+"|"+n(Cr,pr,"[\\:]"))+"*"),Ig=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),Qs=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),Ga=i(Qs+"\\."+Qs+"\\."+Qs+"\\."+Qs),$r=i(We+"{1,4}"),Eo=i(i($r+"\\:"+$r)+"|"+Ga),ia=i(i($r+"\\:")+"{6}"+Eo),Kd=i("\\:\\:"+i($r+"\\:")+"{5}"+Eo),Mf=i(i($r)+"?\\:\\:"+i($r+"\\:")+"{4}"+Eo),Cc=i(i(i($r+"\\:")+"{0,1}"+$r)+"?\\:\\:"+i($r+"\\:")+"{3}"+Eo),Rb=i(i(i($r+"\\:")+"{0,2}"+$r)+"?\\:\\:"+i($r+"\\:")+"{2}"+Eo),Cb=i(i(i($r+"\\:")+"{0,3}"+$r)+"?\\:\\:"+$r+"\\:"+Eo),Nh=i(i(i($r+"\\:")+"{0,4}"+$r)+"?\\:\\:"+Eo),Uh=i(i(i($r+"\\:")+"{0,5}"+$r)+"?\\:\\:"+$r),Lh=i(i(i($r+"\\:")+"{0,6}"+$r)+"?\\:\\:"),Kf=i([ia,Kd,Mf,Cc,Rb,Cb,Nh,Uh,Lh].join("|")),qh=i(i(Cr+"|"+Qr)+"+"),zh=i(Kf+"\\%25"+qh),sV=i(Kf+i("\\%25|\\%(?!"+We+"{2})")+qh),oV=i("[vV]"+We+"+\\."+n(Cr,pr,"[\\:]")+"+"),aV=i("\\["+i(sV+"|"+Kf+"|"+oV)+"\\]"),i5=i(i(Qr+"|"+n(Cr,pr))+"*"),Dg=i(aV+"|"+Ga+"(?!"+i5+")|"+i5),Rg=i(be+"*"),s5=i(i(cs+"@")+"?"+Dg+i("\\:"+Rg)+"?"),Cg=i(Qr+"|"+n(Cr,pr,"[\\:\\@]")),cV=i(Cg+"*"),o5=i(Cg+"+"),dV=i(i(Qr+"|"+n(Cr,pr,"[\\@]"))+"+"),Nd=i(i("\\/"+cV)+"*"),Fh=i("\\/"+i(o5+Nd)+"?"),pS=i(dV+Nd),$b=i(o5+Nd),Gh="(?!"+Cg+")",iwe=i(Nd+"|"+Fh+"|"+pS+"|"+$b+"|"+Gh),Hh=i(i(Cg+"|"+n("[\\/\\?]",wn))+"*"),$g=i(i(Cg+"|[\\/\\?]")+"*"),a5=i(i("\\/\\/"+s5+Nd)+"|"+Fh+"|"+$b+"|"+Gh),lV=i(Tr+"\\:"+a5+i("\\?"+Hh)+"?"+i("\\#"+$g)+"?"),uV=i(i("\\/\\/"+s5+Nd)+"|"+Fh+"|"+pS+"|"+Gh),fV=i(uV+i("\\?"+Hh)+"?"+i("\\#"+$g)+"?"),swe=i(lV+"|"+fV),owe=i(Tr+"\\:"+a5+i("\\?"+Hh)+"?"),awe="^("+Tr+")\\:"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+$b+"|"+Gh+")")+i("\\?("+Hh+")")+"?"+i("\\#("+$g+")")+"?$",cwe="^(){0}"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+pS+"|"+Gh+")")+i("\\?("+Hh+")")+"?"+i("\\#("+$g+")")+"?$",dwe="^("+Tr+")\\:"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+$b+"|"+Gh+")")+i("\\?("+Hh+")")+"?$",lwe="^"+i("\\#("+$g+")")+"?$",uwe="^"+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Cr,pr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Cr,pr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Cr,pr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Cr,pr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Cr,pr,"[\\:\\@\\/\\?]",wn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Cr,pr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Cr,pr),"g"),UNRESERVED:new RegExp(Cr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Cr,An),"g"),PCT_ENCODED:new RegExp(Qr,"g"),IPV4ADDRESS:new RegExp("^("+Ga+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Kf+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+qh+")")+"?\\]?$")}}var d=l(!1),u=l(!0),f=function(){function Z(oe,ae){var be=[],Ee=!0,We=!1,Nt=void 0;try{for(var Pr=oe[Symbol.iterator](),Qr;!(Ee=(Qr=Pr.next()).done)&&(be.push(Qr.value),!(ae&&be.length===ae));Ee=!0);}catch(en){We=!0,Nt=en}finally{try{!Ee&&Pr.return&&Pr.return()}finally{if(We)throw Nt}}return be}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Z(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),p=function(Z){if(Array.isArray(Z)){for(var oe=0,ae=Array(Z.length);oe<Z.length;oe++)ae[oe]=Z[oe];return ae}else return Array.from(Z)},h=2147483647,m=36,y=1,v=26,w=38,x=700,_=72,A=128,D="-",N=/^xn--/,$=/[^\0-\x7E]/,z=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=m-y,H=Math.floor,Y=String.fromCharCode;function R(Z){throw new RangeError(L[Z])}function C(Z,oe){for(var ae=[],be=Z.length;be--;)ae[be]=oe(Z[be]);return ae}function P(Z,oe){var ae=Z.split("@"),be="";ae.length>1&&(be=ae[0]+"@",Z=ae[1]),Z=Z.replace(z,".");var Ee=Z.split("."),We=C(Ee,oe).join(".");return be+We}function S(Z){for(var oe=[],ae=0,be=Z.length;ae<be;){var Ee=Z.charCodeAt(ae++);if(Ee>=55296&&Ee<=56319&&ae<be){var We=Z.charCodeAt(ae++);(We&64512)==56320?oe.push(((Ee&1023)<<10)+(We&1023)+65536):(oe.push(Ee),ae--)}else oe.push(Ee)}return oe}var E=function(Z){return String.fromCodePoint.apply(String,p(Z))},k=function(Z){return Z-48<10?Z-22:Z-65<26?Z-65:Z-97<26?Z-97:m},I=function(Z,oe){return Z+22+75*(Z<26)-((oe!=0)<<5)},K=function(Z,oe,ae){var be=0;for(Z=ae?H(Z/x):Z>>1,Z+=H(Z/oe);Z>j*v>>1;be+=m)Z=H(Z/j);return H(be+(j+1)*Z/(Z+w))},F=function(Z){var oe=[],ae=Z.length,be=0,Ee=A,We=_,Nt=Z.lastIndexOf(D);Nt<0&&(Nt=0);for(var Pr=0;Pr<Nt;++Pr)Z.charCodeAt(Pr)>=128&&R("not-basic"),oe.push(Z.charCodeAt(Pr));for(var Qr=Nt>0?Nt+1:0;Qr<ae;){for(var en=be,pr=1,An=m;;An+=m){Qr>=ae&&R("invalid-input");var Qn=k(Z.charCodeAt(Qr++));(Qn>=m||Qn>H((h-be)/pr))&&R("overflow"),be+=Qn*pr;var wn=An<=We?y:An>=We+v?v:An-We;if(Qn<wn)break;var Cr=m-wn;pr>H(h/Cr)&&R("overflow"),pr*=Cr}var Tr=oe.length+1;We=K(be-en,Tr,en==0),H(be/Tr)>h-Ee&&R("overflow"),Ee+=H(be/Tr),be%=Tr,oe.splice(be++,0,Ee)}return String.fromCodePoint.apply(String,oe)},V=function(Z){var oe=[];Z=S(Z);var ae=Z.length,be=A,Ee=0,We=_,Nt=!0,Pr=!1,Qr=void 0;try{for(var en=Z[Symbol.iterator](),pr;!(Nt=(pr=en.next()).done);Nt=!0){var An=pr.value;An<128&&oe.push(Y(An))}}catch(zh){Pr=!0,Qr=zh}finally{try{!Nt&&en.return&&en.return()}finally{if(Pr)throw Qr}}var Qn=oe.length,wn=Qn;for(Qn&&oe.push(D);wn<ae;){var Cr=h,Tr=!0,cs=!1,Ig=void 0;try{for(var Qs=Z[Symbol.iterator](),Ga;!(Tr=(Ga=Qs.next()).done);Tr=!0){var $r=Ga.value;$r>=be&&$r<Cr&&(Cr=$r)}}catch(zh){cs=!0,Ig=zh}finally{try{!Tr&&Qs.return&&Qs.return()}finally{if(cs)throw Ig}}var Eo=wn+1;Cr-be>H((h-Ee)/Eo)&&R("overflow"),Ee+=(Cr-be)*Eo,be=Cr;var ia=!0,Kd=!1,Mf=void 0;try{for(var Cc=Z[Symbol.iterator](),Rb;!(ia=(Rb=Cc.next()).done);ia=!0){var Cb=Rb.value;if(Cb<be&&++Ee>h&&R("overflow"),Cb==be){for(var Nh=Ee,Uh=m;;Uh+=m){var Lh=Uh<=We?y:Uh>=We+v?v:Uh-We;if(Nh<Lh)break;var Kf=Nh-Lh,qh=m-Lh;oe.push(Y(I(Lh+Kf%qh,0))),Nh=H(Kf/qh)}oe.push(Y(I(Nh,0))),We=K(Ee,Eo,wn==Qn),Ee=0,++wn}}}catch(zh){Kd=!0,Mf=zh}finally{try{!ia&&Cc.return&&Cc.return()}finally{if(Kd)throw Mf}}++Ee,++be}return oe.join("")},W=function(Z){return P(Z,function(oe){return N.test(oe)?F(oe.slice(4).toLowerCase()):oe})},J=function(Z){return P(Z,function(oe){return $.test(oe)?"xn--"+V(oe):oe})},Q={version:"2.1.0",ucs2:{decode:S,encode:E},decode:F,encode:V,toASCII:J,toUnicode:W},q={};function ee(Z){var oe=Z.charCodeAt(0),ae=void 0;return oe<16?ae="%0"+oe.toString(16).toUpperCase():oe<128?ae="%"+oe.toString(16).toUpperCase():oe<2048?ae="%"+(oe>>6|192).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase():ae="%"+(oe>>12|224).toString(16).toUpperCase()+"%"+(oe>>6&63|128).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase(),ae}function se(Z){for(var oe="",ae=0,be=Z.length;ae<be;){var Ee=parseInt(Z.substr(ae+1,2),16);if(Ee<128)oe+=String.fromCharCode(Ee),ae+=3;else if(Ee>=194&&Ee<224){if(be-ae>=6){var We=parseInt(Z.substr(ae+4,2),16);oe+=String.fromCharCode((Ee&31)<<6|We&63)}else oe+=Z.substr(ae,6);ae+=6}else if(Ee>=224){if(be-ae>=9){var Nt=parseInt(Z.substr(ae+4,2),16),Pr=parseInt(Z.substr(ae+7,2),16);oe+=String.fromCharCode((Ee&15)<<12|(Nt&63)<<6|Pr&63)}else oe+=Z.substr(ae,9);ae+=9}else oe+=Z.substr(ae,3),ae+=3}return oe}function ne(Z,oe){function ae(be){var Ee=se(be);return Ee.match(oe.UNRESERVED)?Ee:be}return Z.scheme&&(Z.scheme=String(Z.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Z.userinfo!==void 0&&(Z.userinfo=String(Z.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,ee).replace(oe.PCT_ENCODED,o)),Z.host!==void 0&&(Z.host=String(Z.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,ee).replace(oe.PCT_ENCODED,o)),Z.path!==void 0&&(Z.path=String(Z.path).replace(oe.PCT_ENCODED,ae).replace(Z.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,ee).replace(oe.PCT_ENCODED,o)),Z.query!==void 0&&(Z.query=String(Z.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,ee).replace(oe.PCT_ENCODED,o)),Z.fragment!==void 0&&(Z.fragment=String(Z.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,ee).replace(oe.PCT_ENCODED,o)),Z}function X(Z){return Z.replace(/^0*(.*)/,"$1")||"0"}function le(Z,oe){var ae=Z.match(oe.IPV4ADDRESS)||[],be=f(ae,2),Ee=be[1];return Ee?Ee.split(".").map(X).join("."):Z}function ue(Z,oe){var ae=Z.match(oe.IPV6ADDRESS)||[],be=f(ae,3),Ee=be[1],We=be[2];if(Ee){for(var Nt=Ee.toLowerCase().split("::").reverse(),Pr=f(Nt,2),Qr=Pr[0],en=Pr[1],pr=en?en.split(":").map(X):[],An=Qr.split(":").map(X),Qn=oe.IPV4ADDRESS.test(An[An.length-1]),wn=Qn?7:8,Cr=An.length-wn,Tr=Array(wn),cs=0;cs<wn;++cs)Tr[cs]=pr[cs]||An[Cr+cs]||"";Qn&&(Tr[wn-1]=le(Tr[wn-1],oe));var Ig=Tr.reduce(function(ia,Kd,Mf){if(!Kd||Kd==="0"){var Cc=ia[ia.length-1];Cc&&Cc.index+Cc.length===Mf?Cc.length++:ia.push({index:Mf,length:1})}return ia},[]),Qs=Ig.sort(function(ia,Kd){return Kd.length-ia.length})[0],Ga=void 0;if(Qs&&Qs.length>1){var $r=Tr.slice(0,Qs.index),Eo=Tr.slice(Qs.index+Qs.length);Ga=$r.join(":")+"::"+Eo.join(":")}else Ga=Tr.join(":");return We&&(Ga+="%"+We),Ga}else return Z}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,xe="".match(/(){0}/)[1]===void 0;function de(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},be=oe.iri!==!1?u:d;oe.reference==="suffix"&&(Z=(oe.scheme?oe.scheme+":":"")+"//"+Z);var Ee=Z.match(pe);if(Ee){xe?(ae.scheme=Ee[1],ae.userinfo=Ee[3],ae.host=Ee[4],ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Ee[7],ae.fragment=Ee[8],isNaN(ae.port)&&(ae.port=Ee[5])):(ae.scheme=Ee[1]||void 0,ae.userinfo=Z.indexOf("@")!==-1?Ee[3]:void 0,ae.host=Z.indexOf("//")!==-1?Ee[4]:void 0,ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Z.indexOf("?")!==-1?Ee[7]:void 0,ae.fragment=Z.indexOf("#")!==-1?Ee[8]:void 0,isNaN(ae.port)&&(ae.port=Z.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Ee[4]:void 0)),ae.host&&(ae.host=ue(le(ae.host,be),be)),ae.scheme===void 0&&ae.userinfo===void 0&&ae.host===void 0&&ae.port===void 0&&!ae.path&&ae.query===void 0?ae.reference="same-document":ae.scheme===void 0?ae.reference="relative":ae.fragment===void 0?ae.reference="absolute":ae.reference="uri",oe.reference&&oe.reference!=="suffix"&&oe.reference!==ae.reference&&(ae.error=ae.error||"URI is not a "+oe.reference+" reference.");var We=q[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!We||!We.unicodeSupport)){if(ae.host&&(oe.domainHost||We&&We.domainHost))try{ae.host=Q.toASCII(ae.host.replace(be.PCT_ENCODED,se).toLowerCase())}catch(Nt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Nt}ne(ae,d)}else ne(ae,be);We&&We.parse&&We.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Pe(Z,oe){var ae=oe.iri!==!1?u:d,be=[];return Z.userinfo!==void 0&&(be.push(Z.userinfo),be.push("@")),Z.host!==void 0&&be.push(ue(le(String(Z.host),ae),ae).replace(ae.IPV6ADDRESS,function(Ee,We,Nt){return"["+We+(Nt?"%25"+Nt:"")+"]"})),(typeof Z.port=="number"||typeof Z.port=="string")&&(be.push(":"),be.push(String(Z.port))),be.length?be.join(""):void 0}var Ne=/^\.\.?\//,He=/^\/\.(\/|$)/,Je=/^\/\.\.(\/|$)/,Bt=/^\/?(?:.|\n)*?(?=\/|$)/;function _e(Z){for(var oe=[];Z.length;)if(Z.match(Ne))Z=Z.replace(Ne,"");else if(Z.match(He))Z=Z.replace(He,"/");else if(Z.match(Je))Z=Z.replace(Je,"/"),oe.pop();else if(Z==="."||Z==="..")Z="";else{var ae=Z.match(Bt);if(ae){var be=ae[0];Z=Z.slice(be.length),oe.push(be)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function at(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:d,be=[],Ee=q[(oe.scheme||Z.scheme||"").toLowerCase()];if(Ee&&Ee.serialize&&Ee.serialize(Z,oe),Z.host&&!ae.IPV6ADDRESS.test(Z.host)&&(oe.domainHost||Ee&&Ee.domainHost))try{Z.host=oe.iri?Q.toUnicode(Z.host):Q.toASCII(Z.host.replace(ae.PCT_ENCODED,se).toLowerCase())}catch(Pr){Z.error=Z.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+Pr}ne(Z,ae),oe.reference!=="suffix"&&Z.scheme&&(be.push(Z.scheme),be.push(":"));var We=Pe(Z,oe);if(We!==void 0&&(oe.reference!=="suffix"&&be.push("//"),be.push(We),Z.path&&Z.path.charAt(0)!=="/"&&be.push("/")),Z.path!==void 0){var Nt=Z.path;!oe.absolutePath&&(!Ee||!Ee.absolutePath)&&(Nt=_e(Nt)),We===void 0&&(Nt=Nt.replace(/^\/\//,"/%2F")),be.push(Nt)}return Z.query!==void 0&&(be.push("?"),be.push(Z.query)),Z.fragment!==void 0&&(be.push("#"),be.push(Z.fragment)),be.join("")}function It(Z,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Ee={};return be||(Z=de(at(Z,ae),ae),oe=de(at(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Ee.scheme=oe.scheme,Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=_e(oe.path||""),Ee.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=_e(oe.path||""),Ee.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Ee.path=_e(oe.path):((Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)&&!Z.path?Ee.path="/"+oe.path:Z.path?Ee.path=Z.path.slice(0,Z.path.lastIndexOf("/")+1)+oe.path:Ee.path=oe.path,Ee.path=_e(Ee.path)),Ee.query=oe.query):(Ee.path=Z.path,oe.query!==void 0?Ee.query=oe.query:Ee.query=Z.query),Ee.userinfo=Z.userinfo,Ee.host=Z.host,Ee.port=Z.port),Ee.scheme=Z.scheme),Ee.fragment=oe.fragment,Ee}function $t(Z,oe,ae){var be=c({scheme:"null"},ae);return at(It(de(Z,be),de(oe,be),be,!0),be)}function Ht(Z,oe){return typeof Z=="string"?Z=at(de(Z,oe),oe):a(Z)==="object"&&(Z=de(at(Z,oe),oe)),Z}function T(Z,oe,ae){return typeof Z=="string"?Z=at(de(Z,ae),ae):a(Z)==="object"&&(Z=at(Z,ae)),typeof oe=="string"?oe=at(de(oe,ae),ae):a(oe)==="object"&&(oe=at(oe,ae)),Z===oe}function M(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?d.ESCAPE:u.ESCAPE,ee)}function U(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?d.PCT_ENCODED:u.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(Z,oe){return Z.host||(Z.error=Z.error||"HTTP URIs must have a host."),Z},serialize:function(Z,oe){var ae=String(Z.scheme).toLowerCase()==="https";return(Z.port===(ae?443:80)||Z.port==="")&&(Z.port=void 0),Z.path||(Z.path="/"),Z}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(Z){return typeof Z.secure=="boolean"?Z.secure:String(Z.scheme).toLowerCase()==="wss"}var ke={scheme:"ws",domainHost:!0,parse:function(Z,oe){var ae=Z;return ae.secure=ge(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Z,oe){if((Z.port===(ge(Z)?443:80)||Z.port==="")&&(Z.port=void 0),typeof Z.secure=="boolean"&&(Z.scheme=Z.secure?"wss":"ws",Z.secure=void 0),Z.resourceName){var ae=Z.resourceName.split("?"),be=f(ae,2),Ee=be[0],We=be[1];Z.path=Ee&&Ee!=="/"?Ee:void 0,Z.query=We,Z.resourceName=void 0}return Z.fragment=void 0,Z}},Vt={scheme:"wss",domainHost:ke.domainHost,parse:ke.parse,serialize:ke.serialize},ni={},Vr=!0,Ar="[A-Za-z0-9\\-\\.\\_\\~"+(Vr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",gr="[0-9A-Fa-f]",JH=i(i("%[EFef]"+gr+"%"+gr+gr+"%"+gr+gr)+"|"+i("%[89A-Fa-f]"+gr+"%"+gr+gr)+"|"+i("%"+gr+gr)),ZH="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",YH="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",XH=n(YH,'[\\"\\\\]'),QH="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",eV=new RegExp(Ar,"g"),Kh=new RegExp(JH,"g"),tV=new RegExp(n("[^]",ZH,"[\\.]",'[\\"]',XH),"g"),e5=new RegExp(n("[^]",Ar,QH),"g"),rV=e5;function fS(Z){var oe=se(Z);return oe.match(eV)?oe:Z}var t5={scheme:"mailto",parse:function(Z,oe){var ae=Z,be=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Ee=!1,We={},Nt=ae.query.split("&"),Pr=0,Qr=Nt.length;Pr<Qr;++Pr){var en=Nt[Pr].split("=");switch(en[0]){case"to":for(var pr=en[1].split(","),An=0,Qn=pr.length;An<Qn;++An)be.push(pr[An]);break;case"subject":ae.subject=U(en[1],oe);break;case"body":ae.body=U(en[1],oe);break;default:Ee=!0,We[U(en[0],oe)]=U(en[1],oe);break}}Ee&&(ae.headers=We)}ae.query=void 0;for(var wn=0,Cr=be.length;wn<Cr;++wn){var Tr=be[wn].split("@");if(Tr[0]=U(Tr[0]),oe.unicodeSupport)Tr[1]=U(Tr[1],oe).toLowerCase();else try{Tr[1]=Q.toASCII(U(Tr[1],oe).toLowerCase())}catch(cs){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+cs}be[wn]=Tr.join("@")}return ae},serialize:function(Z,oe){var ae=Z,be=s(Z.to);if(be){for(var Ee=0,We=be.length;Ee<We;++Ee){var Nt=String(be[Ee]),Pr=Nt.lastIndexOf("@"),Qr=Nt.slice(0,Pr).replace(Kh,fS).replace(Kh,o).replace(tV,ee),en=Nt.slice(Pr+1);try{en=oe.iri?Q.toUnicode(en):Q.toASCII(U(en,oe).toLowerCase())}catch(wn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+wn}be[Ee]=Qr+"@"+en}ae.path=be.join(",")}var pr=Z.headers=Z.headers||{};Z.subject&&(pr.subject=Z.subject),Z.body&&(pr.body=Z.body);var An=[];for(var Qn in pr)pr[Qn]!==ni[Qn]&&An.push(Qn.replace(Kh,fS).replace(Kh,o).replace(e5,ee)+"="+pr[Qn].replace(Kh,fS).replace(Kh,o).replace(rV,ee));return An.length&&(ae.query=An.join("&")),ae}},nV=/^([^\:]+)\:(.*)/,r5={scheme:"urn",parse:function(Z,oe){var ae=Z.path&&Z.path.match(nV),be=Z;if(ae){var Ee=oe.scheme||be.scheme||"urn",We=ae[1].toLowerCase(),Nt=ae[2],Pr=Ee+":"+(oe.nid||We),Qr=q[Pr];be.nid=We,be.nss=Nt,be.path=void 0,Qr&&(be=Qr.parse(be,oe))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(Z,oe){var ae=oe.scheme||Z.scheme||"urn",be=Z.nid,Ee=ae+":"+(oe.nid||be),We=q[Ee];We&&(Z=We.serialize(Z,oe));var Nt=Z,Pr=Z.nss;return Nt.path=(be||oe.nid)+":"+Pr,Nt}},iV=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,n5={scheme:"urn:uuid",parse:function(Z,oe){var ae=Z;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(iV))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Z,oe){var ae=Z;return ae.nss=(Z.uuid||"").toLowerCase(),ae}};q[te.scheme]=te,q[ce.scheme]=ce,q[ke.scheme]=ke,q[Vt.scheme]=Vt,q[t5.scheme]=t5,q[r5.scheme]=r5,q[n5.scheme]=n5,t.SCHEMES=q,t.pctEncChar=ee,t.pctDecChars=se,t.parse=de,t.removeDotSegments=_e,t.serialize=at,t.resolveComponents=It,t.resolve=$t,t.normalize=Ht,t.equal=T,t.escapeComponent=M,t.unescapeComponent=U,Object.defineProperty(t,"__esModule",{value:!0})})}),Bde=er((r,e)=>{"use strict";e.exports=function t(n){if(typeof n=="number"&&isNaN(n))throw new Error("NaN is not allowed");if(typeof n=="number"&&!isFinite(n))throw new Error("Infinity is not allowed");return n===null||typeof n!="object"?JSON.stringify(n):n.toJSON instanceof Function?t(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,o)=>`${i}${o===0?"":","}${t(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return i;let o=i.length===0?"":",";return`${i}${o}${t(a)}:${t(n[a])}`},"")}}`}}),u7=er((r,e)=>{var t=1e3,n=t*60,i=n*60,a=i*24,o=a*7,s=a*365.25;e.exports=function(f,p){p=p||{};var h=typeof f;if(h==="string"&&f.length>0)return c(f);if(h==="number"&&isFinite(f))return p.long?d(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(p){var h=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return h*s;case"weeks":case"week":case"w":return h*o;case"days":case"day":case"d":return h*a;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function l(f){var p=Math.abs(f);return p>=a?Math.round(f/a)+"d":p>=i?Math.round(f/i)+"h":p>=n?Math.round(f/n)+"m":p>=t?Math.round(f/t)+"s":f+"ms"}function d(f){var p=Math.abs(f);return p>=a?u(f,p,a,"day"):p>=i?u(f,p,i,"hour"):p>=n?u(f,p,n,"minute"):p>=t?u(f,p,t,"second"):f+" ms"}function u(f,p,h,m){var y=p>=h*1.5;return Math.round(f/h)+" "+m+(y?"s":"")}}),tE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(tE||{}),Di={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},ts=class f7{constructor({method:e,id:t,path:n,query:i,fragment:a,params:o}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let t=f7.DID_URI_PATTERN.exec(e);if(!t||!t.groups)return null;let{method:n,id:i,path:a,query:o,fragment:s}=t.groups,c={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(c.path=a),o&&(c.query=o.slice(1)),s&&(c.fragment=s.slice(1)),o){let l={},d=o.slice(1).split("&");for(let u of d){let[f,p]=u.split("=");l[f]=p}c.params=l}return c}};ts.METHOD_PATTERN="([a-z0-9]+)",ts.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",ts.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${ts.PCT_ENCODED_PATTERN})`,ts.METHOD_ID_PATTERN=`((?:${ts.ID_CHAR_PATTERN}*:)*(${ts.ID_CHAR_PATTERN}+))`,ts.PATH_PATTERN="(/[^#?]*)?",ts.QUERY_PATTERN="([?][^#]*)?",ts.FRAGMENT_PATTERN="(#.*)?",ts.DID_URI_PATTERN=new RegExp("^did:(?<method>"+ts.METHOD_PATTERN+"):(?<id>"+ts.METHOD_ID_PATTERN+")(?<path>"+ts.PATH_PATTERN+")(?<query>"+ts.QUERY_PATTERN+")(?<fragment>"+ts.FRAGMENT_PATTERN+")$");Jn=ts,nt=class p7 extends Error{constructor(e,t){super(`${e}: ${t}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,p7)}},Ode=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidPreviousDidProof="invalidPreviousDidProof",r.InvalidPublicKey="invalidPublicKey",r.InvalidPublicKeyLength="invalidPublicKeyLength",r.InvalidPublicKeyType="invalidPublicKeyType",r.InvalidSignature="invalidSignature",r.NotFound="notFound",r.RepresentationNotSupported="representationNotSupported",r.UnsupportedPublicKeyType="unsupportedPublicKeyType",r))(Ode||{}),Ka=class h7 extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,h7)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(wo||(wo={}));jde=hh(hde(),1);Kde=Mde,Nde=Kde,Ude=Nde,KNe=new Uint8Array(0),Lde=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},SC=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},qde=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},zde=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return m7(this,r)}},Fde=class{constructor(r){this.decoders=r}or(r){return m7(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},m7=(r,e)=>new Fde({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Gde=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new qde(r,e,t),this.decoder=new zde(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},y7=({name:r,prefix:e,encode:t,decode:n})=>new Gde(r,e,t,n),g7=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=Ude(t,e);return y7({prefix:r,name:e,encode:n,decode:a=>SC(i(a))})},Hde=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let o=new Uint8Array(a*t/8|0),s=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,s+=t,s>=8&&(s-=8,o[l++]=255&c>>s)}if(s>=t||255&c<<8-s)throw new SyntaxError("Unexpected end of data");return o},Vde=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",o=0,s=0;for(let c=0;c<r.length;++c)for(s=s<<8|r[c],o+=8;o>t;)o-=t,a+=e[i&s>>o];if(o&&(a+=e[i&s<<t-o]),n)for(;a.length*t&7;)a+="=";return a},Qo=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>y7({prefix:e,name:r,encode(i){return Vde(i,n,t)},decode(i){return Hde(i,n,t,r)}}),x2=Qo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),NNe=Qo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),UNe=Qo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LNe=Qo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qNe=Qo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zNe=Qo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),FNe=Qo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GNe=Qo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),U9=Qo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ja=g7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HNe=g7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),VNe=Qo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),WNe=Qo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$l=Qo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JNe=Qo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});P0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},L9=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(o){return new Promise(function(s,c){o=r[a](o),i(s,c,o.done,o.value)})}}function i(a,o,s,c){Promise.resolve(c).then(function(l){a({value:l,done:s})},o)}},h2=new TextEncoder,eh=new TextDecoder,st=class yo{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new yo(e,"ArrayBuffer")}static asyncIterable(e){if(!Jde(e))throw new TypeError("Input must be of type AsyncIterable.");return new yo(e,"AsyncIterable")}static base32Z(e){return new yo(e,"Base32Z")}static base58Btc(e){return new yo(e,"Base58Btc")}static base64Url(e){return new yo(e,"Base64Url")}static bufferSource(e){return new yo(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new yo(e,"Hex")}static multibase(e){return new yo(e,"Multibase")}static object(e){return new yo(e,"Object")}static string(e){return new yo(e,"String")}static uint8Array(e){return new yo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return ja.baseDecode(this.data).buffer;case"Base64Url":return $l.baseDecode(this.data).buffer;case"BufferSource":{if(QR(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Wde(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return U9.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return ja.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return ja.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return $l.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return $l.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=h2.encode(e);return $l.baseEncode(t)}case"String":{let e=h2.encode(this.data);return $l.baseEncode(e)}case"Uint8Array":return $l.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return P0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=L9(this.data),s;s=yield o.next(),e=s.done,!e;a=!0){i=s.value,a=!1;let l=i;c.push(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let t=this.toUint8Array();return yo.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return yo.uint8Array(t).toHex()}case"Uint8Array":{let t="";for(let n=0;n<this.data.length;n++)t+=e[this.data[n]];return t}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=$l.baseDecode(this.data),t=eh.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=eh.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return eh.decode(this.data);case"Base64Url":{let e=$l.baseDecode(this.data);return eh.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return eh.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return P0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=L9(this.data),s;s=yield o.next(),e=s.done,!e;a=!0){i=s.value,a=!1;let l=i;typeof l=="string"?c+=l:c+=eh.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return c+=eh.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return U9.baseDecode(this.data);case"Base58Btc":return ja.baseDecode(this.data);case"Base64Url":return $l.baseDecode(this.data);case"BufferSource":{let e=QR(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let t=0;t<this.data.length;t+=2){let n=parseInt(this.data.substring(t,t+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[t/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return h2.encode(e)}case"String":return h2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};(function(r){r.Debug="debug",r.Silent="silent"})(z0||(z0={}));Zde=class{constructor(){this.logLevel=z0.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==z0.Silent&&console.info(r)}error(r){this.logLevel!==z0.Silent&&console.error(r)}},Yde=new Zde;typeof window<"u"&&(window.enboxLogger=Yde);T0={};PC(T0,{decode:()=>z2,encodeTo:()=>G0,encodingLength:()=>H0});Xde=w7,q9=128,Qde=127,ele=~Qde,tle=Math.pow(2,31);rle=eC,nle=128,z9=127;ile=Math.pow(2,7),sle=Math.pow(2,14),ole=Math.pow(2,21),ale=Math.pow(2,28),cle=Math.pow(2,35),dle=Math.pow(2,42),lle=Math.pow(2,49),ule=Math.pow(2,56),fle=Math.pow(2,63),ple=function(r){return r<ile?1:r<sle?2:r<ole?3:r<ale?4:r<cle?5:r<dle?6:r<lle?7:r<ule?8:r<fle?9:10},hle={encode:Xde,decode:rle,encodingLength:ple},mle=hle,q2=mle,z2=(r,e=0)=>[q2.decode(r,e),q2.decode.bytes],G0=(r,e,t=0)=>(q2.encode(r,e,t),e),H0=r=>q2.encodingLength(r),yle=(r,e)=>{let t=e.byteLength,n=H0(r),i=n+H0(t),a=new Uint8Array(i+t);return G0(r,a,0),G0(t,a,n),a.set(e,i),new kC(r,t,e,a)},gle=r=>{let e=SC(r),[t,n]=z2(e),[i,a]=z2(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==i)throw new Error("Incorrect length");return new kC(t,i,o,e)},wle=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Lde(r.bytes,t.bytes)}},kC=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},F9=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return ble(t,tC(r),e||ja.encoder);default:return Ple(t,tC(r),e||x2.encoder)}},G9=new WeakMap,tC=r=>{let e=G9.get(r);if(e==null){let t=new Map;return G9.set(r,t),t}return e},ZNe=class Ps{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:e,multihash:t}=this;if(e!==x0)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ps.createV0(t)}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:e,digest:t}=this.multihash,n=yle(e,t);return Ps.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return Ps.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&wle(e.multihash,n.multihash)}toString(e){return F9(this,e)}toJSON(){return{"/":F9(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof Ps)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:a,bytes:o}=t;return new Ps(n,i,a,o||H9(n,i,a.bytes))}else if(t[Ele]===!0){let{version:n,multihash:i,code:a}=t,o=gle(i);return Ps.create(n,a,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==x0)throw new Error(`Version 0 CID must use dag-pb (code: ${x0}) block encoding`);return new Ps(e,t,n,n.bytes)}case 1:{let i=H9(e,t,n.bytes);return new Ps(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return Ps.create(0,x0,e)}static createV1(e,t){return Ps.create(1,e,t)}static decode(e){let[t,n]=Ps.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=Ps.inspectBytes(e),n=t.size-t.multihashSize,i=SC(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let a=i.subarray(t.multihashSize-t.digestSize),o=new kC(t.multihashCode,t.digestSize,a,i);return[t.version===0?Ps.createV0(o):Ps.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=z2(e.subarray(t));return t+=f,u},i=n(),a=x0;if(i===18?(i=0,t=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,s=n(),c=n(),l=t+c,d=l-o;return{version:i,codec:a,multihashCode:s,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,i]=vle(e,t),a=Ps.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tC(a).set(n,e),a}},vle=(r,e)=>{switch(r[0]){case"Q":{let t=e||ja;return[ja.prefix,t.decode(`${ja.prefix}${r}`)]}case ja.prefix:{let t=e||ja;return[ja.prefix,t.decode(r)]}case x2.prefix:{let t=e||x2;return[x2.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},ble=(r,e,t)=>{let{prefix:n}=t;if(n!==ja.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let a=t.encode(r).slice(1);return e.set(n,a),a}else return i},Ple=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let a=t.encode(r);return e.set(n,a),a}else return i},x0=112,xle=18,H9=(r,e,t)=>{let n=H0(r),i=n+H0(e),a=new Uint8Array(i+t.byteLength);return G0(r,a,0),G0(e,a,n),a.set(t,i),a},Ele=Symbol.for("@ipld/js-cid/CID"),Ua=class yf{static addPrefix(e){var t;let{code:n,data:i,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=yf.codeToName.has(n)?n:yf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let o=T0.encodingLength(n),s=new Uint8Array(o+i.byteLength);return s.set(i,o),T0.encodeTo(n,s),s}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=T0.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=yf.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=yf.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){yf.codeToName.set(e.code,e.name),yf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=T0.decode(t),a=yf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:a}}};Ua.codeToName=new Map;Ua.nameToCode=new Map;Ua.registerCodec({code:237,name:"ed25519-pub"});Ua.registerCodec({code:4864,name:"ed25519-priv"});Ua.registerCodec({code:236,name:"x25519-pub"});Ua.registerCodec({code:4866,name:"x25519-priv"});Ua.registerCodec({code:231,name:"secp256k1-pub"});Ua.registerCodec({code:4865,name:"secp256k1-priv"});YNe=hh(l7(),1),of=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Sle=class{constructor(){this.store=new Map}clear(){return of(this,void 0,void 0,function*(){this.store.clear()})}open(){return of(this,void 0,void 0,function*(){})}close(){return of(this,void 0,void 0,function*(){})}delete(r){return of(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return of(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return of(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return of(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return of(this,void 0,void 0,function*(){this.store.set(r,e)})}},rE=class{},b7={};PC(b7,{bitGet:()=>Rle,bitLen:()=>Dle,bitMask:()=>AC,bitSet:()=>Cle,bytesToHex:()=>uh,bytesToNumberBE:()=>ch,bytesToNumberLE:()=>Pf,concatBytes:()=>fh,createHmacDrbg:()=>E7,ensureBytes:()=>Wn,equalBytes:()=>Tle,hexToBytes:()=>Hy,hexToNumber:()=>_C,isBytes:()=>$d,numberToBytesBE:()=>Bd,numberToBytesLE:()=>Vy,numberToHexUnpadded:()=>x7,numberToVarBytesBE:()=>Ale,utf8ToBytes:()=>Ile,validateObject:()=>mh});P7=BigInt(0),nE=BigInt(1),kle=BigInt(2);_le=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Bl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};Cle=(r,e,t)=>r|(t?nE:P7)<<BigInt(e),AC=r=>(kle<<BigInt(r-1))-nE,zR=r=>new Uint8Array(r),W9=r=>Uint8Array.from(r);$le={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||$d(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};FR=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;GR=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),kd=(r,e)=>r<<32-e|r>>>e,Mle=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Mle)throw new Error("Non little-endian hardware is not supported");T7=class{clone(){return this._cloneInto()}},XNe={}.toString;D7=class extends T7{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=GR(this.buffer)}update(r){F2(this);let{view:e,buffer:t,blockLen:n}=this;r=TC(r);let i=r.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let s=GR(r);for(;n<=i-a;a+=n)this.process(s,a);continue}t.set(r.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){F2(this),jle(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;Kle(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=GR(r),s=this.outputLen;if(s%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},Nle=(r,e,t)=>r&e^~r&t,Ule=(r,e,t)=>r&e^r&t^e&t,Lle=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),af=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cf=new Uint32Array(64),qle=class extends D7{constructor(){super(64,32,8,!1),this.A=af[0]|0,this.B=af[1]|0,this.C=af[2]|0,this.D=af[3]|0,this.E=af[4]|0,this.F=af[5]|0,this.G=af[6]|0,this.H=af[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:o,H:s}=this;return[r,e,t,n,i,a,o,s]}set(r,e,t,n,i,a,o,s){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(r,e){for(let d=0;d<16;d++,e+=4)cf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=cf[d-15],f=cf[d-2],p=kd(u,7)^kd(u,18)^u>>>3,h=kd(f,17)^kd(f,19)^f>>>10;cf[d]=h+cf[d-7]+p+cf[d-16]|0}let{A:t,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let d=0;d<64;d++){let u=kd(o,6)^kd(o,11)^kd(o,25),f=l+u+Nle(o,s,c)+Lle[d]+cf[d]|0,p=(kd(t,2)^kd(t,13)^kd(t,22))+Ule(t,n,i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,o,s,c,l)}roundClean(){cf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},R7=I7(()=>new qle),yi=BigInt(0),gn=BigInt(1),nh=BigInt(2),zle=BigInt(3),rC=BigInt(4),Z9=BigInt(5),Y9=BigInt(8),QNe=BigInt(9),Fle=BigInt(16);Vle=(r,e)=>(Xr(r,e)&gn)===gn,Wle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];eue=BigInt(0),HR=BigInt(1);({bytesToNumberBE:rue,hexToBytes:nue}=b7),oh={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=oh;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:rue(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=oh,t=typeof r=="string"?nue(r):r;if(!$d(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=oh._parseInt(t.subarray(2)),{d:o,l:s}=oh._parseInt(a);if(s.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),i=e(t(r.r)),a=n.length/2,o=i.length/2,s=t(a),c=t(o);return`30${t(o+a+4)}02${c}${i}02${s}${n}`}},Ul=BigInt(0),Oa=BigInt(1),eUe=BigInt(2),X9=BigInt(3),tUe=BigInt(4);M7=class extends T7{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,Ole(r);let t=TC(e);if(this.iHash=r.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(t.length>n?r.create().update(t).digest():t);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=r.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(r){return F2(this),this.iHash.update(r),this}digestInto(r){F2(this),S7(r,this.outputLen),this.finished=!0,this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||(r=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:t,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=a,r.outputLen=o,r.oHash=e._cloneInto(r.oHash),r.iHash=t._cloneInto(r.iHash),r}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},K7=(r,e,t)=>new M7(r,e).update(t).digest();K7.create=(r,e)=>new M7(r,e);U7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Q9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cue=BigInt(1),iC=BigInt(2),eq=(r,e)=>(r+e/iC)/e;sC=DC(U7,void 0,void 0,{sqrt:due}),Jo=N7({a:BigInt(0),b:BigInt(7),Fp:sC,n:Q9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Q9,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cue*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=t,o=BigInt("0x100000000000000000000000000000000"),s=eq(a*r,e),c=eq(-n*r,e),l=Xr(r-s*t-c*i,e),d=Xr(-s*n-c*a,e),u=l>o,f=d>o;if(u&&(l=e-l),f&&(d=e-d),l>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},R7),rUe=BigInt(0),nUe=Jo.ProjectivePoint;E2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,VR=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),_d=(r,e)=>r<<32-e|r>>>e,iUe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;pue=class{clone(){return this._cloneInto()}},sUe={}.toString;gue=(r,e,t)=>r&e^~r&t,wue=(r,e,t)=>r&e^r&t^e&t,vue=class extends pue{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=VR(this.buffer)}update(r){tq(this);let{view:e,buffer:t,blockLen:n}=this;r=q7(r);let i=r.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let s=VR(r);for(;n<=i-a;a+=n)this.process(s,a);continue}t.set(r.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){tq(this),uue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;yue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=VR(r),s=this.outputLen;if(s%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},bue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),df=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lf=new Uint32Array(64),Pue=class extends vue{constructor(){super(64,32,8,!1),this.A=df[0]|0,this.B=df[1]|0,this.C=df[2]|0,this.D=df[3]|0,this.E=df[4]|0,this.F=df[5]|0,this.G=df[6]|0,this.H=df[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:o,H:s}=this;return[r,e,t,n,i,a,o,s]}set(r,e,t,n,i,a,o,s){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(r,e){for(let d=0;d<16;d++,e+=4)lf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=lf[d-15],f=lf[d-2],p=_d(u,7)^_d(u,18)^u>>>3,h=_d(f,17)^_d(f,19)^f>>>10;lf[d]=h+lf[d-7]+p+lf[d-16]|0}let{A:t,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let d=0;d<64;d++){let u=_d(o,6)^_d(o,11)^_d(o,25),f=l+u+gue(o,s,c)+bue[d]+lf[d]|0,p=(_d(t,2)^_d(t,13)^_d(t,22))+wue(t,n,i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,o,s,c,l)}roundClean(){lf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},V0=hue(()=>new Pue);Eue=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},z7=class{static digest(r){return Eue(this,arguments,void 0,function*({data:e}){return V0(e)})}},Sue=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},rq="urn:jwk:";Qi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},_ue=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},ns=class Td{static adjustSignatureToLowS(e){return Qi(this,arguments,void 0,function*({signature:t}){let n=Jo.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Qi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Td.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Td.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static compressPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){return Jo.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Qi(this,arguments,void 0,function*({key:t}){let n=yield Td.privateKeyToBytes({privateKey:t}),i=yield Td.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:st.uint8Array(i.x).toBase64Url(),y:st.uint8Array(i.y).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertDerToCompactSignature(e){return Qi(this,arguments,void 0,function*({derSignature:t}){return Jo.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){return Jo.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Qi(this,void 0,void 0,function*(){let e=Jo.utils.randomPrivateKey(),t=yield Td.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return Qi(this,arguments,void 0,function*({key:t}){var n;if(!(dh(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,a=_ue(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return Qi(this,arguments,void 0,function*({privateKey:t}){if(!dh(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Qi(this,arguments,void 0,function*({publicKey:t}){if(!(CC(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=st.base64Url(t.x).toUint8Array(),a=st.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Qi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Td.privateKeyToBytes({privateKey:t}),a=yield Td.publicKeyToBytes({publicKey:n});return Jo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Qi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Td.privateKeyToBytes({privateKey:n}),a=V0(t);return Jo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Qi(this,arguments,void 0,function*({privateKeyBytes:t}){return Jo.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Jo.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Qi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Td.publicKeyToBytes({publicKey:t}),o=V0(i);return Jo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Qi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Jo.getPublicKey(t));let n=Jo.ProjectivePoint.fromHex(t),i=Bd(n.x,32),a=Bd(n.y,32);return{x:i,y:a}})}},F7=DC(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Aue=F7.create(BigInt("-3")),Tue=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Iue=N7({a:Aue,b:Tue,Fp:F7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},R7),Da=Iue,es=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Due=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},xs=class Id{static adjustSignatureToLowS(e){return es(this,arguments,void 0,function*({signature:t}){let n=Da.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return es(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Id.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Id.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static compressPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){return Da.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return es(this,arguments,void 0,function*({key:t}){let n=yield Id.privateKeyToBytes({privateKey:t}),i=yield Id.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:st.uint8Array(i.x).toBase64Url(),y:st.uint8Array(i.y).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertDerToCompactSignature(e){return es(this,arguments,void 0,function*({derSignature:t}){return Da.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){return Da.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return es(this,void 0,void 0,function*(){let e=Da.utils.randomPrivateKey(),t=yield Id.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return es(this,arguments,void 0,function*({key:t}){var n;if(!(dh(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,a=Due(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return es(this,arguments,void 0,function*({privateKey:t}){if(!dh(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return es(this,arguments,void 0,function*({publicKey:t}){if(!(CC(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=st.base64Url(t.x).toUint8Array(),a=st.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return es(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Id.privateKeyToBytes({privateKey:t}),a=yield Id.publicKeyToBytes({publicKey:n});return Da.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return es(this,arguments,void 0,function*({data:t,key:n}){let i=yield Id.privateKeyToBytes({privateKey:n}),a=V0(t);return Da.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return es(this,arguments,void 0,function*({privateKeyBytes:t}){return Da.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){try{Da.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return es(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Id.publicKeyToBytes({publicKey:t}),o=V0(i);return Da.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return es(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Da.getPublicKey(t));let n=Da.ProjectivePoint.fromHex(t),i=Bd(n.x,32),a=Bd(n.y,32);return{x:i,y:a}})}},Ol=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nq=class extends rE{bytesToPrivateKey(r){return Ol(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ns.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield xs.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Ol(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ns.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield xs.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Ol(this,arguments,void 0,function*({key:e}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ns.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield xs.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Ol(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield ns.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield xs.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return Ol(this,arguments,void 0,function*({key:e}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ns.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield xs.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Ol(this,arguments,void 0,function*({key:e,data:t}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield ns.sign({key:e,data:t});case"P-256":return yield xs.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Ol(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!CC(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield ns.verify({key:e,signature:t,data:n});case"P-256":return yield xs.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Ol(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield ns.privateKeyToBytes({privateKey:e});case"P-256":return yield xs.privateKeyToBytes({privateKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Ol(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield ns.publicKeyToBytes({publicKey:e});case"P-256":return yield xs.publicKeyToBytes({publicKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m2=BigInt(4294967295),oC=BigInt(32);Cue=(r,e)=>BigInt(r>>>0)<<oC|BigInt(e>>>0),$ue=(r,e,t)=>r>>>t,Bue=(r,e,t)=>r<<32-t|e>>>t,Oue=(r,e,t)=>r>>>t|e<<32-t,jue=(r,e,t)=>r<<32-t|e>>>t,Mue=(r,e,t)=>r<<64-t|e>>>t-32,Kue=(r,e,t)=>r>>>t-32|e<<64-t,Nue=(r,e)=>e,Uue=(r,e)=>r,Lue=(r,e,t)=>r<<t|e>>>32-t,que=(r,e,t)=>e<<t|r>>>32-t,zue=(r,e,t)=>e<<t-32|r>>>64-t,Fue=(r,e,t)=>r<<t-32|e>>>64-t;Hue=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Vue=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Wue=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Jue=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Zue=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Yue=(r,e,t,n,i,a)=>e+t+n+i+a+(r/2**32|0)|0,Xue={fromBig:G7,split:Rue,toBig:Cue,shrSH:$ue,shrSL:Bue,rotrSH:Oue,rotrSL:jue,rotrBH:Mue,rotrBL:Kue,rotr32H:Nue,rotr32L:Uue,rotlSH:Lue,rotlSL:que,rotlBH:zue,rotlBL:Fue,add:Gue,add3L:Hue,add3H:Vue,add4L:Wue,add4H:Jue,add5H:Yue,add5L:Zue},Lt=Xue,[Que,efe]=Lt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),uf=new Uint32Array(80),ff=new Uint32Array(80),tfe=class extends D7{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:r,Al:e,Bh:t,Bl:n,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:d,Fl:u,Gh:f,Gl:p,Hh:h,Hl:m}=this;return[r,e,t,n,i,a,o,s,c,l,d,u,f,p,h,m]}set(r,e,t,n,i,a,o,s,c,l,d,u,f,p,h,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=p|0,this.Hh=h|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)uf[w]=r.getUint32(e),ff[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let x=uf[w-15]|0,_=ff[w-15]|0,A=Lt.rotrSH(x,_,1)^Lt.rotrSH(x,_,8)^Lt.shrSH(x,_,7),D=Lt.rotrSL(x,_,1)^Lt.rotrSL(x,_,8)^Lt.shrSL(x,_,7),N=uf[w-2]|0,$=ff[w-2]|0,z=Lt.rotrSH(N,$,19)^Lt.rotrBH(N,$,61)^Lt.shrSH(N,$,6),L=Lt.rotrSL(N,$,19)^Lt.rotrBL(N,$,61)^Lt.shrSL(N,$,6),j=Lt.add4L(D,L,ff[w-7],ff[w-16]),H=Lt.add4H(j,A,z,uf[w-7],uf[w-16]);uf[w]=H|0,ff[w]=j|0}let{Ah:t,Al:n,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:d,El:u,Fh:f,Fl:p,Gh:h,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let x=Lt.rotrSH(d,u,14)^Lt.rotrSH(d,u,18)^Lt.rotrBH(d,u,41),_=Lt.rotrSL(d,u,14)^Lt.rotrSL(d,u,18)^Lt.rotrBL(d,u,41),A=d&f^~d&h,D=u&p^~u&m,N=Lt.add5L(v,_,D,efe[w],ff[w]),$=Lt.add5H(N,y,x,A,Que[w],uf[w]),z=N|0,L=Lt.rotrSH(t,n,28)^Lt.rotrBH(t,n,34)^Lt.rotrBH(t,n,39),j=Lt.rotrSL(t,n,28)^Lt.rotrBL(t,n,34)^Lt.rotrBL(t,n,39),H=t&i^t&o^i&o,Y=n&a^n&s^a&s;y=h|0,v=m|0,h=f|0,m=p|0,f=d|0,p=u|0,{h:d,l:u}=Lt.add(c|0,l|0,$|0,z|0),c=o|0,l=s|0,o=i|0,s=a|0,i=t|0,a=n|0;let R=Lt.add3L(z,j,Y);t=Lt.add3H(R,$,L,H),n=R|0}({h:t,l:n}=Lt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:a}=Lt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Lt.add(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Lt.add(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:u}=Lt.add(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:p}=Lt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h,l:m}=Lt.add(this.Gh|0,this.Gl|0,h|0,m|0),{h:y,l:v}=Lt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,a,o,s,c,l,d,u,f,p,h,m,y,v)}roundClean(){uf.fill(0),ff.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},H7=I7(()=>new tfe),_c=BigInt(0),Vo=BigInt(1),y2=BigInt(2),rfe=BigInt(8),nfe={zip215:!0};E0=BigInt(0),WR=BigInt(1);W0=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),iq=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),oUe=BigInt(0),afe=BigInt(1),aC=BigInt(2),cfe=BigInt(5),sq=BigInt(10),dfe=BigInt(20),lfe=BigInt(40),oq=BigInt(80);Na=DC(W0,void 0,!0),J0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:H7,randomBytes:IC,adjustScalarBytes:W7,uvRatio:ufe},th=BC(J0);aUe=BC({...J0,domain:J7}),cUe=BC({...J0,domain:J7,prehash:H7}),I0=ofe({P:W0,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=W0,{pow_p_5_8:t,b2:n}=V7(r);return Xr(Sn(t,BigInt(3),e)*n,e)},adjustScalarBytes:W7,randomBytes:IC});hfe=(Na.ORDER+BigInt(3))/BigInt(8),dUe=Na.pow(aC,hfe),lUe=Na.sqrt(Na.neg(Na.ONE)),uUe=(Na.ORDER-BigInt(5))/BigInt(8),fUe=BigInt(486662),pUe=Xle(Na,Na.neg(BigInt(486664))),hUe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),mUe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),yUe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),gUe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),wUe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ra=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},mfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},is=class gf{static bytesToPrivateKey(e){return Ra(this,arguments,void 0,function*({privateKeyBytes:t}){let n=th.getPublicKey(t),i={crv:"Ed25519",d:st.uint8Array(t).toBase64Url(),kty:"OKP",x:st.uint8Array(n).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return Ra(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:st.uint8Array(t).toBase64Url()};return n.kid=yield _r({jwk:n}),n})}static computePublicKey(e){return Ra(this,arguments,void 0,function*({key:t}){let n=yield gf.privateKeyToBytes({privateKey:t}),i=th.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Ra(this,arguments,void 0,function*({privateKey:t}){let n=yield gf.privateKeyToBytes({privateKey:t}),i=pfe(n),a=I0.getPublicKey(i),o={kty:"OKP",crv:"X25519",d:st.uint8Array(i).toBase64Url(),x:st.uint8Array(a).toBase64Url()};return o.kid=yield _r({jwk:o}),o})}static convertPublicKeyToX25519(e){return Ra(this,arguments,void 0,function*({publicKey:t}){let n=yield gf.publicKeyToBytes({publicKey:t});if(!(yield gf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=ffe(n),a={kty:"OKP",crv:"X25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static generateKey(){return Ra(this,void 0,void 0,function*(){let e=th.utils.randomPrivateKey(),t=yield gf.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return Ra(this,arguments,void 0,function*({key:t}){var n;if(!(zl(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,a=mfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return Ra(this,arguments,void 0,function*({privateKey:t}){if(!zl(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ra(this,arguments,void 0,function*({publicKey:t}){if(!$C(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return st.base64Url(t.x).toUint8Array()})}static sign(e){return Ra(this,arguments,void 0,function*({key:t,data:n}){let i=yield gf.privateKeyToBytes({privateKey:t});return th.sign(n,i)})}static validatePublicKey(e){return Ra(this,arguments,void 0,function*({publicKeyBytes:t}){try{th.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ra(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield gf.publicKeyToBytes({publicKey:t});return th.verify(n,i,a)})}},jl=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},yfe=class extends rE{bytesToPrivateKey(r){return jl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield is.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return jl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield is.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return jl(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield is.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return jl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield is.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return jl(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield is.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return jl(this,arguments,void 0,function*({key:e,data:t}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield is.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return jl(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!$C(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield is.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return jl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield is.privateKeyToBytes({privateKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return jl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield is.publicKeyToBytes({publicKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},gfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wfe=class extends rE{digest(r){return gfe(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield z7.digest({data:t})}})}},pf=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},vfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},Oy=class D0{static bytesToPrivateKey(e){return pf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=I0.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return pf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:st.uint8Array(t).toBase64Url()};return n.kid=yield _r({jwk:n}),n})}static computePublicKey(e){return pf(this,arguments,void 0,function*({key:t}){let n=yield D0.privateKeyToBytes({privateKey:t}),i=I0.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static generateKey(){return pf(this,void 0,void 0,function*(){let e=I0.utils.randomPrivateKey(),t=yield D0.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return pf(this,arguments,void 0,function*({key:t}){var n;if(!(zl(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,a=vfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return pf(this,arguments,void 0,function*({privateKey:t}){if(!zl(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return pf(this,arguments,void 0,function*({publicKey:t}){if(!$C(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return st.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return pf(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield D0.privateKeyToBytes({privateKey:t}),a=yield D0.publicKeyToBytes({publicKey:n});return I0.getSharedSecret(i,a)})}},S0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},bfe=class extends rE{bytesToPrivateKey(r){return S0(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Oy.bytesToPrivateKey({privateKeyBytes:t});default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return S0(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Oy.computePublicKey({key:e});default:throw new Ka(wo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return S0(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Oy.generateKey();default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return S0(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Oy.getPublicKey({key:e});default:throw new Ka(wo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return S0(this,arguments,void 0,function*({privateKey:e}){return Oy.privateKeyToBytes({privateKey:e})})}},Ml=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},JR={Ed25519:{implementation:yfe,names:["Ed25519"]},secp256k1:{implementation:nq,names:["ES256K","secp256k1"]},secp256r1:{implementation:nq,names:["ES256","secp256r1"]},"SHA-256":{implementation:wfe,names:["SHA-256"]},X25519:{implementation:bfe,names:["X25519"]}},Ic=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new Sle}digest(r){return Ml(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e}){let t=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(t?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${rq}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return Ml(this,arguments,void 0,function*({key:e}){let t=yield _r({jwk:e});return`${rq}${t}`})}getPublicKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){let t=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}importKey(r){return Ml(this,arguments,void 0,function*({key:e}){var t;if(!kue(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(t=n.kid)!==null&&t!==void 0||(n.kid=yield _r({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return Ml(this,arguments,void 0,function*({keyUri:e,data:t}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:t,key:n})})}verify(r){return Ml(this,arguments,void 0,function*({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})})}getAlgorithm({algorithm:r}){var e;let t=(e=JR[r])===null||e===void 0?void 0:e.implementation;if(!t)throw new Error(`Algorithm not supported: ${r}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({key:r}){let e=r.alg,t=r.crv;for(let n in JR){let i=JR[n];if(e&&i.names.includes(e)||t&&i.names.includes(t))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${t}`)}getPrivateKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){let t=yield this._keyStore.get(e);if(!t)throw new Error(`Key not found: ${e}`);return t})}},Pfe=class cC{static getJoseSignatureAlgorithmFromPublicKey(e){let t={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(t).includes(e.alg))return e.alg;if(e.crv&&Object.keys(t).includes(e.crv))return t[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(t).join(", ")}. Supported 'crv' values: ${Object.keys(t).join(", ")}.`)}static randomBytes(e){return mue(e)}static randomUuid(){return E2.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let t=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let a=cC.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%i}while(n>t)}else{let i=Math.pow(10,10);do{let a=cC.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%i}while(n>t)}return n.toString().padStart(e,"0")}},xfe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];Se=class{constructor(r,e,t){this.major=r,this.majorEncoded=r<<5,this.name=e,this.terminal=t}toString(){return`Type[${this.major}].${this.name}`}compare(r){return this.major<r.major?-1:this.major>r.major?1:0}static equals(r,e){return r===e||r.major===e.major&&r.name===e.name}};Se.uint=new Se(0,"uint",!0);Se.negint=new Se(1,"negint",!0);Se.bytes=new Se(2,"bytes",!0);Se.string=new Se(3,"string",!0);Se.array=new Se(4,"array",!1);Se.map=new Se(5,"map",!1);Se.tag=new Se(6,"tag",!1);Se.float=new Se(7,"float",!0);Se.false=new Se(7,"false",!0);Se.true=new Se(7,"true",!0);Se.null=new Se(7,"null",!0);Se.undefined=new Se(7,"undefined",!0);Se.break=new Se(7,"break",!0);tt=class{constructor(r,e,t){this.type=r,this.value=e,this.encodedLength=t,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},tb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",kfe=new TextEncoder;_fe=24,Afe=200,Tfe=tb?r=>r.length>=_fe?globalThis.Buffer.from(r):aq(r):r=>r.length>=Afe?kfe.encode(r):aq(r),Kl=r=>Uint8Array.from(r),Ife=tb?(r,e,t)=>G2(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Dfe=tb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Z7(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Rfe=tb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);Cfe=256,X7=class{constructor(r=Cfe){this.chunkSize=r,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(r){let e=this.chunks[this.chunks.length-1];if(this.cursor+r.length<=this.maxCursor+1){let t=e.length-(this.maxCursor-this.cursor)-1;e.set(r,t)}else{if(e){let t=e.length-(this.maxCursor-this.cursor)-1;t<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,t),this.maxCursor=this.cursor-1)}r.length<64&&r.length<this.chunkSize?(e=Rfe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(r,0)):(this.chunks.push(r),this.maxCursor+=r.length)}this.cursor+=r.length}toBytes(r=!1){let e;if(this.chunks.length===1){let t=this.chunks[0];r&&this.cursor>t.length/2?(e=this.cursor===t.length?t:t.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=Ife(t,0,this.cursor)}else e=Dfe(this.chunks,this.cursor);return r&&this.reset(),e}},$fe=class{constructor(r){this.dest=r,this.cursor=0,this.chunks=[r]}reset(){this.cursor=0}push(r){if(this.cursor+r.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(r,this.cursor),this.cursor+=r.length}toBytes(r=!1){let e=this.dest.subarray(0,this.cursor);return r&&this.reset(),e}},kn="CBOR decode error:",Q7="CBOR encode error:",rb=[];rb[23]=1;rb[24]=2;rb[25]=3;rb[26]=5;rb[27]=9;ss=[24,256,65536,4294967296,BigInt("18446744073709551616")];bh.encodedSize=function(r){return La.encodedSize(r.value)};La.encodedSize=function(r){return r<ss[0]?1:r<ss[1]?2:r<ss[2]?3:r<ss[3]?5:9};bh.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};OC=BigInt(-1),ez=BigInt(1);jC.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*OC-ez:e*-1-1;return t<ss[0]?1:t<ss[1]?2:t<ss[2]?3:t<ss[3]?5:9};jC.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};iE.encodedSize=function(r){let e=H2(r);return La.encodedSize(e.length)+e.length};iE.compareTokens=function(r,e){return Vfe(H2(r),H2(e))};cq=new TextDecoder,Wfe=32;tpe=iE;MC.compareTokens=bh.compareTokens;MC.encodedSize=function(r){return La.encodedSize(r.value)};KC.compareTokens=bh.compareTokens;KC.encodedSize=function(r){return La.encodedSize(r.value)};NC.compareTokens=bh.compareTokens;NC.encodedSize=function(r){return La.encodedSize(r.value)};tz=20,rz=21,nz=22,iz=23;LC.encodedSize=function(r,e){let t=r.value;if(t===!1||t===!0||t===null||t===void 0)return 1;if(!e||e.float64!==!0){oz(t);let n=qC(Ac,1);if(t===n||Number.isNaN(t))return 3;if(az(t),n=zC(Ac,1),t===n)return 5}return 9};sz=new ArrayBuffer(9),$a=new DataView(sz,1),Ac=new Uint8Array(sz,0);LC.compareTokens=bh.compareTokens;je=[];for(let r=0;r<=23;r++)je[r]=yr;je[24]=Bfe;je[25]=Ofe;je[26]=jfe;je[27]=Mfe;je[28]=yr;je[29]=yr;je[30]=yr;je[31]=yr;for(let r=32;r<=55;r++)je[r]=yr;je[56]=Kfe;je[57]=Nfe;je[58]=Ufe;je[59]=Lfe;je[60]=yr;je[61]=yr;je[62]=yr;je[63]=yr;for(let r=64;r<=87;r++)je[r]=qfe;je[88]=zfe;je[89]=Ffe;je[90]=Gfe;je[91]=Hfe;je[92]=yr;je[93]=yr;je[94]=yr;je[95]=sE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)je[r]=Zfe;je[120]=Yfe;je[121]=Xfe;je[122]=Qfe;je[123]=epe;je[124]=yr;je[125]=yr;je[126]=yr;je[127]=sE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)je[r]=rpe;je[152]=npe;je[153]=ipe;je[154]=spe;je[155]=ope;je[156]=yr;je[157]=yr;je[158]=yr;je[159]=ape;for(let r=160;r<=183;r++)je[r]=cpe;je[184]=dpe;je[185]=lpe;je[186]=upe;je[187]=fpe;je[188]=yr;je[189]=yr;je[190]=yr;je[191]=ppe;for(let r=192;r<=215;r++)je[r]=hpe;je[216]=mpe;je[217]=ype;je[218]=gpe;je[219]=wpe;je[220]=yr;je[221]=yr;je[222]=yr;je[223]=yr;for(let r=224;r<=243;r++)je[r]=sE("simple values are not supported");je[244]=yr;je[245]=yr;je[246]=yr;je[247]=vpe;je[248]=sE("simple values are not supported");je[249]=Ppe;je[250]=xpe;je[251]=Epe;je[252]=yr;je[253]=yr;je[254]=yr;je[255]=bpe;Gl=[];for(let r=0;r<24;r++)Gl[r]=new tt(Se.uint,r,1);for(let r=-1;r>=-24;r--)Gl[31-r]=new tt(Se.negint,r,1);Gl[64]=new tt(Se.bytes,new Uint8Array(0),1);Gl[96]=new tt(Se.string,"",1);Gl[128]=new tt(Se.array,0,1);Gl[160]=new tt(Se.map,0,1);Gl[244]=new tt(Se.false,!1,1);Gl[245]=new tt(Se.true,!0,1);Gl[246]=new tt(Se.null,null,1);_pe=Object.freeze({float64:!0,mapSorter:Rpe,quickEncodeToken:kpe});Tpe=Ape(),Ipe=new X7,dq=class dz{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Q7} object contains circular references`);return new dz(t,e)}},hf={null:new tt(Se.null,null),undefined:new tt(Se.undefined,void 0),true:new tt(Se.true,!0),false:new tt(Se.false,!1),emptyArray:new tt(Se.array,0),emptyMap:new tt(Se.map,0)},Ef={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new tt(Se.float,r):r>=0?new tt(Se.uint,r):new tt(Se.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new tt(Se.uint,r):new tt(Se.negint,r)},Uint8Array(r,e,t,n){return new tt(Se.bytes,r)},string(r,e,t,n){return new tt(Se.string,r)},boolean(r,e,t,n){return r?hf.true:hf.false},null(r,e,t,n){return hf.null},undefined(r,e,t,n){return hf.undefined},ArrayBuffer(r,e,t,n){return new tt(Se.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new tt(Se.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[hf.emptyArray,new tt(Se.break)]:hf.emptyArray;n=dq.createCheck(n,r);let i=[],a=0;for(let o of r)i[a++]=S2(o,t,n);return t.addBreakTokens?[new tt(Se.array,r.length),i,new tt(Se.break)]:[new tt(Se.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",a=i?r.keys():Object.keys(r),o=i?r.size:a.length,s;if(o){s=new Array(o),n=dq.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,l=0;for(let d of a){let u=i?r.get(d):r[d];c&&u===void 0||(s[l++]=[S2(d,t,n),S2(u,t,n)])}l<o&&(s.length=l)}return s?.length?(Dpe(s,t),t.addBreakTokens?[new tt(Se.map,s.length),s,new tt(Se.break)]:[new tt(Se.map,s.length),s]):t.addBreakTokens===!0?[hf.emptyMap,new tt(Se.break)]:hf.emptyMap}};Ef.Map=Ef.Object;Ef.Buffer=Ef.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ef[`${r}Array`]=Ef.DataView;vUe=Se.uint.majorEncoded,bUe=Se.negint.majorEncoded,PUe=Se.bytes.majorEncoded,xUe=Se.string.majorEncoded,EUe=Se.array.majorEncoded,SUe=Se.float.majorEncoded|tz,kUe=Se.float.majorEncoded|rz,_Ue=Se.float.majorEncoded|nz,AUe=Se.float.majorEncoded|iz,TUe=BigInt(-1),IUe=BigInt(1);DUe=Symbol.for("DONE"),RUe=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(uq||(uq={}));(function(r){r[r.P256=1]="P256",r[r.P384=2]="P384",r[r.P521=3]="P521",r[r.X25519=4]="X25519",r[r.X448=5]="X448",r[r.Ed25519=6]="Ed25519",r[r.Ed448=7]="Ed448",r[r.Secp256k1=8]="Secp256k1"})(Es||(Es={}));(function(r){r[r.EdDSA=-8]="EdDSA",r[r.ES256=-7]="ES256",r[r.ES384=-35]="ES384",r[r.ES512=-36]="ES512",r[r.ES256K=-47]="ES256K"})(Ma||(Ma={}));(function(r){r[r.Kty=1]="Kty",r[r.Kid=2]="Kid",r[r.Alg=3]="Alg",r[r.KeyOps=4]="KeyOps",r[r.BaseIv=5]="BaseIv"})(fq||(fq={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(pq||(pq={}));CUe={"P-256":Es.P256,"P-384":Es.P384,"P-521":Es.P521,X25519:Es.X25519,Ed25519:Es.Ed25519,Ed448:Es.Ed448,secp256k1:Es.Secp256k1},$Ue={[Es.P256]:"P-256",[Es.P384]:"P-384",[Es.P521]:"P-521",[Es.X25519]:"X25519",[Es.Ed25519]:"Ed25519",[Es.Ed448]:"Ed448",[Es.Secp256k1]:"secp256k1"},BUe={EdDSA:Ma.EdDSA,ES256:Ma.ES256,ES384:Ma.ES384,ES512:Ma.ES512,ES256K:Ma.ES256K},OUe={[Ma.EdDSA]:"EdDSA",[Ma.ES256]:"ES256",[Ma.ES384]:"ES384",[Ma.ES512]:"ES512",[Ma.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(hq||(hq={}));(function(r){r[r.Iss=1]="Iss",r[r.Sub=2]="Sub",r[r.Aud=3]="Aud",r[r.Exp=4]="Exp",r[r.Nbf=5]="Nbf",r[r.Iat=6]="Iat",r[r.Cti=7]="Cti",r[r.Nonce=10]="Nonce",r[r.Ueid=256]="Ueid",r[r.Sueids=257]="Sueids",r[r.Oemid=258]="Oemid",r[r.Hwmodel=259]="Hwmodel",r[r.Hwversion=260]="Hwversion",r[r.Secboot=262]="Secboot",r[r.Dbgstat=263]="Dbgstat",r[r.Location=264]="Location",r[r.Profile=265]="Profile",r[r.Submods=266]="Submods",r[r.Measres=272]="Measres",r[r.Intuse=268]="Intuse"})(mq||(mq={}));(function(r){r[r.Enabled=0]="Enabled",r[r.Disabled=1]="Disabled",r[r.DisabledSinceBoot=2]="DisabledSinceBoot",r[r.DisabledPermanently=3]="DisabledPermanently",r[r.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(yq||(yq={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(gq||(gq={}));FC={};PC(FC,{extractDidFragment:()=>Zs,getServices:()=>$pe,getVerificationMethodByKey:()=>Bpe,getVerificationMethodTypes:()=>uz,getVerificationMethods:()=>oE,getVerificationRelationshipsById:()=>fz,isDidService:()=>pz,isDidVerificationMethod:()=>V2,isDwnDidService:()=>Ope,isPortableDid:()=>Ph,keyBytesToMultibaseId:()=>hz,multibaseIdToKeyBytes:()=>mz});Ss=class yz{constructor({uri:e,document:t,metadata:n,keyManager:i}){this.uri=e,this.document=t,this.metadata=n,this.keyManager=i}async export(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let t=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:i});t.push({...a})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(o=>Zs(o.id)===(Zs(e?.methodId)??Zs(this.document.assertionMethod?.[0])));if(!(t&&t.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:t.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:Pfe.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:s}){return await a.verify({data:o,key:i,signature:s})}}}static async import({portableDid:e,keyManager:t=new Ic}){let n=oE({didDocument:e.document});if(n.length===0)throw new nt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await t.importKey({key:i})}for(let i of n){if(!i.publicKeyJwk)throw new Error(`Verification method '${i.id}' does not contain a public key in JWK format`);let a=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:a})}return new yz({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},sb=class{static async getSigningMethod(r){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(r,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},gz=(r=>(r[r.Discoverable=0]="Discoverable",r[r.Organization=1]="Organization",r[r.Government=2]="Government",r[r.Corporation=3]="Corporation",r[r.LocalBusiness=4]="LocalBusiness",r[r.SoftwarePackage=5]="SoftwarePackage",r[r.WebApp=6]="WebApp",r[r.FinancialInstitution=7]="FinancialInstitution",r))(gz||{}),GC=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(GC||{}),wz=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(wz||{}),wq="0123456789abcdef",vz=[],vq=[];for(let r=0;r<256;r++)vz[r]=wq[r>>4&15]+wq[r&15],r<16&&(r<10?vq[48+r]=r:vq[87+r]=r);jpe=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=vz[r[n++]];return t},Mpe=(r,e=0)=>{let t=r.length||0;if(!e){let o=t;for(;o--;)e+=r[o].length}let n=new Uint8Array(e),i=e,a=t;for(;a--;)i-=r[a].length,n.set(r[a],i);return n},bq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Kpe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(k0=0;k0<bq.length;k0++)Kpe[bq.charCodeAt(k0)]=k0;Npe=new TextDecoder,bz=(r,e)=>e?new TextDecoder(e).decode(r):Npe.decode(r),Upe=new TextEncoder,Fl=r=>Upe.encode(r),Pq=typeof window<"u"?window:self,xq=Pq.crypto||Pq.msCrypto||{},jUe=xq.subtle||xq.webkitSubtle;br.bytes=-1;br._floatConversionDetected=!1;br._encode=function(r,e){if(e!=null)switch(Pz(e)){case"object":br.dict(r,e);break;case"map":br.dictMap(r,e);break;case"array":br.list(r,e);break;case"set":br.listSet(r,e);break;case"string":br.string(r,e);break;case"number":br.number(r,e);break;case"boolean":br.number(r,e);break;case"arraybufferview":br.buffer(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":br.buffer(r,new Uint8Array(e));break}};aE=new Uint8Array([101]),xz=new Uint8Array([100]),Ez=new Uint8Array([108]);br.buffer=function(r,e){r.push(Fl(e.length+":"),e)};br.string=function(r,e){r.push(Fl(Fl(e).byteLength+":"+e))};br.number=function(r,e){if(Number.isInteger(e))return r.push(Fl("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,a=n*t+i;r.push(Fl("i"+a+"e")),a!==e&&!br._floatConversionDetected&&(br._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};br.dict=function(r,e){r.push(xz);let t=0,n,i=Object.keys(e).sort(),a=i.length;for(;t<a;t++)n=i[t],e[n]!=null&&(br.string(r,n),br._encode(r,e[n]));r.push(aE)};br.dictMap=function(r,e){r.push(xz);let t=Array.from(e.keys()).sort();for(let n of t)e.get(n)!=null&&(ArrayBuffer.isView(n)?br._encode(r,n):br.string(r,String(n)),br._encode(r,e.get(n)));r.push(aE)};br.list=function(r,e){let t=0,n=e.length;for(r.push(Ez);t<n;t++)e[t]!=null&&br._encode(r,e[t]);r.push(aE)};br.listSet=function(r,e){r.push(Ez);for(let t of e)t!=null&&br._encode(r,t);r.push(aE)};Lpe=br,qpe=105,zpe=58,Fpe=100,Gpe=108,HC=101;bt.bytes=0;bt.position=0;bt.data=null;bt.encoding=null;bt.next=function(){switch(bt.data[bt.position]){case Fpe:return bt.dictionary();case Gpe:return bt.list();case qpe:return bt.integer();default:return bt.buffer()}};bt.find=function(r){let e=bt.position,t=bt.data.length,n=bt.data;for(;e<t;){if(n[e]===r)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(r)+'" [0x'+r.toString(16)+"]")};bt.dictionary=function(){bt.position++;let r={};for(;bt.data[bt.position]!==HC;){let e=bt.buffer(),t=bz(e);t.includes("\uFFFD")&&(t=jpe(e)),r[t]=bt.next()}return bt.position++,r};bt.list=function(){bt.position++;let r=[];for(;bt.data[bt.position]!==HC;)r.push(bt.next());return bt.position++,r};bt.integer=function(){let r=bt.find(HC),e=Sz(bt.data,bt.position+1,r);return bt.position+=r+1-bt.position,e};bt.buffer=function(){let r=bt.find(zpe),e=Sz(bt.data,bt.position,r),t=++r+e;return bt.position=t,bt.encoding?bz(bt.data.slice(r,t)):bt.data.slice(r,t)};Hpe=bt;kz=cE,Xpe=kz,_z={encode:Lpe,decode:Hpe,byteLength:kz,encodingLength:Xpe},Qpe=/^(\d{1,3}\.){3,3}\d{1,3}$/,ehe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Cd={name:"v4",size:4,isFormat:r=>Qpe.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let a=0;a<n;){let o=r.charCodeAt(a++);o===46?(e[t++]=i,i=0):i=i*10+(o-48)}return e[t]=i,e},decode(r,e){return e=~~e,`${r[e++]}.${r[e++]}.${r[e++]}.${r[e]}`}},xf={name:"v6",size:16,isFormat:r=>r.length>0&&ehe.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,a=0,o=0,s=!0,c=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let d=r.charCodeAt(l);d===58?(s?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(c===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2),a=0,o=0),s=!0,c=!1):d===46?(t<n&&(e[t]=o),t++,o=0,a=0,s=!1,c=!0):(s=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(s===!1)c===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2);else if(i===0)t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2;else if(i!==-1){t+=2;for(let l=Math.min(t-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=t}if(i!==t&&i!==-1)for(t>n-2&&(t=n-2);n>i;)e[--n]=t<n&&t>i?e[--t]:0;else for(;t<n;)e[t++]=0;return e},decode(r,e){e=~~e;let t="";for(let n=0;n<16;n+=2)n!==0&&(t+=":"),t+=(r[e+n]<<8|r[e+n+1]).toString(16);return t.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};Y0.bytes=0;ab.bytes=0;ph=r=>r instanceof Uint8Array;R0={},Rz=new Array(255);for(let r=0;r<=15;r+=1){let e=r.toString(16),t=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),o=r<<4|n,s=`${e}${i}`;Rz[o]=s,R0[s]=o,R0[`${t}${i}`]=o,R0[`${e}${a}`]=o,R0[`${t}${a}`]=o}}dhe=Math.pow(2,24),lhe=Math.pow(2,16),uhe=Math.pow(2,8),Ll=(r,e)=>r[e]*dhe+r[e+1]*lhe+r[e+2]*uhe+r[e+3],qt=(r,e)=>r[e]<<8|r[e+1],ql=(r,e,t)=>(e=+e,r[t+3]=e,e=e>>>8,r[t+2]=e,e=e>>>8,r[t+1]=e,e=e>>>8,r[t]=e,t+4),ot=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);phe=0,kq=32768,dC=32768,hhe=~dC,Cz=32768,mhe=~Cz;Ze=Hr({encode(r,e,t){e||(e=new Uint8Array(Ze.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let o=0;o<a.length;o++){let s=WC(e,a[o],t+1);e[t]=s,t+=s+1}}return e[t++]=0,Ze.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,a=0,o=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let s=r[e++];if(a+=o?0:1,s===0)break;if(s&192)if((s&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let c=qt(r,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+s>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=s+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(ab(r,e,e+s)),e+=s,a+=o?0:s}}return Ze.decode.bytes=a,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:Sf(r.replace(/^\.|\.$/gm,""))+2}}),mi=Hr({encode(r,e,t){e||(e=new Uint8Array(mi.encodingLength(r))),t||(t=0);let n=WC(e,r,t+1);return e[t]=n,mi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=ab(r,e+1,e+1+t);return mi.decode.bytes=t+1,n},encodingLength(r){return Sf(r)+1}}),jy=Hr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(jy.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?kq:phe;return ot(e,r.id||0,t),ot(e,n|i,t+2),ot(e,r.questions.length,t+4),ot(e,r.answers.length,t+6),ot(e,r.authorities.length,t+8),ot(e,r.additionals.length,t+10),e},decode(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=qt(r,e+2);return{id:qt(r,e),type:t&kq?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:she(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:ihe(t&15),questions:new Array(qt(r,e+4)),answers:new Array(qt(r,e+6)),authorities:new Array(qt(r,e+8)),additionals:new Array(qt(r,e+10))}},encodingLength(){return 12}}),k2=Hr({encode(r,e,t){e||(e=new Uint8Array(k2.encodingLength(r))),t||(t=0);let n=r.length;return ot(e,n,t),Xo(r,e,t+2,0,n),k2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n=r.slice(e+2,e+2+t);return k2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),_2=Hr({encode(r,e,t){return e||(e=new Uint8Array(_2.encodingLength(r))),t||(t=0),Ze.encode(r,e,t+2),ot(e,Ze.encode.bytes,t),_2.encode.bytes=Ze.encode.bytes+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n=Ze.decode(r,e+2);return _2.decode.bytes=t+2,n},encodingLength(r){return Ze.encodingLength(r)+2}}),A2=Hr({encode(r,e,t){e||(e=new Uint8Array(A2.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.mname,e,t),t+=Ze.encode.bytes,Ze.encode(r.rname,e,t),t+=Ze.encode.bytes,ql(e,r.serial||0,t),t+=4,ql(e,r.refresh||0,t),t+=4,ql(e,r.retry||0,t),t+=4,ql(e,r.expire||0,t),t+=4,ql(e,r.minimum||0,t),t+=4,ot(e,t-n-2,n),A2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=Ze.decode(r,e),e+=Ze.decode.bytes,n.rname=Ze.decode(r,e),e+=Ze.decode.bytes,n.serial=Ll(r,e),e+=4,n.refresh=Ll(r,e),e+=4,n.retry=Ll(r,e),e+=4,n.expire=Ll(r,e),e+=4,n.minimum=Ll(r,e),e+=4,A2.decode.bytes=e-t,n},encodingLength(r){return 22+Ze.encodingLength(r.mname)+Ze.encodingLength(r.rname)}}),T2=Hr({encode(r,e,t){Array.isArray(r)||(r=[r]);for(let i=0;i<r.length;i++)if(typeof r[i]=="string"&&(r[i]=VC(r[i])),!ph(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(T2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,Xo(i,e,t,0,i.length),t+=i.length}),ot(e,t-n-2,n),T2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=qt(r,e);e+=2;let i=[];for(;n>0;){let a=r[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(r.slice(e,e+a)),e+=a,n-=a}return T2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Sf(t)+1:e+=t.length+1}),e}}),I2=Hr({encode(r,e,t){e||(e=new Uint8Array(I2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=VC(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return Xo(r,e,t,0,i),t+=i,ot(e,t-n-2,n),I2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=qt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,I2.decode.bytes=e-t,i},encodingLength(r){return r?(ph(r)?r.length:Sf(r))+2:2}}),D2=Hr({encode(r,e,t){e||(e=new Uint8Array(D2.encodingLength(r))),t||(t=0);let n=t;return t+=2,mi.encode(r.cpu,e,t),t+=mi.encode.bytes,mi.encode(r.os,e,t),t+=mi.encode.bytes,ot(e,t-n-2,n),D2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=mi.decode(r,e),e+=mi.decode.bytes,n.os=mi.decode(r,e),e+=mi.decode.bytes,D2.decode.bytes=e-t,n},encodingLength(r){return mi.encodingLength(r.cpu)+mi.encodingLength(r.os)+2}}),zy=Hr({encode(r,e,t){return e||(e=new Uint8Array(zy.encodingLength(r))),t||(t=0),Ze.encode(r,e,t+2),ot(e,Ze.encode.bytes,t),zy.encode.bytes=Ze.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Ze.decode(r,e+2);return zy.decode.bytes=Ze.decode.bytes+2,t},encodingLength(r){return Ze.encodingLength(r)+2}}),R2=Hr({encode(r,e,t){e||(e=new Uint8Array(R2.encodingLength(r))),t||(t=0),ot(e,r.priority||0,t+2),ot(e,r.weight||0,t+4),ot(e,r.port||0,t+6),Ze.encode(r.target,e,t+8);let n=Ze.encode.bytes+6;return ot(e,n,t),R2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n={};return n.priority=qt(r,e+2),n.weight=qt(r,e+4),n.port=qt(r,e+6),n.target=Ze.decode(r,e+8),R2.decode.bytes=t+2,n},encodingLength(r){return 8+Ze.encodingLength(r.target)}}),vf=Hr({encode(r,e,t){let n=vf.encodingLength(r);return e||(e=new Uint8Array(vf.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=vf.ISSUER_CRITICAL),ot(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,mi.encode(r.tag,e,t),t+=mi.encode.bytes,WC(e,r.value,t),t+=Sf(r.value),vf.encode.bytes=n,e},decode(r,e){e||(e=0);let t=qt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=mi.decode(r,e),e+=mi.decode.bytes,i.value=ab(r,e,n+t),i.issuerCritical=!!(i.flags&vf.ISSUER_CRITICAL),vf.decode.bytes=t+2,i},encodingLength(r){return mi.encodingLength(r.tag)+mi.encodingLength(r.value)+2}});vf.ISSUER_CRITICAL=128;C2=Hr({encode(r,e,t){e||(e=new Uint8Array(C2.encodingLength(r))),t||(t=0);let n=t;return t+=2,ot(e,r.preference||0,t),t+=2,Ze.encode(r.exchange,e,t),t+=Ze.encode.bytes,ot(e,t-n-2,n),C2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=qt(r,e),e+=2,n.exchange=Ze.decode(r,e),e+=Ze.decode.bytes,C2.decode.bytes=e-t,n},encodingLength(r){return 4+Ze.encodingLength(r.exchange)}}),$z=Hr({encode(r,e,t){return e||(e=new Uint8Array($z.encodingLength(r))),t||(t=0),ot(e,4,t),t+=2,Cd.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,Cd.decode(r,e)},bytes:6}),$2=Hr({encode(r,e,t){return e||(e=new Uint8Array($2.encodingLength(r))),t||(t=0),ot(e,16,t),t+=2,xf.encode(r,e,t),$2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=xf.decode(r,e);return $2.decode.bytes=18,t},bytes:18}),_q=r=>new Uint8Array(r),Nl=Hr({encode(r,e,t){e||(e=new Uint8Array(Nl.encodingLength(r))),t||(t=0);let n=t,i=Eq(r.code);if(ot(e,i,t),t+=2,r.data)ot(e,r.data.length,t),t+=2,Xo(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let a=r.sourcePrefixLength||0,o=r.family||the(r.ip,_q),s=rhe(r.ip,_q),c=Math.ceil(a/8);ot(e,c+4,t),t+=2,ot(e,o,t),t+=2,e[t++]=a,e[t++]=r.scopePrefixLength||0,Xo(s,e,t,0,c),t+=c}break;case 11:r.timeout?(ot(e,2,t),t+=2,ot(e,r.timeout,t),t+=2):(ot(e,0,t),t+=2);break;case 12:{let a=r.length||0;ot(e,a,t),t+=2,e.fill(0,t,t+a),t+=a}break;case 14:{let a=r.tags.length*2;ot(e,a,t),t+=2;for(let o of r.tags)ot(e,o,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return Nl.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=qt(r,e),t.type=ohe(t.code),e+=2;let n=qt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=qt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);Xo(r,i,0,e,e+n-4),t.ip=nhe(i)}break;case 11:n>0&&(t.timeout=qt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(qt(r,e)),e+=2}return Nl.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(Eq(r.code)){case 8:{let e=r.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)}}),bf=Hr({encode(r,e,t){e||(e=new Uint8Array(bf.encodingLength(r))),t||(t=0);let n=t,i=Ly(r,Nl);return ot(e,i,t),t=M0(r,Nl,e,t+2),bf.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=qt(r,e);e+=2;let a=0;for(;i>0;)n[a++]=Nl.decode(r,e),e+=Nl.decode.bytes,i-=Nl.decode.bytes;return bf.decode.bytes=e-t,n},encodingLength(r){return 2+Ly(r||[],Nl)}}),Rd=Hr({encode(r,e,t){e||(e=new Uint8Array(Rd.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!ph(i))throw new Error("Key must be a Buffer");return t+=2,ot(e,r.flags,t),t+=2,e[t]=Rd.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,Xo(i,e,t,0,i.length),t+=i.length,Rd.encode.bytes=t-n,ot(e,Rd.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);if(e+=2,n.flags=qt(r,e),e+=2,r[e]!==Rd.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=r[e],e+=1,n.key=r.slice(e,t+i+2),e+=n.key.length,Rd.decode.bytes=e-t,n},encodingLength(r){return 6+Sf(r.key)}});Rd.PROTOCOL_DNSSEC=3;Rd.ZONE_KEY=128;Rd.SECURE_ENTRYPOINT=32768;C0=Hr({encode(r,e,t){e||(e=new Uint8Array(C0.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!ph(i))throw new Error("Signature must be a Buffer");return t+=2,ot(e,Z0(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,ql(e,r.originalTTL,t),t+=4,ql(e,r.expiration,t),t+=4,ql(e,r.inception,t),t+=4,ot(e,r.keyTag,t),t+=2,Ze.encode(r.signersName,e,t),t+=Ze.encode.bytes,Xo(i,e,t,0,i.length),t+=i.length,C0.encode.bytes=t-n,ot(e,C0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.typeCovered=dE(qt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=Ll(r,e),e+=4,n.expiration=Ll(r,e),e+=4,n.inception=Ll(r,e),e+=4,n.keyTag=qt(r,e),e+=2,n.signersName=Ze.decode(r,e),e+=Ze.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,C0.decode.bytes=e-t,n},encodingLength(r){return 20+Ze.encodingLength(r.signersName)+Sf(r.signature)}}),$0=Hr({encode(r,e,t){e||(e=new Uint8Array($0.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.mbox||".",e,t),t+=Ze.encode.bytes,Ze.encode(r.txt||".",e,t),t+=Ze.encode.bytes,$0.encode.bytes=t-n,ot(e,$0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=Ze.decode(r,e)||".",e+=Ze.decode.bytes,n.txt=Ze.decode(r,e)||".",e+=Ze.decode.bytes,$0.decode.bytes=e-t,n},encodingLength(r){return 2+Ze.encodingLength(r.mbox||".")+Ze.encodingLength(r.txt||".")}}),Yo=Hr({encode(r,e,t){e||(e=new Uint8Array(Yo.encodingLength(r))),t||(t=0);let n=t,i=[];for(let a=0;a<r.length;a++){let o=Z0(r[a]);i[o>>8]===void 0&&(i[o>>8]=[]),i[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<i.length;a++)if(i[a]!==void 0){let o=VC(i[a]);e[t]=a,t+=1,e[t]=o.length,t+=1,Xo(o,e,t,0,o.length),t+=o.length}return Yo.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let a=r[e];e+=1;let o=r[e];e+=1;for(let s=0;s<o;s++){let c=r[e+s];for(let l=0;l<8;l++)if(c&1<<7-l){let d=dE(a<<8|s<<3|l);i.push(d)}}e+=o}return Yo.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=Z0(r[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let t=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(t+=2+Math.ceil((e[n]+1)/8));return t}}),B0=Hr({encode(r,e,t){e||(e=new Uint8Array(B0.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.nextDomain,e,t),t+=Ze.encode.bytes,Yo.encode(r.rrtypes,e,t),t+=Yo.encode.bytes,B0.encode.bytes=t-n,ot(e,B0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.nextDomain=Ze.decode(r,e),e+=Ze.decode.bytes,n.rrtypes=Yo.decode(r,e,i-(e-t)),e+=Yo.decode.bytes,B0.decode.bytes=e-t,n},encodingLength(r){return 2+Ze.encodingLength(r.nextDomain)+Yo.encodingLength(r.rrtypes)}}),O0=Hr({encode(r,e,t){e||(e=new Uint8Array(O0.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!ph(i))throw new Error("salt must be a Buffer");let a=r.nextDomain;if(!ph(a))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,ot(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,Xo(i,e,t,0,i.length),t+=i.length,e[t]=a.length,t+=1,Xo(a,e,t,0,a.length),t+=a.length,Yo.encode(r.rrtypes,e,t),t+=Yo.encode.bytes,O0.encode.bytes=t-n,ot(e,O0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=qt(r,e),e+=2;let a=r[e];e+=1,n.salt=r.slice(e,e+a),e+=a;let o=r[e];return e+=1,n.nextDomain=r.slice(e,e+o),e+=o,n.rrtypes=Yo.decode(r,e,i-(e-t)),e+=Yo.decode.bytes,O0.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+Yo.encodingLength(r.rrtypes)}}),j0=Hr({encode(r,e,t){e||(e=new Uint8Array(j0.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!ph(i))throw new Error("Digest must be a Buffer");return t+=2,ot(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,Xo(i,e,t,0,i.length),t+=i.length,j0.encode.bytes=t-n,ot(e,j0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.keyTag=qt(r,e),e+=2,n.algorithm=r[e],e+=1,n.digestType=r[e],e+=1,n.digest=r.slice(e,t+i+2),e+=n.digest.length,j0.decode.bytes=e-t,n},encodingLength(r){return 6+Sf(r.digest)}}),Uy=Hr({encode(r,e,t){e||(e=new Uint8Array(Uy.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=Sq(r.fingerprint),a=lC(r.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${a}`);return che(e,r.fingerprint,t,t+=i),Uy.encode.bytes=t-n,ot(e,Uy.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};e+=2,n.algorithm=r[e],e+=1,n.hash=r[e],e+=1;let i=lC(n.hash);return n.fingerprint=ahe(r,e,e+i),e+=i,Uy.decode.bytes=e-t,n},encodingLength(r){return 4+Sq(r.fingerprint)}});Uy.getFingerprintLengthForHashType=lC;Ba=Hr({encode(r,e,t){e||(e=new Uint8Array(Ba.encodingLength(r))),t||(t=0);let n=t;if(Ze.encode(r.name,e,t),t+=Ze.encode.bytes,ot(e,Z0(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");ot(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,ot(e,r.flags||0,t+6),t+=8,bf.encode(r.options||[],e,t),t+=bf.encode.bytes}else{let i=Iz(r.class===void 0?"IN":r.class);r.flush&&(i|=dC),ot(e,i,t+2),ql(e,r.ttl||0,t+4),t+=8;let a=ZR(r.type);a.encode(r.data,e,t),t+=a.encode.bytes}return Ba.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=Ze.decode(r,e),e+=Ze.decode.bytes,t.type=dE(qt(r,e)),t.type==="OPT")t.udpPayloadSize=qt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=qt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=bf.decode(r,e+8),e+=8+bf.decode.bytes;else{let i=qt(r,e+2);t.ttl=Ll(r,e+4),t.class=Tz(i&hhe),t.flush=!!(i&dC);let a=ZR(t.type);t.data=a.decode(r,e+8),e+=8+a.decode.bytes}return Ba.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return Ze.encodingLength(r.name)+8+ZR(r.type).encodingLength(e)}}),Fy=Hr({encode(r,e,t){e||(e=new Uint8Array(Fy.encodingLength(r))),t||(t=0);let n=t;return Ze.encode(r.name,e,t),t+=Ze.encode.bytes,ot(e,Z0(r.type),t),t+=2,ot(e,Iz(r.class===void 0?"IN":r.class),t),t+=2,Fy.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=Ze.decode(r,e),e+=Ze.decode.bytes,n.type=dE(qt(r,e)),e+=2,n.class=Tz(qt(r,e)),e+=2,n.class&Cz&&(n.class&=mhe),Fy.decode.bytes=e-t,n},encodingLength(r){return Ze.encodingLength(r.name)+4}}),yhe=1024,os={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(ghe(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),jy.encode(r,e,t),t+=jy.encode.bytes,t=M0(r.questions,Fy,e,t),t=M0(r.answers,Ba,e,t),t=M0(r.authorities,Ba,e,t),t=M0(r.additionals,Ba,e,t),os.encode.bytes=t-i,n&&Y2.bytes!==e.length?e.slice(0,Y2.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=jy.decode(r,e);return e+=jy.decode.bytes,e=g2(n.questions,Fy,r,e),e=g2(n.answers,Ba,r,e),e=g2(n.authorities,Ba,r,e),e=g2(n.additionals,Ba,r,e),os.decode.bytes=e-t,n},encodingLength:function(r){return jy.encodingLength(r)+Ly(r.questions||[],Fy)+Ly(r.answers||[],Ba)+Ly(r.authorities||[],Ba)+Ly(r.additionals||[],Ba)}};os.encode.bytes=0;os.decode.bytes=0;J2={encode:function(r,e,t){return e=os.encode(W2(r,"query"),e,t),J2.encode.bytes=os.encode.bytes,e},decode:function(r,e){let t=os.decode(r,e);return J2.decode.bytes=os.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return os.encodingLength(W2(r,"query"))}};J2.encode.bytes=0;J2.decode.bytes=0;Z2={encode:function(r,e,t){return e=os.encode(W2(r,"response"),e,t),Z2.encode.bytes=os.encode.bytes,e},decode:function(r,e){let t=os.decode(r,e);return Z2.decode.bytes=os.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return os.encodingLength(W2(r,"response"))}};Z2.encode.bytes=0;Z2.decode.bytes=0;Y2=os.encode,uC=os.decode,ghe=os.encodingLength;Bz.bytes=0;Oz.bytes=0;Mz="dht";Ehe=0,mf=7200,B2=";",Js=",",Uz={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},Lz={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};Tq=O.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",zz=class fC extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.verificationMethods?.some(d=>!(d.algorithm in Uz)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:i}),o=await qy.identityKeyToIdentifier({identityKey:a}),s={id:o,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},c=[...t.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let u=d.id&&d.id.split("#").pop()==="0"?i:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:u}),p=d.id??f.kid??await _r({jwk:f});p=`${o}#${Zs(p)}`,s.verificationMethod??=[],s.verificationMethod.push({id:p,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let h of d.purposes??[])s[h]??=[],s[h].push(p)}t.services?.forEach(d=>{s.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,s.service.push(d)});let l=new Ss({uri:o,document:s,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let d=await fC.publish({did:l,gatewayUri:t.gatewayUri});l.metadata=d.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==fC.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new nt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Zs(a.id)===(Zs(t)??Zs(e.assertionMethod?.[0])));if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t=Tq}){return await Iq.put({did:e,gatewayUri:t})}static async resolve(e,t={}){let n=t?.gatewayUri??Tq;try{await qy.identifierToIdentityKey({didUri:e});let{didDocument:i,didDocumentMetadata:a}=await Iq.get({didUri:e,gatewayUri:n});return{...Di,didDocument:i,didDocumentMetadata:a}}catch(i){if(!(i instanceof nt))throw new Error(i);return{...Di,didResolutionMetadata:{error:i.code,...i.message&&{errorMessage:i.message}}}}}};zz.methodName="dht";vo=zz,Iq=class N0{static async get({didUri:e,gatewayUri:t}){let n=qy.identifierToIdentityKeyBytes({didUri:e}),i=await N0.pkarrGet({gatewayUri:t,publicKeyBytes:n}),a=await qy.parseBep44GetMessage({bep44Message:i}),o=await N0.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=i.seq.toString(),o}static async put({did:e,gatewayUri:t}){let n=await N0.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),i=await qy.createBep44PutMessage({dnsPacket:n,publicKeyBytes:qy.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await N0.pkarrPut({gatewayUri:t,bep44Message:i});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:i.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return whe(e)}static async pkarrPut(e){return vhe(e)}static async fromDnsPacket(e){return She(e)}static async toDnsPacket(e){return khe(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},qy=class{static async createBep44PutMessage(r){return bhe(r)}static async identifierToIdentityKey(r){return Kz(r)}static identifierToIdentityKeyBytes(r){return JC(r)}static async identityKeyToIdentifier(r){return xhe(r)}static keyConverter(r){return ZC(r)}static async parseBep44GetMessage(r){return Phe(r)}static parseTxtDataToObject(r){return K0(r)}static parseTxtDataToString(r){return X0(r)}static async validatePreviousDidProof(r){return Nz(r)}static chunkDataIfNeeded(r){return qz(r)}},Hn={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"},Vn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},MUe=new Uint8Array(0),_he=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Ahe=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},The=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return Fz(this,r)}},Ihe=class{constructor(r){this.decoders=r}or(r){return Fz(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Fz=(r,e)=>new Ihe({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Dhe=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Ahe(r,e,t),this.decoder=new The(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rhe=({name:r,prefix:e,encode:t,decode:n})=>new Dhe(r,e,t,n),Che=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let o=new Uint8Array(a*t/8|0),s=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,s+=t,s>=8&&(s-=8,o[l++]=255&c>>s)}if(s>=t||255&c<<8-s)throw new SyntaxError("Unexpected end of data");return o},$he=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",o=0,s=0;for(let c=0;c<r.length;++c)for(s=s<<8|r[c],o+=8;o>t;)o-=t,a+=e[i&s>>o];if(o&&(a+=e[i&s<<t-o]),n)for(;a.length*t&7;)a+="=";return a},lE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rhe({prefix:e,name:r,encode(i){return $he(i,n,t)},decode(i){return Che(i,n,t,r)}}),KUe=lE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),NUe=lE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dq=lE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UUe=lE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Wy=class O2{static encode(e){return Dq.baseEncode(e)}static decodeAsBytes(e,t){if(!O2.isBase64UrlString(e))throw new Vn(Hn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return Dq.baseDecode(e)}static decodeAsString(e,t){let n=O2.decodeAsBytes(e,t);return O2.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}},Bhe=hh($de(),1);(function(r){r.Public="public",r.Private="private"})(pC||(pC={}));Dd=pC,Wo=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Dd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Vn(Hn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Vn(Hn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Vn(Hn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Dd.Private&&(r.d===void 0||r.d.length!==43))throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Vn(Hn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!Wy.isBase64UrlString(r))throw new Vn(Hn.IdNotUsingBase64UrlCharacterSet,`Key ID '${r}' is not a Base64URL string.`)}static validatePublicKeyPurposes(r){if(r===void 0)return;let e=new Set;for(let t of r){if(e.has(t))throw new Vn(Hn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},YC=class{};YC.hashAlgorithmInMultihashCode=18;YC.maxCanonicalizedDeltaSizeInBytes=1e3;Tc=YC,Ohe=hh(Bde(),1),Q0=class hC{static canonicalizeAsBytes(e){let t=hC.removeAllUndefinedProperties(e),n=Ohe.default(t);return Wy.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?hC.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},jhe=Gz,Rq=128,Mhe=127,Khe=~Mhe,Nhe=Math.pow(2,31);Uhe=mC,Lhe=128,Cq=127;qhe=Math.pow(2,7),zhe=Math.pow(2,14),Fhe=Math.pow(2,21),Ghe=Math.pow(2,28),Hhe=Math.pow(2,35),Vhe=Math.pow(2,42),Whe=Math.pow(2,49),Jhe=Math.pow(2,56),Zhe=Math.pow(2,63),Yhe=function(r){return r<qhe?1:r<zhe?2:r<Fhe?3:r<Ghe?4:r<Hhe?5:r<Vhe?6:r<Whe?7:r<Jhe?8:r<Zhe?9:10},Xhe={encode:jhe,decode:Uhe,encodingLength:Yhe},Qhe=Xhe,X2=Qhe,$q=(r,e=0)=>[X2.decode(r,e),X2.decode.bytes],Bq=(r,e,t=0)=>(X2.encode(r,e,t),e),Oq=r=>X2.encodingLength(r),jq=(r,e)=>{let t=e.byteLength,n=Oq(r),i=n+Oq(t),a=new Uint8Array(i+t);return Bq(r,a,0),Bq(t,a,n),a.set(e,i),new Hz(r,t,e,a)},eme=r=>{let e=_he(r),[t,n]=$q(e),[i,a]=$q(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==i)throw new Error("Incorrect length");return new Hz(t,i,o,e)},Hz=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},Vz=({name:r,code:e,encode:t})=>new tme(r,e,t),tme=class{constructor(r,e,t){this.name=r,this.code=e,this.encode=t}digest(r){if(r instanceof Uint8Array){let e=this.encode(r);return e instanceof Uint8Array?jq(this.code,e):e.then(t=>jq(this.code,t))}else throw Error("Unknown type, must be binary type")}},Wz=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Mq=Vz({name:"sha2-256",code:18,encode:Wz("SHA-256")}),LUe=Vz({name:"sha2-512",code:19,encode:Wz("SHA-512")}),_0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Zo=class U0{static hash(e,t){return _0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield Mq.digest(e)).bytes;break;default:throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return _0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield Mq.encode(e);break;default:throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=Q0.canonicalizeAsBytes(e);return yield U0.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=Q0.canonicalizeAsBytes(e),i=yield U0.hashAsNonMultihashBytes(n,t);return yield U0.hashThenEncode(i,t)})}static hashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=yield U0.hash(e,t);return Wy.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=Wy.decodeAsBytes(e,t);try{n=eme(i)}catch{throw new Vn(Hn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let a=Tc.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(yC||(yC={}));w2=yC;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(gC||(gC={}));By=gC,v2=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Jz=class Ca{static createCreateRequest(e){return v2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;Wo.validateEs256kOperationKey(t,Dd.Public),Wo.validateEs256kOperationKey(n,Dd.Public),Ca.validateDidDocumentKeys(i),Ca.validateServices(a);let o=Tc.hashAlgorithmInMultihashCode,s=[{action:By.Replace,document:e.document}],c={updateCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(n,o),patches:s};Ca.validateDeltaSize(c);let l={deltaHash:yield Zo.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(t,o)};return{type:w2.Create,suffixData:l,delta:c}})}static createDeactivateRequest(e){return v2(this,void 0,void 0,function*(){Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.recoveryPublicKey,Dd.Public);let t=Tc.hashAlgorithmInMultihashCode,n=yield Zo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:w2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return v2(this,void 0,void 0,function*(){Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.recoveryPublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextRecoveryPublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextUpdatePublicKey,Dd.Public),Ca.validateDidDocumentKeys(e.document.publicKeys),Ca.validateServices(e.document.services);let t=Tc.hashAlgorithmInMultihashCode,n=yield Zo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:By.Replace,document:e.document}],a=yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),o={patches:i,updateCommitment:a},s=yield Zo.canonicalizeThenHashThenEncode(o,t),c={recoveryCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:s},l=yield e.signer.sign({alg:"ES256K"},c);return{type:w2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:l}})}static createUpdateRequest(e){return v2(this,void 0,void 0,function*(){if(Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.updatePublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextUpdatePublicKey,Dd.Public),Ca.validateServices(e.servicesToAdd),Ca.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let h of e.idsOfServicesToRemove)Wo.validateId(h);if(e.idsOfPublicKeysToRemove!==void 0)for(let h of e.idsOfPublicKeysToRemove)Wo.validateId(h);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let h={action:By.AddServices,services:n};t.push(h)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let h={action:By.RemoveServices,ids:i};t.push(h)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let h={action:By.AddPublicKeys,publicKeys:a};t.push(h)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let h={action:By.RemovePublicKeys,ids:o};t.push(h)}let s=Tc.hashAlgorithmInMultihashCode,c=yield Zo.canonicalizeThenHashThenEncode(e.updatePublicKey,s),l=yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,s),d={patches:t,updateCommitment:l},u=yield Zo.canonicalizeThenHashThenEncode(d,s),f={updateKey:e.updatePublicKey,deltaHash:u},p=yield e.signer.sign({alg:"ES256K"},f);return{type:w2.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:p}})}static validateDidSuffix(e){Zo.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let t=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Vn(Hn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Wo.validateId(n.id),t.has(n.id))throw new Vn(Hn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),Wo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Ca.validateService(n),t.has(n.id))throw new Vn(Hn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){Wo.validateId(e.id);let t=30;if(e.type.length>t){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${t}.`;throw new Vn(Hn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Vn(Hn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Bhe.parse(e.serviceEndpoint).error!==void 0)throw new Vn(Hn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=Q0.canonicalizeAsBytes(e);if(t.length>Tc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Tc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Vn(Hn.DeltaExceedsMaximumSize,n)}}},Kq=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},rme=class Zz{static createLongFormDid(e){return Kq(this,void 0,void 0,function*(){let t=yield Jz.createCreateRequest(e),n=yield Zz.computeDidUniqueSuffix(t.suffixData),i;Tc.network===void 0||Tc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Tc.network}:${n}`;let a={suffixData:t.suffixData,delta:t.delta},o=Q0.canonicalizeAsBytes(a),s=Wy.encode(o);return`${i}:${s}`})}static computeDidUniqueSuffix(e){return Kq(this,void 0,void 0,function*(){let t=Q0.canonicalizeAsBytes(e),n=yield Zo.hash(t,Tc.hashAlgorithmInMultihashCode);return Wy.encode(n)})}},rs=2n**255n-19n,j2=2n**252n+27742317777372353535851937790883648493n,wC=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,vC=0x6666666666666666666666666666666666666666666666666666666666666658n,b2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:rs,n:j2,h:8,Gx:wC,Gy:vC},go=(r="")=>{throw new Error(r)},Yz=r=>typeof r=="string",XC=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?go("Uint8Array expected"):r,Jy=r=>new Uint8Array(r),nme=(r,e)=>XC(Yz(r)?e6(r):Jy(r),e),lt=(r,e=rs)=>{let t=r%e;return t>=0n?t:e+t},Nq=r=>r instanceof Zy?r:go("Point expected"),Zy=class My{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new My(e.x,e.y,1n,lt(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=b2;e=nme(e,32);let i=e.slice();i[31]=e[31]&-129;let a=sme(i);a===0n||(t&&!(0n<a&&a<rs)&&go("bad y coord 1"),!t&&!(0n<a&&a<2n**256n)&&go("bad y coord 2"));let o=lt(a*a),s=lt(o-1n),c=lt(n*o+1n),{isValid:l,value:d}=ame(s,c);l||go("bad y coordinate 3");let u=(d&1n)===1n;return(e[31]&128)!==0!==u&&(d=lt(-d)),new My(d,a,1n,lt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:a,ey:o,ez:s}=Nq(e),c=lt(t*s),l=lt(a*i),d=lt(n*s),u=lt(o*i);return c===l&&d===u}is0(){return this.equals(M2)}negate(){return new My(lt(-this.ex),this.ey,this.ez,lt(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=b2,a=lt(e*e),o=lt(t*t),s=lt(2n*lt(n*n)),c=lt(i*a),l=e+t,d=lt(lt(l*l)-a-o),u=c+o,f=u-s,p=c-o,h=lt(d*f),m=lt(u*p),y=lt(d*p),v=lt(f*u);return new My(h,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:a}=this,{ex:o,ey:s,ez:c,et:l}=Nq(e),{a:d,d:u}=b2,f=lt(t*o),p=lt(n*s),h=lt(a*u*l),m=lt(i*c),y=lt((t+n)*(o+s)-f-p),v=lt(m-h),w=lt(m+h),x=lt(p-d*f),_=lt(y*v),A=lt(w*x),D=lt(y*x),N=lt(v*w);return new My(_,A,N,D)}mul(e,t=!0){if(e===0n)return t===!0?go("cannot multiply by 0"):M2;if(typeof e=="bigint"&&0n<e&&e<j2||go("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(Q2))return lme(e).p;let n=M2,i=Q2;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(b2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(j2/2n,!1).double();return j2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:t,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=Qz(n);return lt(n*i)!==1n&&go("invalid inverse"),{x:lt(e*i),y:lt(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=ime(t);return n[31]|=e&1n?128:0,n}toHex(){return QC(this.toRawBytes())}};Zy.BASE=new Zy(wC,vC,1n,lt(wC*vC));Zy.ZERO=new Zy(0n,1n,1n,0n);({BASE:Q2,ZERO:M2}=Zy),Xz=(r,e)=>r.toString(16).padStart(e,"0"),QC=r=>Array.from(r).map(e=>Xz(e,2)).join(""),e6=r=>{let e=r.length;(!Yz(r)||e%2)&&go("hex invalid 1");let t=Jy(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&go("hex invalid 2"),t[n]=o}return t},ime=r=>e6(Xz(r,32*2)).reverse(),sme=r=>BigInt("0x"+QC(Jy(XC(r)).reverse())),Lq=(...r)=>{let e=Jy(r.reduce((n,i)=>n+XC(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},Qz=(r,e=rs)=>{(r===0n||e<=0n)&&go("no inverse n="+r+" mod="+e);let t=lt(r,e),n=e,i=0n,a=1n,o=1n,s=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}return n===1n?lt(i,e):go("no inverse")},Ad=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=rs;return t},ome=r=>{let e=r*r%rs*r%rs,t=Ad(e,2n)*e%rs,n=Ad(t,1n)*r%rs,i=Ad(n,5n)*n%rs,a=Ad(i,10n)*i%rs,o=Ad(a,20n)*a%rs,s=Ad(o,40n)*o%rs,c=Ad(s,80n)*s%rs,l=Ad(c,80n)*s%rs,d=Ad(l,10n)*i%rs;return{pow_p_5_8:Ad(d,2n)*r%rs,b2:e}},qq=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ame=(r,e)=>{let t=lt(e*e*e),n=lt(t*t*e),i=ome(r*n).pow_p_5_8,a=lt(r*t*i),o=lt(e*a*a),s=a,c=lt(a*qq),l=o===r,d=o===lt(-r),u=o===lt(-r*qq);return l&&(a=s),(d||u)&&(a=c),(lt(a)&1n)===1n&&(a=lt(-a)),{isValid:l||d,value:a}},zq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,cme={bytesToHex:QC,hexToBytes:e6,concatBytes:Lq,mod:lt,invert:Qz,randomBytes:r=>{let e=zq();return e||go("crypto.getRandomValues must be defined"),e.getRandomValues(Jy(r))},sha512Async:async(...r)=>{let e=zq();e||go("crypto.subtle or etc.sha512Async must be defined");let t=Lq(...r);return Jy(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(cme,{sha512Sync:{configurable:!1,get(){return YR},set(r){YR||(YR=r)}}});ih=8,dme=()=>{let r=[],e=256/ih+1,t=Q2,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(ih-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},lme=r=>{let e=Uq||(Uq=dme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=M2,i=Q2,a=1+256/ih,o=2**(ih-1),s=BigInt(2**ih-1),c=2**ih,l=BigInt(ih);for(let d=0;d<a;d++){let u=d*o,f=Number(r&s);r>>=l,f>o&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}},t6=2n**256n,lh=t6-0x1000003d1n,r6=t6-0x14551231950b75fc4402da1732fc9bebfn,eF=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,tF=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,rF={p:lh,n:r6,a:0n,b:7n,Gx:eF,Gy:tF},Gy=32,Fq=r=>et(et(r*r)*r+rF.b),Ii=(r="")=>{throw new Error(r)},uE=r=>typeof r=="bigint",nF=r=>typeof r=="string",XR=r=>uE(r)&&0n<r&&r<lh,iF=r=>uE(r)&&0n<r&&r<r6,sF=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ii("Uint8Array expected"):r,eb=r=>new Uint8Array(r),n6=(r,e)=>sF(nF(r)?fE(r):eb(r),e),et=(r,e=lh)=>{let t=r%e;return t>=0n?t:e+t},Gq=r=>r instanceof Yy?r:Ii("Point expected"),Yy=class Ky{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Ky(e.x,e.y,1n)}static fromHex(e){e=n6(e);let t,n=e[0],i=e.subarray(1),a=Vq(i,0,Gy),o=e.length;if(o===33&&[2,3].includes(n)){XR(a)||Ii("Point hex invalid: x not FE");let s=ume(Fq(a)),c=(s&1n)===1n;(n&1)===1!==c&&(s=et(-s)),t=new Ky(a,s,1n)}return o===65&&n===4&&(t=new Ky(a,Vq(i,Gy,2*Gy),1n)),t?t.ok():Ii("Point is not on curve")}static fromPrivateKey(e){return F0.mul(fme(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:a,py:o,pz:s}=Gq(e),c=et(t*s),l=et(a*i),d=et(n*s),u=et(o*i);return c===l&&d===u}negate(){return new Ky(this.px,et(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:a,py:o,pz:s}=Gq(e),{a:c,b:l}=rF,d=0n,u=0n,f=0n,p=et(l*3n),h=et(t*a),m=et(n*o),y=et(i*s),v=et(t+n),w=et(a+o);v=et(v*w),w=et(h+m),v=et(v-w),w=et(t+i);let x=et(a+s);return w=et(w*x),x=et(h+y),w=et(w-x),x=et(n+i),d=et(o+s),x=et(x*d),d=et(m+y),x=et(x-d),f=et(c*w),d=et(p*y),f=et(d+f),d=et(m-f),f=et(m+f),u=et(d*f),m=et(h+h),m=et(m+h),y=et(c*y),w=et(p*w),m=et(m+y),y=et(h-y),y=et(c*y),w=et(w+y),h=et(m*w),u=et(u+h),h=et(x*w),d=et(v*d),d=et(d-h),h=et(v*m),f=et(x*f),f=et(f+h),new Ky(d,u,f)}mul(e,t=!0){if(!t&&e===0n)return K2;if(iF(e)||Ii("invalid scalar"),this.equals(F0))return yme(e).p;let n=K2,i=F0;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}mulAddQUns(e,t,n){return this.mul(t,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:t,pz:n}=this;if(this.equals(K2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=aF(n);return et(n*i)!==1n&&Ii("invalid inverse"),{x:et(e*i),y:et(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!XR(e)||!XR(t))&&Ii("Point invalid: x or y"),et(t*t)===Fq(e)?this:Ii("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:t,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+Wq(t)+(e?"":Wq(n))}toRawBytes(e=!0){return fE(this.toHex(e))}};Yy.BASE=new Yy(eF,tF,1n);Yy.ZERO=new Yy(0n,1n,0n);({BASE:F0,ZERO:K2}=Yy),oF=(r,e)=>r.toString(16).padStart(e,"0"),i6=r=>Array.from(r).map(e=>oF(e,2)).join(""),fE=r=>{let e=r.length;(!nF(r)||e%2)&&Ii("hex invalid 1");let t=eb(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Ii("hex invalid 2"),t[n]=o}return t},pE=r=>BigInt("0x"+(i6(r)||"0")),Vq=(r,e,t)=>pE(r.slice(e,t)),s6=r=>uE(r)&&r>=0n&&r<t6?fE(oF(r,2*Gy)):Ii("bigint expected"),Wq=r=>i6(s6(r)),Jq=(...r)=>{let e=eb(r.reduce((n,i)=>n+sF(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},aF=(r,e=lh)=>{(r===0n||e<=0n)&&Ii("no inverse n="+r+" mod="+e);let t=et(r,e),n=e,i=0n,a=1n,o=1n,s=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}return n===1n?et(i,e):Ii("no inverse")},ume=r=>{let e=1n;for(let t=r,n=(lh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%lh),t=t*t%lh;return et(e*e)===r?e:Ii("sqrt invalid")},fme=r=>(uE(r)||(r=pE(n6(r,Gy))),iF(r)?r:Ii("private key out of range")),Zq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;hme={hexToBytes:fE,bytesToHex:i6,concatBytes:Jq,bytesToNumberBE:pE,numberToBytesBE:s6,mod:et,invert:aF,hmacSha256Async:async(r,...e)=>{let t=Zq();if(!t)return Ii("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return eb(await n.sign("HMAC",i,Jq(...e)))},hmacSha256Sync:N2,hashToPrivateKey:pme,randomBytes:r=>{let e=Zq();return e||Ii("crypto.getRandomValues must be defined"),e.getRandomValues(eb(r))}};Object.defineProperties(hme,{hmacSha256Sync:{configurable:!1,get(){return N2},set(r){N2||(N2=r)}}});sh=8,mme=()=>{let r=[],e=256/sh+1,t=F0,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(sh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},yme=r=>{let e=Hq||(Hq=mme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=K2,i=F0,a=1+256/sh,o=2**(sh-1),s=BigInt(2**sh-1),c=2**sh,l=BigInt(sh);for(let d=0;d<a;d++){let u=d*o,f=Number(r&s);r>>=l,f>o&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(Yq||(Yq={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(Xq||(Xq={}));A0=class rh{static appendPathToUrl({baseUrl:e,path:t}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=t.startsWith("/")?t.substring(1):t,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:t,services:n,verificationMethods:i}){let a=await rh.createIonDocument({services:n,verificationMethods:i}),o=rh.normalizeJwk(e),s=rh.normalizeJwk(t);return await rme.createLongFormDid({document:a,recoveryKey:o,updateKey:s})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await Jz.createCreateRequest({document:e,recoveryKey:rh.normalizeJwk(t),updateKey:rh.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let a of t){let o=a.id??a.publicKeyJwk.kid??await _r({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let s={id:o,publicKeyJwk:rh.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(s)}let i=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:i}}static normalizeJwk(e){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);return n}},gme=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(gme||{}),wme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Qq="https://ion.tbd.engineering",vme=class L0 extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.verificationMethods?.some(h=>!(h.algorithm in wme)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(h=>"id"in h).map(h=>h.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(h=>!h.id||!h.type||!h.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let h of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:h.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:h.id,publicKeyJwk:y,purposes:h.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),s=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:c}),d=await A0.computeLongFormDidUri({recoveryKey:s,updateKey:l,services:t.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await L0.resolve(d,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let p=new Ss({uri:d,document:u,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:s,updateKey:l},keyManager:e});if(t.publish??!0){let h=await L0.publish({did:p,gatewayUri:t.gatewayUri});p.metadata=h.didDocumentMetadata}return p}static async getSigningMethod({didDocument:e,methodId:t}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(t??e.assertionMethod?.[0]));if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==L0.methodName)throw new nt("methodNotSupported","Method not supported");return await Ss.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=Qq}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:fz({didDocument:e.document,methodId:o.id})}))??[],i=await A0.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await A0.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=A0.appendPathToUrl({baseUrl:t,path:"/operations"}),s=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:s.ok},didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:"internalError",errorMessage:`Failed to publish DID document for: ${e.uri}`}}}}static async resolve(e,t={}){let n=Jn.parse(e);if(!n)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L0.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??Qq;try{let a=A0.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new nt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:s,didDocumentMetadata:c}=await o.json();return{...Di,...s&&{didDocument:s},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof nt))throw new Error(a);return{...Di,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};vme.methodName="ion";cF=class q0 extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),o=st.object(a).toBase64Url(),s=`did:${q0.methodName}:${o}`,c=(await q0.resolve(s)).didDocument;return new Ss({uri:s,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Jn.parse(e.id);if(t&&t.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==q0.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new nt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Jn.parse(e),i;try{i=n?st.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==q0.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:i}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],i.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...Di,didDocument:a}}};cF.methodName="jwk";bo=cF,bme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},U2=class Ny{static async jwkToMulticodec({jwk:e}){let t=[];e.crv&&(t.push(e.crv),e.d?t.push("private"):t.push("public"));let n=t.join(":"),i=Ny.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ua.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":xs.compressPublicKey,secp256k1:ns.compressPublicKey}[e];if(!t)throw new nt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:is,"P-256":xs,secp256k1:ns}[e];if(!t)throw new nt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static async multicodecToJwk({code:e,name:t}){if(!(t?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");t=t===void 0?Ua.getNameFromCode({code:e}):t;let n=t,i=Ny.MULTICODEC_TO_JWK[n];if(i===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...i}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in bme))throw new nt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Ny.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Ny.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Ny.jwkToMulticodec({jwk:e});return hz({keyBytes:t,multicodecName:n})}};U2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},U2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},U2.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""}};P2=U2,Pme=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(Pme||{}),e7={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},dF=class wf extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),o=await P2.publicKeyToMultibaseId({publicKey:a}),s=`did:${wf.methodName}:${o}`,c=(await wf.resolve(s,t)).didDocument;return new Ss({uri:s,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Jn.parse(e.id);if(t&&t.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==wf.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new nt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await wf.createDocument({didUri:e,options:t});return{...Di,didDocument:n}}catch(n){if(!(n instanceof nt))throw new Error(n);return{...Di,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:t={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=t,o={id:""},s=Jn.parse(e);if(!s)throw new nt("invalidDid",`Invalid DID URI: ${e}`);let c=s.id;if(s.method!==wf.methodName)throw new nt("methodNotSupported",`Method not supported: ${s.method}`);if(!wf.validateIdentifier(s))throw new nt("invalidDid",`Invalid DID URI: ${e}`);let l=await wf.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}});o.id=s.uri,o.verificationMethod=[l],o.authentication=[l.id],o.assertionMethod=[l.id],o.capabilityInvocation=[l.id],o.capabilityDelegation=[l.id];let d=[n];return uz({didDocument:o}).forEach(u=>{let f=e7[u];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:s,multicodecCode:c,multicodecName:l}=mz({multibaseKeyId:t}),d=s.byteLength,u=P2.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==u)throw new nt("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await ns.validatePublicKey({publicKeyBytes:s});break;case"ed25519-pub":f=await is.validatePublicKey({publicKeyBytes:s});break}if(!f)throw new nt("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${t}`;try{new URL(o.id)}catch{throw new nt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in e7))throw new nt("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new nt("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=t),a==="JsonWebKey2020"){let{crv:p}=await P2.multicodecToJwk({code:c});o.publicKeyJwk=await P2.keyConverter(p).bytesToPublicKey({publicKeyBytes:s})}return o}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&QR(n)==="String"&&n.startsWith("z")}};dF.methodName="key";cb=dF,xme=3e4;lF=class L2 extends sb{static async create({keyManager:e=new Ic,options:t}){if(!t.domain)throw new nt("invalidDid","The 'domain' option is required for did:web creation");if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=t.path?`${t.domain}:${t.path}`:t.domain,i=`did:${L2.methodName}:${n}`;if(!Jn.parse(i))throw new nt("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let s=0;s<a.length;s++){let c=a[s],l=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:l}),u=c.id?.split("#").pop()??`key-${s}`,f=`${i}#${u}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??i,publicKeyJwk:d});for(let p of c.purposes??[])o[p]??=[],o[p].push(f)}return t.services&&(o.service=t.services.map(s=>({...s,id:`${i}#${s.id.split("#").pop()}`}))),new Ss({uri:i,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=Zs(t)??Zs(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(o=>Zs(o.id)===i):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==L2.methodName)throw new nt("methodNotSupported","Method not supported");return await Ss.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Jn.parse(e);if(!n)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L2.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let a=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let o=new URL(a);if(Eme(o.hostname))return{...Di,didResolutionMetadata:{error:"notFound"}};let s=await fetch(a,{signal:AbortSignal.timeout(xme)});if(!s.ok)throw new Error("HTTP error status code returned");let c=await s.json();return{...Di,didDocument:c}}catch{return{...Di,didResolutionMetadata:{error:"notFound"}}}}};lF.methodName="web";uF=lF,Sme=hh(l7(),1),kme=hh(u7(),1),hE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new Sme.Level(e),this.ttl=(0,kme.default)(t)}open(){return this.cache.open()}async get(r){try{let e=await this.cache.get(r),t=JSON.parse(e);if(Date.now()>=t.ttlMillis){this.cache.nextTick(()=>this.cache.del(r));return}else return t.value}catch(e){if(e.notFound)return;throw e}}set(r,e){let t={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(t);return this.cache.put(r,n)}delete(r){return this.cache.del(r)}clear(){return this.cache.clear()}close(){return this.cache.close()}},_me=hh(u7(),1),mE=class{constructor({ttl:r="15m"}={}){this.cache=new jde.default({ttl:(0,_me.default)(r)})}async open(){}async get(r){if(!r)throw new Error("Key cannot be null or undefined");return this.cache.get(r)}async set(r,e){this.cache.set(r,e)}async delete(r){this.cache.delete(r)}async clear(){this.cache.clear()}async close(){}},Ame={open(){return Promise.resolve()},get(r){return Promise.resolve(void 0)},set(r,e){return Promise.resolve()},delete(r){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},tg=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this.cache=r||Ame;for(let t of e)this.didResolvers.set(t.methodName,t)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(r,e){let t=Jn.parse(r);if(!t)return{...Di,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...Di,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};let i=await this.cache.get(t.uri);if(i)return i;{let a=await n.resolve(t.uri,e);return a.didResolutionMetadata.error||await this.cache.set(t.uri,a),a}}async dereference(r,e){let t=Jn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(t.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!t.fragment||t.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:s=[]}=n,c=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let d of s)if(c.has(d.id)){l=d;break}for(let d of o)if(c.has(d.id)){l=d;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var rg,fF=G(()=>{"use strict";g();MI();jI();vr();Go();bN();xN();SN();Ho();v9();b9();$9();B9();O9();j9();M9();K9();a2();qR();ea();ur();rg=class r{methodHandlers;didResolver;messageStore;dataStore;resumableTaskStore;stateIndex;tenantGate;eventLog;storageController;resumableTaskManager;_coreProtocols;ownsResolver;constructor(e){this.didResolver=e.didResolver,this.ownsResolver=e.ownsResolver??!1,this.tenantGate=e.tenantGate,this.messageStore=e.messageStore,this.dataStore=e.dataStore,this.resumableTaskStore=e.resumableTaskStore,this.stateIndex=e.stateIndex,this.eventLog=e.eventLog,this.storageController=new $y({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new o2(e.resumableTaskStore,this.storageController),this._coreProtocols=new py,this._coreProtocols.register(new rt);let t={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[ve.Messages+me.Read]:new px(t),[ve.Messages+me.Subscribe]:new yx(t),[ve.Messages+me.Sync]:new wx(t),[ve.Protocols+me.Configure]:new r2(t),[ve.Protocols+me.Query]:new i2(t),[ve.Records+me.Count]:new s2(t),[ve.Records+me.Delete]:new c2(t),[ve.Records+me.Query]:new d2(t),[ve.Records+me.Read]:new l2(t),[ve.Records+me.Subscribe]:new f2(t),[ve.Records+me.Write]:new p2(t)}}static async create(e){e.didResolver||(e.didResolver=new tg({didResolvers:[vo,bo,cb,uF],cache:new mE}),e.ownsResolver=!0),e.tenantGate??=new hy;let t=new r(e);return await t.open(),t}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,t,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(t);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:o}=n,s=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[s].handle({tenant:e,message:t,dataStream:a,subscriptionHandler:o})}async validateTenant(e){let t=await this.tenantGate.isActiveTenant(e);if(!t.isActiveTenant)return{status:{code:401,detail:t.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let t=e?.descriptor?.interface,n=e?.descriptor?.method;if(t===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${t}, method: ${n}`}};try{ye.validateJsonSchema(e)}catch(i){return wt(i,400)}}}});function Tme(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Zn(r,e){return e?Promise.race([r,Tme(e)]):r}var yE=G(()=>{"use strict";g()});import{Level as Ime}from"level";async function Ys(r,e){return new Ime(r,{...e,keyEncoding:"utf8"})}var qa,kf=G(()=>{"use strict";g();yE();qa=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Ys,...e},this.db=t}async open(){switch(await this.createLevelDatabase(),this.db.status){case"open":return;case"opening":return new Promise(e=>{this.db.once("open",e)});case"closing":return new Promise((e,t)=>{let n=()=>{this.db.open().then(e).catch(t)};this.db.once("closed",n)});case"closed":return this.db.open()}}async close(){if(this.db)switch(this.db.status){case"open":return this.db.close();case"opening":return new Promise((e,t)=>{let n=()=>{this.db.close().then(e).catch(t)};this.db.once("open",n)});case"closing":return new Promise(e=>{this.db.once("closed",e)});case"closed":return}}async partition(e){return await this.createLevelDatabase(),new r(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,t){t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal);try{return await Zn(this.db.get(String(e)),t?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,t){return!!await this.get(e,t)}async*keys(e){e?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),e?.signal);for await(let t of this.db.keys())e?.signal?.throwIfAborted(),yield t}async*iterator(e,t){t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal);for await(let n of this.db.iterator(e))t?.signal?.throwIfAborted(),yield n}async put(e,t,n){return n?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),n?.signal),Zn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal),Zn(this.db.del(String(e)),t?.signal)}async isEmpty(e){for await(let t of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,t){return t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal),Zn(this.db.batch(e),t?.signal)}createPartitionOperation(e,t){return{...t,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Zn(n.db.compactRange?.(...t),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let t=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,t]}get root(){let e=this.db;for(let t=e.db;t&&t!==e;)e=t;return new r(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var _f,gE=G(()=>{"use strict";g();kw();kf();_f=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Ys,...e},this.db=t??new qa({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let t=await this.db.partition(e);return new r({...this.config,location:""},t)}async put(e,t,n){return await this.db.put(String(e),t,n),tr.parse(e.toString())}async get(e,t){return await this.db.get(String(e),t)}async has(e,t){return this.db.has(String(e),t)}async delete(e,t){return this.db.delete(String(e),t)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,t){for await(let n of e)await this.put(n.cid,n.block,t),yield n.cid}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async*getAll(e){let t=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of t)yield{cid:tr.decode(n),block:i}}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async clear(){return this.db.clear()}}});function Dme(r){return r[Symbol.asyncIterator]!=null}function Rme(r){if(Dme(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var pF,hF=G(()=>{g();pF=Rme});var mF,Cme,yF,$me,gF,wF=G(()=>{g();Nf();Xh();mF=0,Cme="identity",yF=Ha,$me=r=>Gf(mF,yF(r)),gF={code:mF,name:Cme,encode:yF,digest:$me}});var vF,Bme,bF,PF=G(()=>{g();km();vF=Tn(la(),1);al();Bme=async(r,e,t,n,i,a,o,s)=>{let c=await o.get(r,s),l=S_(c),d=l,u=t;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),u=`${u}/${f}`;let p=tr.asCID(d[f]);if(p!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}},next:{cid:p,name:f,path:u,toResolve:n}};d=d[f]}else throw(0,vF.default)(new Error(`No property named ${f} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}}}},bF=Bme});function Ome(r,e,t,n){let i=BigInt(r.length),a=BigInt(e+i);return t>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(r=r.subarray(0,Number(n-e))),t>=e&&t<a&&(r=r.subarray(Number(t-e))),r)}var xh,wE=G(()=>{g();xh=Ome});var db,jme,ng,vE=G(()=>{g();db=Tn(la(),1),jme=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),a=BigInt(t);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,db.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,db.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,db.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,db.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},ng=jme});var xF,Mme,Kme,EF,SF=G(()=>{g();xF=Tn(la(),1);Xh();dl();wE();vE();Mme=r=>{async function*e(t={}){let{start:n,end:i}=ng(r.length,t.offset,t.length),a=xh(r,0n,n,i);t.onProgress?.(new Cn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Kme=async(r,e,t,n,i,a,o,s)=>{if(n.length>0)throw(0,xF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Hb(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:Mme(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},EF=Kme});var kF,Nme,Ume,_F,AF=G(()=>{g();kF=Tn(la(),1);dl();wE();vE();Nme=r=>{async function*e(t={}){let{start:n,end:i}=ng(r.length,t.offset,t.length),a=xh(r,0n,n,i);t.onProgress?.(new Cn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Ume=async(r,e,t,n,i,a,o,s)=>{if(n.length>0)throw(0,kF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await o.get(r,s);return{entry:{type:"raw",name:e,path:t,cid:r,content:Nme(c),depth:a,size:BigInt(c.length),node:c}}},_F=Ume});var Lme,qme,TF,zme,IF,DF,RF=G(()=>{g();ua();SA();kA();Lme=async function(r){return(await W1.encode(r)).slice(0,8).reverse()},qme=async(r,e,t)=>{await Promise.all(r.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);e._putObjectAt(i,new Hc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},TF=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),zme=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},IF=async(r,e,t,n,i)=>{if(n==null){let d=Y1({hashFn:Lme});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await qme(r.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=TF(a.pos),s=zme(a);s.length>n.hamtDepth&&(n.lastBucket=s[n.hamtDepth],o=TF(n.lastBucket._posAtParent));let c=r.Links.find(d=>{if(d.Name==null)return!1;let u=d.Name.substring(0,2),f=d.Name.substring(2);return!(u!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let l=await t.get(c.Hash,i);return r=cl(l),IF(r,e,t,n,i)},DF=IF});function Fme(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var bE,o6=G(()=>{g();bE=Fme});function Gme(r){return r[Symbol.asyncIterator]!=null}function Hme(r,e){let t=0;if(Gme(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=bE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){await o&&(yield i);for(let c of n)await e(c,t++)&&(yield c)}();let s=e;return function*(){o===!0&&(yield i);for(let c of n)s(c,t++)&&(yield c)}()}var CF,$F=G(()=>{g();o6();CF=Hme});function Vme(r){return r[Symbol.asyncIterator]!=null}function Wme(r,e){let t=0;if(Vme(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=bE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,t++)}();let s=e;return function*(){yield o;for(let c of n)yield s(c,t++)}()}var ig,PE=G(()=>{g();o6();ig=Wme});function Po(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var xE=G(()=>{g()});async function*Eh(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],o=Po(),s=Po(),c=!1,l,d=!1;i.addEventListener("task-complete",()=>{s.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(a.length===t&&(o=Po(),await o.promise),d)break;let m={done:!1};a.push(m),h().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new EE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new EE("task-complete"))})}c=!0,i.dispatchEvent(new EE("task-complete"))}catch(h){l=h,i.dispatchEvent(new EE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(h=>h.done)}function*f(){for(;a.length>0&&a[0].done;){let h=a[0];if(a.shift(),h.ok)yield h.value;else throw d=!0,o.resolve(),h.err;o.resolve()}}function*p(){for(;u();)for(let h=0;h<a.length;h++)if(a[h].done){let m=a[h];if(a.splice(h,1),h--,m.ok)yield m.value;else throw d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(u()||(s=Po(),await s.promise),l!=null||(n?yield*f():yield*p(),l!=null))throw l;if(c&&a.length===0)break}}var EE,SE=G(()=>{g();xE();EE=globalThis.CustomEvent??Event});var kE,sg,BF=G(()=>{g();kE=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},sg=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new kE(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new kE(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}});function _E(r={}){return Jme(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Jme(r,e){e=e??{};let t=e.onEnd,n=new sg,i,a,o,s=Po(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,v)=>{a=w=>{a=null,n.push(w);try{y(r(n))}catch(x){v(x)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{s.resolve(),s=Po()})}},l=y=>a!=null?a(y):(n.push(y),i),d=y=>(n=new sg,a!=null?a({error:y}):(n.push({error:y}),i)),u=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>o?i:(o=!0,y!=null?d(y):l({done:!0})),p=()=>(n=new sg,f(),{done:!0}),h=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,x;v!=null&&(w=new Promise((_,A)=>{x=()=>{A(new a6)},v.addEventListener("abort",x)}));try{await Promise.race([s.promise,w])}finally{x!=null&&v!=null&&v?.removeEventListener("abort",x)}}},t==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var a6,c6=G(()=>{g();xE();BF();a6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function Zme(r){return r.reason}async function OF(r,e,t){if(e==null)return r;let n=t?.translateError??Zme;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((a,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var jF=G(()=>{g()});function MF(){return new d6}var d6,KF=G(()=>{g();xE();jF();d6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Po(),this.haveNext=Po()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Po(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Po(),await OF(this.readNext.promise,t?.signal,t)}}});function Yme(r){return r[Symbol.asyncIterator]!=null}async function Xme(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Qme(r){let e=new AbortController,t=MF();Xme(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*eye(r){for(let e of r)yield*e}function tye(...r){let e=[];for(let t of r)Yme(t)||e.push(t);return e.length===r.length?eye(e):Qme(r)}var NF,UF=G(()=>{g();KF();NF=tye});function og(r,...e){if(r==null)throw new Error("Empty pipeline");if(l6(r)){let n=r;r=()=>n.source}else if(qF(r)||LF(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&l6(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)l6(t[n])&&(t[n]=nye(t[n]));return rye(...t)}var rye,LF,qF,l6,nye,AE=G(()=>{g();c6();UF();rye=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},LF=r=>r?.[Symbol.asyncIterator]!=null,qF=r=>r?.[Symbol.iterator]!=null,l6=r=>r==null?!1:r.sink!=null&&r.source!=null,nye=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=_E({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,a=r.source;if(LF(a))i=async function*(){yield*a,n.end()};else if(qF(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return NF(n,i())}return r.source}});var iye,zF,FF=G(()=>{g();$F();PE();SE();AE();dl();iye=(r,e,t,n,i,a,o)=>{async function*s(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new Cn("unixfs:exporter:walk:directory",{cid:r})),yield*og(u,f=>ig(f,p=>async()=>{let h=p.Name??"",m=`${n}/${h}`;return(await i(p.Hash,h,m,[],a+1,o,c)).entry}),f=>Eh(f,{ordered:!0}),f=>CF(f,p=>p!=null))}return s},zF=iye});var HF=Ae((Wqe,u6)=>{"use strict";g();var sye=Object.prototype.hasOwnProperty,Xs="~";function lb(){}Object.create&&(lb.prototype=Object.create(null),new lb().__proto__||(Xs=!1));function oye(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function GF(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new oye(t,n||r,i),o=Xs?Xs+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],a]:r._events[o].push(a):(r._events[o]=a,r._eventsCount++),r}function TE(r,e){--r._eventsCount===0?r._events=new lb:delete r._events[e]}function ks(){this._events=new lb,this._eventsCount=0}ks.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)sye.call(t,n)&&e.push(Xs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ks.prototype.listeners=function(e){var t=Xs?Xs+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=new Array(a);i<a;i++)o[i]=n[i].fn;return o};ks.prototype.listenerCount=function(e){var t=Xs?Xs+e:e,n=this._events[t];return n?n.fn?1:n.length:0};ks.prototype.emit=function(e,t,n,i,a,o){var s=Xs?Xs+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var f=c.length,p;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!d)for(p=1,d=new Array(l-1);p<l;p++)d[p-1]=arguments[p];c[u].fn.apply(c[u].context,d)}}return!0};ks.prototype.on=function(e,t,n){return GF(this,e,t,n,!1)};ks.prototype.once=function(e,t,n){return GF(this,e,t,n,!0)};ks.prototype.removeListener=function(e,t,n,i){var a=Xs?Xs+e:e;if(!this._events[a])return this;if(!t)return TE(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&TE(this,a);else{for(var s=0,c=[],l=o.length;s<l;s++)(o[s].fn!==t||i&&!o[s].once||n&&o[s].context!==n)&&c.push(o[s]);c.length?this._events[a]=c.length===1?c[0]:c:TE(this,a)}return this};ks.prototype.removeAllListeners=function(e){var t;return e?(t=Xs?Xs+e:e,this._events[t]&&TE(this,t)):(this._events=new lb,this._eventsCount=0),this};ks.prototype.off=ks.prototype.removeListener;ks.prototype.addListener=ks.prototype.on;ks.prefixed=Xs;ks.EventEmitter=ks;typeof u6<"u"&&(u6.exports=ks)});var f6,VF=G(()=>{g();f6=Tn(HF(),1)});function h6(r,e,t,n){let i,a=new Promise((o,s)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&s(JF(c)),c.addEventListener("abort",()=>{s(JF(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(d){s(d)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new ub(c);typeof r.cancel=="function"&&r.cancel(),s(l)},e),(async()=>{try{o(await r)}catch(c){s(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var ub,p6,WF,JF,ZF=G(()=>{g();ub=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},p6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},WF=r=>globalThis.DOMException===void 0?new p6(r):new DOMException(r),JF=r=>{let e=r.reason===void 0?WF("This operation was aborted."):r.reason;return e instanceof Error?e:WF(e)}});function m6(r,e,t){let n=0,i=r.length;for(;i>0;){let a=Math.trunc(i/2),o=n+a;t(r[o],e)<=0?(n=++o,i-=a+1):i=a}return n}var YF=G(()=>{g()});var Sh,Hl,y6,XF,QF=G(()=>{g();YF();Sh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},y6=class{constructor(){Hl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Sh(this,Hl,"f")[this.size-1].priority>=t.priority){Sh(this,Hl,"f").push(n);return}let i=m6(Sh(this,Hl,"f"),n,(a,o)=>o.priority-a.priority);Sh(this,Hl,"f").splice(i,0,n)}dequeue(){let e=Sh(this,Hl,"f").shift();return e?.run}filter(e){return Sh(this,Hl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Sh(this,Hl,"f").length}};Hl=new WeakMap;XF=y6});var _n,Ye,Yn,pb,hb,Tf,BE,mb,IE,Dc,fb,ta,DE,ra,yb,Af,RE,eG,tG,iG,rG,nG,CE,g6,w6,OE,sG,$E,jE,v6,oG,aG=G(()=>{g();VF();ZF();QF();_n=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Ye=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},jE=class extends Error{},v6=class extends f6.default{constructor(e){var t,n,i,a;if(super(),Yn.add(this),pb.set(this,void 0),hb.set(this,void 0),Tf.set(this,0),BE.set(this,void 0),mb.set(this,void 0),IE.set(this,0),Dc.set(this,void 0),fb.set(this,void 0),ta.set(this,void 0),DE.set(this,void 0),ra.set(this,0),yb.set(this,void 0),Af.set(this,void 0),RE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:XF,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);_n(this,pb,e.carryoverConcurrencyCount,"f"),_n(this,hb,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),_n(this,BE,e.intervalCap,"f"),_n(this,mb,e.interval,"f"),_n(this,ta,new e.queueClass,"f"),_n(this,DE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,_n(this,RE,e.throwOnTimeout===!0,"f"),_n(this,Af,e.autoStart===!1,"f")}get concurrency(){return Ye(this,yb,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);_n(this,yb,e,"f"),Ye(this,Yn,"m",OE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Ye(this,RE,"f"),...t},new Promise((n,i)=>{Ye(this,ta,"f").enqueue(async()=>{var a,o,s;_n(this,ra,(o=Ye(this,ra,"f"),o++,o),"f"),_n(this,Tf,(s=Ye(this,Tf,"f"),s++,s),"f");try{if(!((a=t.signal)===null||a===void 0)&&a.aborted)throw new jE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=h6(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Ye(this,Yn,"m",sG).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof ub&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Ye(this,Yn,"m",iG).call(this)}},t),this.emit("add"),Ye(this,Yn,"m",CE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Ye(this,Af,"f")?(_n(this,Af,!1,"f"),Ye(this,Yn,"m",OE).call(this),this):this}pause(){_n(this,Af,!0,"f")}clear(){_n(this,ta,new(Ye(this,DE,"f")),"f")}async onEmpty(){Ye(this,ta,"f").size!==0&&await Ye(this,Yn,"m",$E).call(this,"empty")}async onSizeLessThan(e){Ye(this,ta,"f").size<e||await Ye(this,Yn,"m",$E).call(this,"next",()=>Ye(this,ta,"f").size<e)}async onIdle(){Ye(this,ra,"f")===0&&Ye(this,ta,"f").size===0||await Ye(this,Yn,"m",$E).call(this,"idle")}get size(){return Ye(this,ta,"f").size}sizeBy(e){return Ye(this,ta,"f").filter(e).length}get pending(){return Ye(this,ra,"f")}get isPaused(){return Ye(this,Af,"f")}};pb=new WeakMap,hb=new WeakMap,Tf=new WeakMap,BE=new WeakMap,mb=new WeakMap,IE=new WeakMap,Dc=new WeakMap,fb=new WeakMap,ta=new WeakMap,DE=new WeakMap,ra=new WeakMap,yb=new WeakMap,Af=new WeakMap,RE=new WeakMap,Yn=new WeakSet,eG=function(){return Ye(this,hb,"f")||Ye(this,Tf,"f")<Ye(this,BE,"f")},tG=function(){return Ye(this,ra,"f")<Ye(this,yb,"f")},iG=function(){var e;_n(this,ra,(e=Ye(this,ra,"f"),e--,e),"f"),Ye(this,Yn,"m",CE).call(this),this.emit("next")},rG=function(){Ye(this,Yn,"m",w6).call(this),Ye(this,Yn,"m",g6).call(this),_n(this,fb,void 0,"f")},nG=function(){let e=Date.now();if(Ye(this,Dc,"f")===void 0){let t=Ye(this,IE,"f")-e;if(t<0)_n(this,Tf,Ye(this,pb,"f")?Ye(this,ra,"f"):0,"f");else return Ye(this,fb,"f")===void 0&&_n(this,fb,setTimeout(()=>{Ye(this,Yn,"m",rG).call(this)},t),"f"),!0}return!1},CE=function(){if(Ye(this,ta,"f").size===0)return Ye(this,Dc,"f")&&clearInterval(Ye(this,Dc,"f")),_n(this,Dc,void 0,"f"),this.emit("empty"),Ye(this,ra,"f")===0&&this.emit("idle"),!1;if(!Ye(this,Af,"f")){let e=!Ye(this,Yn,"a",nG);if(Ye(this,Yn,"a",eG)&&Ye(this,Yn,"a",tG)){let t=Ye(this,ta,"f").dequeue();return t?(this.emit("active"),t(),e&&Ye(this,Yn,"m",g6).call(this),!0):!1}}return!1},g6=function(){Ye(this,hb,"f")||Ye(this,Dc,"f")!==void 0||(_n(this,Dc,setInterval(()=>{Ye(this,Yn,"m",w6).call(this)},Ye(this,mb,"f")),"f"),_n(this,IE,Date.now()+Ye(this,mb,"f"),"f"))},w6=function(){Ye(this,Tf,"f")===0&&Ye(this,ra,"f")===0&&Ye(this,Dc,"f")&&(clearInterval(Ye(this,Dc,"f")),_n(this,Dc,void 0,"f")),_n(this,Tf,Ye(this,pb,"f")?Ye(this,ra,"f"):0,"f"),Ye(this,Yn,"m",OE).call(this)},OE=function(){for(;Ye(this,Yn,"m",CE).call(this););},sG=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new jE("The task was aborted."))},{once:!0})})},$E=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};oG=v6});async function cG(r,e,t,n,i,a,o){if(e instanceof Uint8Array){let l=xh(e,n,i,a);t.push(l);return}if(e.Data==null)throw(0,kh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let s;try{s=Pi.unmarshal(e.Data)}catch(l){throw(0,kh.default)(l,"ERR_NOT_UNIXFS")}if(s.data!=null){let l=s.data,d=xh(l,n,i,a);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==s.blockSizes.length)throw(0,kh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+s.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await og(c,l=>ig(l,d=>async()=>{let u=await r.get(d.link.Hash,o);return{...d,block:u}}),l=>Eh(l,{ordered:!0}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let p;switch(d.Hash.code){case Dw:p=cl(u);break;case bu:p=u;break;default:t.end((0,kh.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new oG({concurrency:1});h.on("error",m=>{t.end(m)}),h.add(async()=>{o.onProgress?.(new Cn("unixfs:exporter:walk:file",{cid:d.Hash})),await cG(r,p,t,f,i,a,o)}),await h.onIdle()}}),n>=a&&t.end()}var kh,aye,b6,dG=G(()=>{g();ua();kh=Tn(la(),1);vu();PE();SE();AE();c6();Kw();aG();dl();wE();vE();aye=(r,e,t,n,i,a,o)=>{async function*s(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=ng(l,c.offset,c.length);if(u===0n)return;let f=0n,p=u-d,h=_E();c.onProgress?.(new Cn("unixfs:exporter:walk:file",{cid:r})),cG(o,e,h,0n,d,u,c).catch(m=>{h.end(m)});for await(let m of h)if(m!=null){if(f+=BigInt(m.byteLength),f>p)throw h.end(),(0,kh.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");f===p&&h.end(),c.onProgress?.(new Cn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:p,fileSize:l})),yield m}if(f<p)throw(0,kh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return s},b6=aye});async function*lG(r,e,t,n,i,a){let o=r.Links,s=og(o,c=>ig(c,l=>async()=>{let d=l.Name!=null?l.Name.substring(2):null;if(d!=null&&d!==""){let u=await t(l.Hash,d,`${e}/${d}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return r=cl(u),a.onProgress?.(new Cn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:lG(r,e,t,n,i,a)}}}),c=>Eh(c,{ordered:!0}));for await(let{entries:c}of s)yield*c}var cye,uG,fG=G(()=>{g();ua();PE();SE();AE();dl();cye=(r,e,t,n,i,a,o)=>{function s(c={}){return c.onProgress?.(new Cn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),lG(e,n,i,a,o,c)}return s};uG=cye});var gb,dye,lye,uye,pG,hG=G(()=>{g();ua();gb=Tn(la(),1);vu();RF();FF();dG();fG();dye=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,lye={raw:b6,file:b6,directory:zF,"hamt-sharded-directory":uG,metadata:(r,e,t,n,i,a,o)=>()=>[],symlink:(r,e,t,n,i,a,o)=>()=>[]},uye=async(r,e,t,n,i,a,o,s)=>{let c=await o.get(r,s),l=cl(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,gb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=Pi.unmarshal(l.Data)}catch(p){throw(0,gb.default)(p,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let p;if(d?.type==="hamt-sharded-directory"?p=await DF(l,n[0],o):p=dye(l,n[0]),p==null)throw(0,gb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),m=`${t}/${h}`;u={cid:p,toResolve:n,name:h??"",path:m}}let f=lye[d.type](r,l,d,t,i,a,o);if(f==null)throw(0,gb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}},pG=uye});var mG,fye,yG,gG,wG=G(()=>{g();km();ua();mG=Tn(la(),1);Kw();wF();PF();SF();AF();hG();fye={[Dw]:pG,[bu]:_F,[mu]:bF,[gF.code]:EF},yG=async(r,e,t,n,i,a,o)=>{let s=fye[r.code];if(s==null)throw(0,mG.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return s(r,e,t,n,yG,i,a,o)},gG=yG});async function*mye(r,e,t={}){let{cid:n,toResolve:i}=hye(r),a=n.toString(),o=a,s=i.length;for(;;){let c=await gG(n,a,o,i,s,e,t);if(c.entry==null&&c.next==null)throw(0,ME.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function vG(r,e,t={}){let n=await pF(mye(r,e,t));if(n==null)throw(0,ME.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var ME,pye,hye,bG=G(()=>{g();ME=Tn(la(),1);hF();al();wG();pye=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),hye=r=>{if(r instanceof Uint8Array)return{cid:tr.decode(r),toResolve:[]};let e=tr.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=pye(r);return{cid:tr.parse(t[0]),toResolve:t.slice(1)}}throw(0,ME.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var P6,KE,If,PG=G(()=>{"use strict";g();gE();kf();yu();bG();TA();P6=new TextEncoder,KE=new TextDecoder,If=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ys,...e},this.blockstore=new _f({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,t,n,i){let a=await this.getRefsPartition(e,t),o=await a.get(n);if(o){await i.cancel();let{dataSize:u}=JSON.parse(KE.decode(o));return{dataSize:u}}let s=await this.getRefcountsPartition(),c=await s.get(n),l=c?JSON.parse(KE.decode(c)):{count:0,dataSize:0},d;if(l.count>0)await i.cancel(),d=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Lw([{content:Wt.asAsyncIterable(i)}],u,{cidVersion:1}),p;for await(p of f);d=Number(p.unixfs?.fileSize()??p.size)}return await a.put(n,P6.encode(JSON.stringify({dataSize:d}))),await s.put(n,P6.encode(JSON.stringify({count:l.count+1,dataSize:d}))),{dataSize:d}}async get(e,t,n){let a=await(await this.getRefsPartition(e,t)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(KE.decode(a)),s=await this.getBlocksPartition(n);if(!await s.has(n))return;let d=(await vG(n,s)).content(),u=new ReadableStream({async pull(f){let p=await d.next();p.done?f.close():f.enqueue(p.value)}});return{dataSize:o,dataStream:u}}async delete(e,t,n){let i=await this.getRefsPartition(e,t);if(!await i.get(n))return;await i.delete(n);let o=await this.getRefcountsPartition(),s=await o.get(n);if(!s)return;let c=JSON.parse(KE.decode(s)),l=c.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,P6.encode(JSON.stringify({count:l,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,t){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(t)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function xG(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function EG(r,e,t,n,i){let a=[];for(let l of t.properties){let d=e[l];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[t.sortProperty];if(o===void 0||Array.isArray(o))return;let s=a.join(NE),c=n(o);return s+NE+c+i+r}function SG(r,e,t){let n=[];for(let i of e.properties){let a=r[i];if(a===void 0||typeof a=="object")return;n.push(t(a))}return n.join(NE)+NE}function kG(r,e,t,n,i,a){let o=EG(t.messageCid,t.indexes,n,i,a);if(o!==void 0)return AG(r,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(t)})}function _G(r,e,t,n,i,a,o){let s=EG(t,n,i,a,o);if(s!==void 0)return AG(r,e,`__compound:${i.name}__`,{type:"del",key:s})}async function AG(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function x6(r,e,t){let n,i=0;for(let a of t){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let s of a.properties){let c=r[s];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function TG(r,e,t,n,i,a,o,s,c){let{sortDirection:l=Rt.Ascending,cursor:d,limit:u}=n,f=SG(t,i,a);if(f===void 0)return s(e,[t],n,c);let p=await xG(r,e,i),h={};if(d!==void 0){let x=a(d.value),_=f+x+o+d.messageCid;l===Rt.Ascending?(h.gt=_,h.lt=f+"\xFF"):(h.lt=_,h.gt=f,h.reverse=!0)}else l===Rt.Ascending?(h.gt=f,h.lt=f+"\xFF"):(h.gt=f,h.lt=f+"\xFF",h.reverse=!0);let m=new Set(i.properties),y={},v=!1;for(let x in t)m.has(x)||(y[x]=t[x],v=!0);let w=[];for await(let[x,_]of p.iterator(h,c)){if(u!==void 0&&w.length===u)break;let A=JSON.parse(_);v&&!nr.matchFilter(A.indexes,y)||w.push(A)}return w}async function IG(r,e,t,n,i,a,o){let s=SG(t,n,i);if(s===void 0)return(await a(e,[t],{sortProperty:n.sortProperty},o)).length;let c=await xG(r,e,n),l=new Set(n.properties),d=!1,u={};for(let h in t)l.has(h)||(u[h]=t[h],d=!0);let f={gt:s,lt:s+"\xFF"},p=0;if(d)for await(let[h,m]of c.iterator(f,o)){let y=JSON.parse(m);nr.matchFilter(y.indexes,u)&&p++}else for await(let[h,m]of c.iterator(f,o))p++;return p}var NE,DG=G(()=>{"use strict";g();yc();ed();NE=""});var RG,_h,E6=G(()=>{"use strict";g();Oi();DA();ed();DG();kf();Et();yc();RG="index",_h=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ys,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async clear(){await this.db.clear()}async put(e,t,n,i){if(hp(n))throw new ie(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:t,indexes:n},o=[];for(let d in n){let u=n[d];if(Array.isArray(u))for(let f of u){let p=this.createPutIndexedItemOperation(e,a,d,f);o.push(p)}else{let f=this.createPutIndexedItemOperation(e,a,d,u);o.push(f)}}for(let d of this._compoundIndexes){let u=kG(this.db,e,a,d,r.encodeValue,r.delimiter);u!==void 0&&o.push(u)}let s=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});o.push(s);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,i)}async delete(e,t,n){let i=[],a=await this.getIndexes(e,t);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(o);for(let l in a){let d=a[l];if(Array.isArray(d))for(let u of d){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,d);i.push(u)}}for(let l of this._compoundIndexes){let d=_G(this.db,e,t,a,l,r.encodeValue,r.delimiter);d!==void 0&&i.push(d)}let s=await Promise.all(i);await(await this.db.partition(e)).batch(s,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:a}=t,o=r.keySegmentJoin(r.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),a=r.getIndexPartitionName(t);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(RG,t)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,t){let n=r.getIndexPartitionName(t);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(RG)}async query(e,t,n,i){if(t.length===1&&!hp(t[0])){let a=x6(t[0],n,this._compoundIndexes);if(a!==void 0)return TG(this.db,e,t[0],n,a,r.encodeValue,r.delimiter,this.queryWithIteratorPaging.bind(this),i)}return r.shouldQueryWithInMemoryPaging(t,n)?this.queryWithInMemoryPaging(e,t,n,i):this.queryWithIteratorPaging(e,t,n,i)}async count(e,t,n,i){if(t.length===1&&!hp(t[0])){let o=x6(t[0],{...n},this._compoundIndexes);if(o!==void 0)return IG(this.db,e,t[0],o,r.encodeValue,this.query.bind(this),i)}return(await this.query(e,t,{...n},i)).length}async queryWithIteratorPaging(e,t,n,i){let{cursor:a,limit:o}=n,s=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let l of this.getIndexIterator(e,s,n,i)){if(o!==void 0&&o===c.length)break;let{indexes:d}=l;nr.matchAnyFilter(d,t)&&c.push(l)}return c}async*getIndexIterator(e,t,n,i){let{sortProperty:a,sortDirection:o=Rt.Ascending,cursor:s}=n,c={gt:t};o===Rt.Descending&&(c.reverse=!0,s!==void 0&&(c.lt=t,delete c.gt));let l=await this.getIndexPartition(e,a);for await(let[d,u]of l.iterator(c,i)){let{indexes:f,messageCid:p}=JSON.parse(u);yield{indexes:f,messageCid:p}}}createStartingKeyFromCursor(e){let{messageCid:t,value:n}=e;return r.keySegmentJoin(r.encodeValue(n),t)}static createCursorFromLastArrayItem(e,t){if(e.length>0)return this.createCursorFromItem(e.at(-1),t)}static createCursorFromItem(e,t){let{messageCid:n,indexes:i}=e,a=i[t];if(a===void 0)throw new ie(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ie(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:a,sortDirection:o=Rt.Ascending,cursor:s,limit:c}=n,l=s?this.createStartingKeyFromCursor(s):void 0,d=new Map;t.length===0&&(t=[{}]);try{for(let h of t)await this.executeSingleFilterQuery(e,h,a,d,i)}catch(h){if(h.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...d.values()].sort((h,m)=>this.sortItems(h,m,a,o)),f=l!==void 0?this.findCursorStartingIndex(u,o,a,l):0;if(f<0)return[];let p=c!==void 0?f+c:void 0;return u.slice(f,p)}async executeSingleFilterQuery(e,t,n,i,a){let o=c=>{for(let l of c)if(!(i.has(l.messageCid)||!nr.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ie(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(hp(t)){let c=await this.getAllItems(e,n);o(c);return}let s=xP.reduceFilter(t);for(let c in s){let l=s[c];if(nr.isEqualFilter(l)){let d=await this.filterExactMatches(e,c,l,a);o(d)}else if(nr.isOneOfFilter(l))for(let d of new Set(l)){let u=await this.filterExactMatches(e,c,d,a);o(u)}else if(nr.isRangeFilter(l)){let d=await this.filterRangeMatches(e,c,l,a);o(d)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[a,o]of n.iterator())i.push(JSON.parse(o));return i}async filterExactMatches(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(n)),o={gt:a},s=await this.getIndexPartition(e,t),c=[];for await(let[l,d]of s.iterator(o,i)){if(!l.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,t,n,i){let a={};for(let c in n){let l=c,d=r.encodeValue(n[l]);l==="lte"?a[l]=d+"\xFF":a[l]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],s=await this.getIndexPartition(e,t);for await(let[c,l]of s.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(c)===r.encodeValue(n.gt)||o.push(JSON.parse(l));return o}sortItems(e,t,n,i){let a=e.indexes[n],o=t.indexes[n],s=r.encodeValue(a)+e.messageCid,c=r.encodeValue(o)+t.messageCid;return i===Rt.Ascending?qw(s,c):qw(c,s)}findCursorStartingIndex(e,t,n,i){let a=c=>{let{messageCid:l,indexes:d}=c,u=d[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===Rt.Ascending?f>i:f<i},o=0,s=e.length;for(;o<s;){let c=o+s>>>1;a(e[c])?s=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,t){let i=await(await this.getIndexesLookupPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[t]=e.split(r.delimiter);return t}static delimiter="\0";static keySegmentJoin(...e){return e.join(r.delimiter)}static encodeNumberValue(e){let t=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?t:0;return a+String(e+o).padStart(i,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,t){for(let n of e)if(!r.isFilterConcise(n,t))return!1;return!0}static isFilterConcise(e,t){return e.recordId!==void 0?!0:t.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function UE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*yye(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],a=tr.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*S6(n,i))}else{let t=tr.asCID(e);t?yield[r.join("/"),t]:yield*S6(e,r)}}function*S6(r,e){if(r==null||r instanceof Uint8Array)return;let t=tr.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let a=[...e,n];yield*yye(a,i)}}function*gye(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!tr.asCID(n)&&(yield*k6(n,i))}else yield*k6(e,r)}function*k6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!tr.asCID(n)&&(yield*gye(i,n))}}function wye(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=tr.asCID(t);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:t}}async function CG({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),i=await t.digest(n),a=tr.create(1,e.code,i);return new LE({value:r,bytes:n,cid:a})}async function $G({bytes:r,codec:e,hasher:t}){if(!r)throw new Error('Missing required argument "bytes"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),i=await t.digest(r),a=tr.create(1,e.code,i);return new LE({value:n,bytes:r,cid:a})}var LE,BG=G(()=>{g();kw();D_();LE=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:UE(),bytes:UE(),value:UE(),asBlock:UE()})}links(){return S6(this.value,[])}tree(){return k6(this.value,[])}get(e="/"){return wye(this.value,e.split("/").filter(Boolean))}}});var bye,Df,OG=G(()=>{"use strict";g();BG();km();gE();ll();al();kf();yE();E6();vr();Yl();ed();bye=[{name:"protocol-protocolPath-messageTimestamp",properties:["protocol","protocolPath"],sortProperty:"messageTimestamp"},{name:"protocol-protocolPath-dateCreated",properties:["protocol","protocolPath"],sortProperty:"dateCreated"},{name:"schema-messageTimestamp",properties:["schema"],sortProperty:"messageTimestamp"},{name:"schema-dateCreated",properties:["schema"],sortProperty:"dateCreated"},{name:"protocol-contextId-messageTimestamp",properties:["protocol","contextId"],sortProperty:"messageTimestamp"}],Df=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Ys,...e},this.blockstore=new _f({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new _h({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??bye})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,t,n){n?.signal?.throwIfAborted();let i=await Zn(this.blockstore.partition(e),n?.signal),a=tr.parse(t),o=await i.get(a,n);return o?(await Zn($G({bytes:o,codec:ol,hasher:Mn}),n?.signal)).value:void 0}async query(e,t,n,i,a){a?.signal?.throwIfAborted();let o=r.buildQueryOptions(n,i),s=await this.index.query(e,t,o,a),c;i?.limit!==void 0&&i.limit<s.length&&(s.splice(-1),c=_h.createCursorFromLastArrayItem(s,o.sortProperty));let l=[];for(let d=0;d<s.length;d++){let{messageCid:u}=s[d],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:c}}async count(e,t,n,i){i?.signal?.throwIfAborted();let a=r.buildQueryOptions(n);return this.index.count(e,t,a,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:a,datePublished:o,messageTimestamp:s}=e,c=Rt.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":o!==void 0?l="datePublished":s!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(c=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Zn(this.blockstore.partition(e),n?.signal),a=tr.parse(t);await i.delete(a,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let a=await Zn(this.blockstore.partition(e),i?.signal),o=await Zn(CG({value:t,codec:ol,hasher:Mn}),i?.signal),s=mr.parseCid(await ye.getCid(t));await a.put(s,o.bytes,i);let c=s.toString();await this.index.put(e,c,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var Rf,jG=G(()=>{"use strict";g();ll();kf();Rf=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ys,...e},this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async register(e,t){let n=await mr.computeCid(e),i={id:n,timeout:Date.now()+t*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let t=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),t.push(a)),t.length>=e)break}return t}async read(e){let t=await this.db.get(e);if(t)return JSON.parse(t)}async extend(e,t){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+t*1e3,await this.db.put(i.id,JSON.stringify(i))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}}});function MG(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}var KG=G(()=>{g()});var NG,Cf,UG=G(()=>{"use strict";g();KG();yc();Et();NG="events",Cf=class r{emitter=MG();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;epoch;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,this.epoch=crypto.randomUUID(),e.errorHandler&&(this.errorHandler=e.errorHandler)}async getStreamId(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(n);return Array.from(i.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,t,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(t),messageCid:n}}async validateCursor(e,t){let n=await this.getStreamId(e),i;if(t.streamId!==n)i="stream_mismatch";else if(t.epoch!==this.epoch)i="epoch_mismatch";else{let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let l=c.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}let a=await this.getReplayBounds(e),o={requested:t,oldestAvailable:a?.oldest??t,latestAvailable:a?.latest??t,reason:i},s=new ie(re.EventLogProgressGap,`progress token gap: ${i}`);throw s.gapInfo=o,s}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,t,n,i){if(!this.isOpen){this.errorHandler(new ie(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let s=this.tenantLogs.get(e);if(s===void 0&&(s=new Map,this.tenantLogs.set(e,s)),s.set(o,{event:t,indexes:n,messageCid:i}),s.size>this.maxEventsPerTenant){let l=s.size-this.maxEventsPerTenant,d=0;for(let u of s.keys()){if(d>=l)break;s.delete(u),d++}}let c=`${e}_${NG}`;return this.emitter.emit(c,{tenant:e,event:t,indexes:n,seq:o,messageCid:i}),this.buildToken(e,o,i)}async read(e,t={}){let{cursor:n,limit:i,filters:a}=t;n!==void 0&&await this.validateCursor(e,n);let o=n!==void 0?r.parsePosition(n.position):void 0,s=this.tenantLogs.get(e);if(s===void 0||s.size===0)return{events:[],cursor:n};let c=[],l=i??Number.MAX_SAFE_INTEGER;for(let[d,u]of s)if(!(o!==void 0&&d<=o)&&!(a!==void 0&&a.length>0&&!nr.matchAnyFilter(u.indexes,a))&&(c.push({seq:d,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),c.length>=l))break;if(c.length>0){let d=c[c.length-1],u=await this.buildToken(e,d.seq,d.messageCid);return{events:c,cursor:u}}return{events:c,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ie(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ie?t:new ie(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let a=`${e}_${NG}`,{cursor:o,filters:s}=i??{},c=async d=>this.buildToken(e,d.seq,d.messageCid);if(o!==void 0){await this.validateCursor(e,o);let d=r.parsePosition(o.position),u=[],f=!1,p=v=>{s!==void 0&&s.length>0&&!nr.matchAnyFilter(v.indexes,s)||(f?c(v).then(w=>{n({type:"event",cursor:w,event:v.event})}):u.push({event:v.event,seq:v.seq,messageCid:v.messageCid}))};this.emitter.on(a,p);let h=await this.read(e,{cursor:o,filters:s}),m=h.cursor??o,y=h.cursor!==void 0?r.parsePosition(h.cursor.position):d;for(let v of h.events){let w=await this.buildToken(e,v.seq,v.messageCid??"");n({type:"event",cursor:w,event:v.event})}f=!0;for(let v of u)if(v.seq>y){let w=await this.buildToken(e,v.seq,v.messageCid);n({type:"event",cursor:w,event:v.event})}return n({type:"eose",cursor:m}),{id:t,close:async()=>{this.emitter.off(a,p)}}}let l=d=>{s!==void 0&&s.length>0&&!nr.matchAnyFilter(d.indexes,s)||c(d).then(u=>{n({type:"event",cursor:u,event:d.event})})};return this.emitter.on(a,l),{id:t,close:async()=>{this.emitter.off(a,l)}}}async getReplayBounds(e){let t=this.tenantLogs.get(e);if(t===void 0||t.size===0)return;let n=[...t.keys()],i=n[0],a=n[n.length-1],o=t.get(i),s=t.get(a),c=await this.buildToken(e,i,o.messageCid),l=await this.buildToken(e,a,s.messageCid);return{oldest:c,latest:l}}async trim(e,t){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof t=="number")for(let i of n.keys())if(i<t)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var ag,_6=G(()=>{"use strict";g();Hu();ag=class{db;nodesPartition;metaPartition;initialized=!1;constructor(e){this.db=e}async open(){this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta"),this.initialized=!0}async close(){this.initialized=!1}async clear(){await this.db.clear(),this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta")}async getNode(e){this.ensureInitialized();let t=an(e),n=await this.nodesPartition.get(t);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,t){this.ensureInitialized();let n=an(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=an(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return Gu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",an(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:an(e.leftHash),rightHash:an(e.rightHash)}:{type:"leaf",keyHash:an(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Gu(e.leftHash),rightHash:Gu(e.rightHash)}:{type:"leaf",keyHash:Gu(e.keyHash),valueCid:e.valueCid}}}});var cg,A6=G(()=>{"use strict";g();Hu();cg=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Al()}async close(){await this.store.close()}async clear(){await this.store.clear()}async getRoot(){let e=await this.store.getRoot();return e===void 0?this.defaultHashes[0]:e}async insert(e){let t=await Fu(e),n=await yy(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),o=await this.insertAtNode(a,t,n,i,0);return await this.store.setRoot(o),o}async delete(e){let t=await Fu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,t,0);return await this.store.setRoot(i),i}async has(e){let t=await Fu(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Fu(e),n=await this.getRoot();return this.generateProof(n,t,0)}async getSubtreeHash(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(on(t,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(t);if(i===void 0||i.type==="leaf")return i!==void 0&&i.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(on(t,this.defaultHashes[n]))return[];let i=await this.store.getNode(t);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(on(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(t,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,t,n,i,a){if(a>=ys||on(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return on(o.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,i,n,a);let s=o,c=uo(t,a),l,d;c?(l=s.leftHash,d=await this.insertAtNode(s.rightHash,t,n,i,a+1)):(l=await this.insertAtNode(s.leftHash,t,n,i,a+1),d=s.rightHash);let u=await Tl(l,d);if(!on(u,e)){let f={type:"internal",leftHash:l,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,a){let o=a;for(;o<ys&&uo(e.keyHash,o)===uo(n.keyHash,o);)o++;if(o>=ys)return i;let s=uo(e.keyHash,o),c,l;s?(c=i,l=t):(c=t,l=i);let d=await Tl(c,l);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:l});for(let u=o-1;u>=a;u--){let f=uo(e.keyHash,u),p=this.defaultHashes[u+1],h,m;f?(h=p,m=d):(h=d,m=p),d=await Tl(h,m),await this.store.putNode(d,{type:"internal",leftHash:h,rightHash:m})}return d}async deleteAtNode(e,t,n){if(n>=ys)return this.defaultHashes[ys];if(on(e,this.defaultHashes[n]))return e;let i=await this.store.getNode(e);if(i===void 0)return this.defaultHashes[n];if(i.type==="leaf")return on(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,o=uo(t,n),s,c;if(o?(s=a.leftHash,c=await this.deleteAtNode(a.rightHash,t,n+1)):(s=await this.deleteAtNode(a.leftHash,t,n+1),c=a.rightHash),on(s,this.defaultHashes[n+1])&&on(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=on(s,this.defaultHashes[n+1]),d=on(c,this.defaultHashes[n+1]);if(l||d){let f=l?c:s,p=await this.store.getNode(f);if(p!==void 0&&p.type==="leaf")return await this.store.deleteNode(e),f}let u=await Tl(s,c);if(!on(u,e)){let f={type:"internal",leftHash:s,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=ys||on(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return on(i.keyHash,t);let a=i;return uo(t,n)?this.existsAtNode(a.rightHash,t,n+1):this.existsAtNode(a.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=ys)return{siblings:[],leafNode:void 0,depth:n};if(on(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let i=await this.store.getNode(e);if(i===void 0)return{siblings:[],leafNode:void 0,depth:n};if(i.type==="leaf")return{siblings:[],leafNode:i,depth:n};let a=i,o=uo(t,n),s,c;o?(s=a.rightHash,c=a.leftHash):(s=a.leftHash,c=a.rightHash);let l=await this.generateProof(s,t,n+1);return l.siblings.unshift(c),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(uo(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await yy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(uo(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=ys||on(e,this.defaultHashes[t]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let i=n,a=await this.collectLeaves(i.leftHash,t+1),o=await this.collectLeaves(i.rightHash,t+1);return[...a,...o]}async diffAtNode(e,t,n,i,a,o,s){if(on(e,t)||n>=ys)return;let c=on(e,this.defaultHashes[n]),l=on(t,this.defaultHashes[n]);if(c&&!l){let f=await a.collectLeaves(t,n);s.push(...f);return}if(!c&&l){let f=await i.collectLeaves(e,n);o.push(...f);return}let d=await i.store.getNode(e),u=await a.store.getNode(t);if(d?.type==="leaf"&&u?.type==="leaf"){on(d.keyHash,u.keyHash)?d.valueCid!==u.valueCid&&(o.push(d.valueCid),s.push(u.valueCid)):(o.push(d.valueCid),s.push(u.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(t,n),p=d.valueCid;new Set(f).has(p)||o.push(p);for(let m of f)m!==p&&s.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),p=u.valueCid;new Set(f).has(p)||s.push(p);for(let m of f)m!==p&&o.push(m);return}if(d?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(d.leftHash,u.leftHash,n+1,i,a,o,s),await this.diffAtNode(d.rightHash,u.rightHash,n+1,i,a,o,s);return}if(d===void 0){let f=await a.collectLeaves(t,n);s.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);o.push(...f)}}}});var $f,LG=G(()=>{"use strict";g();Hu();_6();A6();kf();$f=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Ys,...e}}async open(){this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Al()}async close(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.close()}async clear(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.clear()}async insert(e,t,n){await(await this.getGlobalTree(e)).insert(t);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let a=await this.getStoredIndexes(e,i);if(await n.delete(i),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(i)}await this.deleteStoredIndexes(e,i)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,t){return(await this.getProtocolTree(e,t)).getRoot()}async getSubtreeHash(e,t){return(await this.getGlobalTree(e)).getSubtreeHash(t)}async getProtocolSubtreeHash(e,t,n){return(await this.getProtocolTree(e,t)).getSubtreeHash(n)}async getLeaves(e,t){return(await this.getGlobalTree(e)).getLeaves(t)}async getProtocolLeaves(e,t,n){return(await this.getProtocolTree(e,t)).getLeaves(n)}getGlobalTree(e){let t=this.globalTrees.get(e);return t!==void 0||(t=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,t)),t}getProtocolTree(e,t){let n=`${e}\0${t}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",t]),this.protocolTrees.set(n,i)),i}async createTree(e,t){let n=e;for(let o of t)n=await n.partition(o);let i=new ag(n),a=new cg(i);return await a.initialize(),a}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(t,JSON.stringify(a))}async getStoredIndexes(e,t){let i=await(await this.getMetaPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,t){await(await this.getMetaPartition(e)).delete(t)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var qE,qG=G(()=>{"use strict";g();Hu();qE=class{nodes=new Map;root;async open(){}async close(){}async clear(){this.nodes.clear(),this.root=void 0}async getNode(e){return this.nodes.get(an(e))}async putNode(e,t){this.nodes.set(an(e),t)}async deleteNode(e){this.nodes.delete(an(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var Pye,zE,zG=G(()=>{"use strict";g();km();al();yu();ea();CS();In();Kc();fx();mx();Ho();u1();t2();n2();ti();dx();b0();lx();u2();Gs();Oi();Vb();Yl();ms();Pn();lv();ur();Um();Pye={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},zE=class r{static async generatePersona(e){let t=e?.did;t||(t=`did:example:${r.randomString(32)}`);let n=r.randomString(10),i=e?.keyId??`${t}#${n}`,a=e?.keyPair??await Va.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await At.generateKey();o={publicJwk:await At.getPublicKey({key:c}),privateJwk:c}}return{did:t,keyId:i,keyPair:a,encryptionKeyPair:o,signer:new rl({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await _a.create({definition:Pye,signer:ut.createSigner(t)}),i=await e.processMessage(t.did,n.message);if(i.status.code!==202)throw new Error(`Failed to install default test protocol: ${i.status.code} ${i.status.detail}`)}static async generateProtocolsConfigure(e){let t=e?.author??await r.generatePersona(),n=e?.protocolDefinition;if(!n){let s="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[s]={schema:"test-object",dataFormats:["text/plain"]},n.structure[s]={}}let i=ut.createSigner(t),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await _a.create(a);return{author:t,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};rr(i);let a=await Aa.create(i);return{author:t,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??kt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:ve.Messages,method:me.Read},o=ut.createSigner(t),s=n.did,c={signer:o,grantedTo:s,dateExpires:i,scope:a,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await rt.createGrant(c);return{dataStream:Wt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i=ut.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,s,c;a===void 0&&o===void 0&&(s=e?.data??r.randomBytes(32),c=Wt.fromBytes(s));let l={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${r.randomString(20)}`,tags:e?.tags,recordId:e?.recordId,parentContextId:e?.parentContextId,published:e?.published,dataFormat:e?.dataFormat??"application/json",dateCreated:e?.dateCreated,messageTimestamp:e?.messageTimestamp,datePublished:e?.datePublished,data:s,dataCid:a,dataSize:o,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await _t.create(l),u=d.message;return{author:t,message:u,dataCid:a,dataSize:o,dataBytes:s,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:a,protocolPath:o,protocolParentContextId:s,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:l}=e,d=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:p}=await Ei.aeadEncrypt(di.A256GCM,u,d,t),h=o.split("/"),m=h[h.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:a.protocol,protocolPath:o,parentContextId:s,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),x={initializationVector:d,key:u,authenticationTag:p,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let $ of h)_=_[$];let A=_.$encryption?.publicKeyJwk,N={publicKeyId:_.$encryption?.rootKeyId,publicKey:A,derivationScheme:Pt.ProtocolPath};x.keyEncryptionInputs.push(N)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(s===void 0){let A={rootKeyId:n.keyId,derivationScheme:Pt.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await _t.getEntryId(n.did,y.descriptor),N=Ie.constructKeyDerivationPathUsingProtocolContextScheme(D),$=await Ni.derivePublicKey(A,N);_={publicKeyId:n.keyId,publicKey:$,derivationScheme:Pt.ProtocolContext}}else{if(c===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:l,derivationScheme:Pt.ProtocolContext}}x.keyEncryptionInputs.push(_)}return await w.encryptSymmetricEncryptionKey(x),await w.sign({signer:ut.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:x}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=kt.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),a=e.datePublished??(i?n:void 0),o=e.data??r.randomBytes(32),s=Wt.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ut.createSigner(e.author)},l=await _t.createFrom(c);return{message:l.message,recordsWrite:l,dataBytes:o,dataStream:s}}static async generateRecordsQuery(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};rr(a);let s=(await ba.create(a)).message;return{author:t,message:s}}static async generateRecordsSubscribe(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};rr(a);let s=(await Ia.create(a)).message;return{author:t,message:s}}static async generateRecordsCount(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};rr(a);let s=(await hd.create(a)).message;return{author:t,message:s}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await Ta.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ut.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};rr(i);let a=await gd.create(i),o=a.message;return{author:t,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:ut.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await yd.create(i);return{author:t,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Kg.generateKeyPair(),t=await Kg.sign(r.randomBytes(32),e.privateJwk);return De.bytesToBase64Url(t)}static randomString(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=t.charAt(Math.floor(Math.random()*t.length));return n}static randomBytes(e){let t=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return t}static async randomCborSha256Cid(){let e=r.randomBytes(32),t=await Mn.digest(e);return(await tr.createV1(mu,t)).toString()}static randomInt(e,t){return Math.floor(Math.random()*(t-e)+e)}static randomTimestamp(e){let{year:t,month:n,day:i,hour:a,minute:o,second:s,millisecond:c,microsecond:l}=e||{};return kt.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:s||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:l||this.randomInt(0,1e3)})}static createDidResolutionResult(e){return{didResolutionMetadata:{},didDocument:{id:e.did,verificationMethod:[{controller:e.did,id:e.keyId,type:"JsonWebKey2020",publicKeyJwk:e.keyPair.publicJwk}]},didDocumentMetadata:{}}}static async generateDidKeyPersona(){let e=await cb.create(),t=await cb.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),a={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},o=await At.generateKey(),c={publicJwk:await At.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new rl({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var FE,FG=G(()=>{"use strict";g();ms();FE=class r{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,t=r.pollRetrySleep,n=r.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await kt.sleep(t)}}}});var GG={};cr(GG,{AllowAllTenantGate:()=>hy,BlockstoreLevel:()=>_f,Cid:()=>mr,ContentEncryptionAlgorithm:()=>di,CoreProtocolRegistry:()=>py,DataStoreLevel:()=>If,DataStream:()=>Wt,DateSort:()=>Ut,Dwn:()=>rg,DwnConstant:()=>lo,DwnError:()=>ie,DwnErrorCode:()=>re,DwnInterfaceName:()=>ve,DwnMethodName:()=>me,Encoder:()=>De,Encryption:()=>Ei,EventEmitterEventLog:()=>Cf,HdKey:()=>Ni,IndexLevel:()=>_h,Jws:()=>ut,KeyAgreementAlgorithm:()=>dv,KeyDerivationScheme:()=>Pt,LevelWrapper:()=>qa,Message:()=>ye,MessageStoreLevel:()=>Df,MessagesRead:()=>yd,MessagesSubscribe:()=>gd,MessagesSync:()=>Vu,PERMISSIONS_REVOCATION_PATH:()=>EP,PermissionConditionPublication:()=>Lm,PermissionGrant:()=>Ir,PermissionRequest:()=>md,PermissionsProtocol:()=>rt,Poller:()=>FE,PrivateKeySigner:()=>rl,ProtocolRecordLimitStrategy:()=>Wl,Protocols:()=>xd,ProtocolsConfigure:()=>_a,ProtocolsQuery:()=>Aa,Records:()=>Ie,RecordsCount:()=>hd,RecordsDelete:()=>Ta,RecordsQuery:()=>ba,RecordsRead:()=>Sd,RecordsSubscribe:()=>Ia,RecordsWrite:()=>_t,ResumableTaskStoreLevel:()=>Rf,SMTStoreLevel:()=>ag,SMTStoreMemory:()=>qE,SMT_DEPTH:()=>ys,Secp256k1:()=>Va,Secp256r1:()=>tl,SortDirection:()=>Rt,SparseMerkleTree:()=>cg,StateIndexLevel:()=>$f,TestDataGenerator:()=>zE,Time:()=>kt,ZERO_HASH:()=>gx,authenticate:()=>yn,createLevelDatabase:()=>Ys,executeUnlessAborted:()=>Zn,getBit:()=>uo,getDefaultHashes:()=>NI,getRuleSetAtPath:()=>Ed,hashChildren:()=>Tl,hashEquals:()=>on,hashKey:()=>Fu,hashLeaf:()=>yy,hashToHex:()=>an,hexToHash:()=>Gu,initDefaultHashes:()=>Al,isCrossProtocolRef:()=>nf,parseCrossProtocolRef:()=>Ws});var Xn=G(()=>{"use strict";g();Bg();Fo();jI();bT();MI();ll();dx();lx();yu();Um();fF();my();Et();ur();In();mx();lv();Gs();yE();Kc();vr();fx();UI();dc();KI();Ho();u1();Xp();t2();n2();ti();b0();LR();u2();Vb();Ok();ed();ms();PT();mp();gE();PG();E6();kf();OG();jG();UG();LG();A6();_6();qG();Hu();zG();FG()});var JE=Ae((EHe,XG)=>{g();var ug=1e3,fg=ug*60,pg=fg*60,Ih=pg*24,Rye=Ih*7,Cye=Ih*365.25;XG.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return $ye(r);if(t==="number"&&isFinite(r))return e.long?Oye(r):Bye(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function $ye(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Cye;case"weeks":case"week":case"w":return t*Rye;case"days":case"day":case"d":return t*Ih;case"hours":case"hour":case"hrs":case"hr":case"h":return t*pg;case"minutes":case"minute":case"mins":case"min":case"m":return t*fg;case"seconds":case"second":case"secs":case"sec":case"s":return t*ug;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Bye(r){var e=Math.abs(r);return e>=Ih?Math.round(r/Ih)+"d":e>=pg?Math.round(r/pg)+"h":e>=fg?Math.round(r/fg)+"m":e>=ug?Math.round(r/ug)+"s":r+"ms"}function Oye(r){var e=Math.abs(r);return e>=Ih?WE(r,e,Ih,"day"):e>=pg?WE(r,e,pg,"hour"):e>=fg?WE(r,e,fg,"minute"):e>=ug?WE(r,e,ug,"second"):r+" ms"}function WE(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();Xn();Xn();var Re=(d=>(d[d.MessagesRead=ve.Messages+me.Read]="MessagesRead",d[d.MessagesSubscribe=ve.Messages+me.Subscribe]="MessagesSubscribe",d[d.MessagesSync=ve.Messages+me.Sync]="MessagesSync",d[d.ProtocolsConfigure=ve.Protocols+me.Configure]="ProtocolsConfigure",d[d.ProtocolsQuery=ve.Protocols+me.Query]="ProtocolsQuery",d[d.RecordsDelete=ve.Records+me.Delete]="RecordsDelete",d[d.RecordsQuery=ve.Records+me.Query]="RecordsQuery",d[d.RecordsRead=ve.Records+me.Read]="RecordsRead",d[d.RecordsSubscribe=ve.Records+me.Subscribe]="RecordsSubscribe",d[d.RecordsWrite=ve.Records+me.Write]="RecordsWrite",d))(Re||{}),Ah={[Re.MessagesRead]:yd,[Re.MessagesSubscribe]:gd,[Re.MessagesSync]:Vu,[Re.ProtocolsConfigure]:_a,[Re.ProtocolsQuery]:Aa,[Re.RecordsDelete]:Ta,[Re.RecordsQuery]:ba,[Re.RecordsRead]:Sd,[Re.RecordsSubscribe]:Ia,[Re.RecordsWrite]:_t};g();async function T6(r){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort()),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort()));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(i),o="";for(let s of a)o+=String.fromCharCode(s);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var I6=100;g();var D6="^",as=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${D6}${t}${D6}${n}`}async getOrCreateLink(e){let t=await T6(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let a=await this.sublevel.get(n),o=JSON.parse(a);return delete o.push,o.connectivity="unknown",o}catch(a){if(a.code!=="LEVEL_NOT_FOUND")throw a}let i={tenantDid:e.tenantDid,remoteEndpoint:e.remoteEndpoint,scopeId:t,scope:e.scope,status:"initializing",connectivity:"unknown",pull:{},needsReconcile:!1,delegateDid:e.delegateDid,protocol:e.protocol};return await this.sublevel.put(n,JSON.stringify(i)),i}async saveLink(e){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),await this.sublevel.put(t,JSON.stringify(e))}async deleteLink(e,t,n){let i=r.buildKey(e,t,n);await this.sublevel.del(i)}async getLinksForTenant(e){let t=`${e}${D6}`,n=[];for await(let[i,a]of this.sublevel.iterator())i.startsWith(t)&&n.push(JSON.parse(a));return n}async getAllLinks(){let e=[];for await(let[,t]of this.sublevel.iterator())e.push(JSON.parse(t));return e}async setStatus(e,t){e.status=t,await this.saveLink(e)}static comparePosition(e,t){let n=BigInt(e.position)-BigInt(t.position);return n<BigInt(0)?-1:n>BigInt(0)?1:0}static validateTokenDomain(e,t){return e.contiguousAppliedToken===void 0?!0:t.streamId===e.contiguousAppliedToken.streamId&&t.epoch===e.contiguousAppliedToken.epoch}static setReceivedToken(e,t){(e.receivedToken===void 0||r.comparePosition(t,e.receivedToken)>0)&&(e.receivedToken=t)}static commitContiguousToken(e,t){e.contiguousAppliedToken=t}static resetCheckpoint(e,t){e.contiguousAppliedToken=t,e.receivedToken=t}async markNeedsReconcile(e,t){e.needsReconcile||(e.needsReconcile=!0,await this.saveLink(e))}async clearNeedsReconcile(e){e.needsReconcile&&(e.needsReconcile=!1,await this.saveLink(e))}};g();var R6=(p=>(p.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",p.InitialWriteMissing="ClosureInitialWriteMissing",p.ParentChainMissing="ClosureParentChainMissing",p.ContextChainMissing="ClosureContextChainMissing",p.GrantMissing="ClosureGrantMissing",p.GrantNotYetActive="ClosureGrantNotYetActive",p.GrantExpired="ClosureGrantExpired",p.GrantRevocationMissing="ClosureGrantRevocationMissing",p.VisibilityFloorMissing="ClosureVisibilityFloorMissing",p.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",p.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",p.DependencyForbidden="ClosureDependencyForbidden",p.DepthExceeded="ClosureDepthExceeded",p))(R6||{});function wb(r,e){return{tenantDid:r,protocolCache:new Map,grantCache:new Map,satisfiedDeps:new Set,missingDeps:new Set,maxDepth:e??32}}function HG(r,e){let t=e.descriptor;if(t.interface==="Protocols"&&t.method==="Configure"){let n=t.definition?t.definition.protocol:void 0;n&&r.protocolCache.delete(n)}if(t.protocol==="https://identity.foundation/dwn/permissions"){let n=e.recordId,i=t.protocolPath;if(i==="grant"&&n&&(r.grantCache.delete(n),r.satisfiedDeps.delete(`permissionGrant:grantId:${n}`),r.missingDeps.delete(`permissionGrant:grantId:${n}`)),i==="grant/revocation"){let a=t.parentId;a&&(r.grantCache.delete(`revocation:${a}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${a}`),r.missingDeps.delete(`grantRevocation:grantId:${a}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${a}`),r.missingDeps.delete(`permissionGrant:grantId:${a}`))}}if(t.interface==="Records"){let n=e.recordId,i=t.protocol,a=t.protocolPath;if(n){let o=s=>{let c=s.indexOf(n);if(c===-1)return!1;let l=c>0?s[c-1]:":",d=c+n.length<s.length?s[c+n.length]:"|",u=l===":"||l==="|",f=d==="|"||d===void 0;return u&&(c+n.length===s.length||f)};for(let s of r.satisfiedDeps)o(s)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)o(s)&&r.missingDeps.delete(s)}if(i&&a){let o=`filter:${i}|${a}`;for(let s of r.satisfiedDeps)s.includes(o)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)s.includes(o)&&r.missingDeps.delete(s)}if(i==="https://identity.foundation/protocols/key-delivery"){let s=e.descriptor?.tags?.protocol;if(s){let c=`messageCid:${s}|`;for(let l of r.satisfiedDeps)l.includes(c)&&r.satisfiedDeps.delete(l);for(let l of r.missingDeps)l.includes(c)&&r.missingDeps.delete(l)}}else if(i){let o=`messageCid:${i}|`;for(let s of r.satisfiedDeps)s.includes(o)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)s.includes(o)&&r.missingDeps.delete(s)}}}g();Xn();g();function VG(r,e){let t=e.split("/"),n=r.structure;for(let i of t)if(n=n[i],!n)return;return n}function zGe(r){return r.split("/")[0]||r}function Th(r,e){let t=VG(r,e);if(!t)return!1;function n(i){for(let a in i)if(!a.startsWith("$")){let o=i[a];if(o.$role===!0||n(o))return!0}return!1}return n(t)?!0:C6(void 0,e,r)}function C6(r,e,t){let n=t.structure;function i(a){if(a.$actions){for(let o of a.$actions)if(o.who&&o.who!=="anyone"&&(r===void 0||o.who===r)&&o.of===e&&o.can?.includes("read"))return!0}for(let o in a)if(!o.startsWith("$")&&i(a[o]))return!0;return!1}return i(n)}function $6({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let a=new Set,o=VG(r,e);return o&&(o.$role===!0&&t&&a.add(t),t&&t!==n&&C6("recipient",e,r)&&a.add(t),i&&i!==n&&C6("author",e,r)&&a.add(i),a.delete(n)),a}function xye(r){let t=r.descriptor.protocol;return t?t===rt.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function Eye(r){let e=r.descriptor,t=[];if(e.interface!=="Records")return[];let n=r.recordId,i=e.parentId;i&&t.push({dependencyClass:2,label:"parentRecord",identifier:i,identifierType:"recordId"});let a=r.contextId;if(a&&n&&a!==n){let o=a.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:o,identifierType:"recordId"})}if(n&&e.method==="Write"){let o=e.dateCreated,s=e.messageTimestamp;o&&s&&o!==s&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"})}return n&&e.method==="Delete"&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"}),t}function Sye(r){let e=[],t=r.authorization;if(!t)return[];let n=t.signature?.payload;if(n)try{let i=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));i.permissionGrantId&&(e.push({dependencyClass:3,label:"permissionGrant",identifier:i.permissionGrantId,identifierType:"grantId"}),e.push({dependencyClass:3,label:"grantRevocation",identifier:i.permissionGrantId,identifierType:"grantId"}))}catch{}return e}function kye(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let a of t){if(!Object.hasOwn(n,a))return;i=n[a],n=i}return i}function _ye(r,e){let t=r.descriptor;if(t.interface!=="Records")return[];let n=t.protocolPath;if(!n)return[];let i=[];if(kye(e?.structure,n)?.$encryption){let l=n.split("/").pop();if(e?.types?.[l??""]?.encryptionRequired===!0){i.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:t.protocol,identifierType:"protocol"}),i.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"});let f=r.contextId;if(f){let p=n.split("/")[0];if(Th(e,p)){let m=f.split("/")[0];i.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${t.protocol}|${m}`,identifierType:"messageCid"})}}}}let o=n.split("/")[0],s=e?.structure?.[o];if(s?.$ref){let l=s.$ref.indexOf(":");if(l>0){let d=s.$ref.substring(0,l),f=e?.uses?.[d];if(f){i.push({dependencyClass:6,label:"crossProtocolConfig",identifier:f,identifierType:"protocol"});let p=n.split("/"),h=t.parentId;p.length===2&&h&&i.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${f}|${h}`,identifierType:"recordId"})}}}let c=r.authorization;if(c&&e?.uses){let l=c.signature?.payload;if(l)try{let u=JSON.parse(Buffer.from(l,"base64url").toString("utf-8")).protocolRole;if(u&&u.includes(":")){let f=u.indexOf(":"),p=u.substring(0,f),h=e.uses[p];if(h){i.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:h,identifierType:"protocol"});let m=u.substring(f+1),y=ye.getAuthor(r),v=r.contextId;if(y){let w={interface:"Records",method:"Write",protocol:h,protocolPath:m,recipient:y,isLatestBaseState:!0};if(v){let _=m.split("/").length-1;if(_>0){let D=v.split("/").slice(0,_).join("/");D&&(w.contextId={gte:D,lt:D+"\uFFFF"})}}let x=w.contextId?JSON.stringify(w.contextId):"no-context";i.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${h}|${m}|${y}|${x}`,identifierType:"filter",filter:w})}}}}catch{}}return i}async function GE(r,e,t,n){if(t.kind==="full")return{complete:!0,rootMessageCid:await ye.getCid(r),edges:[],depth:0};let i=await ye.getCid(r),a=[],o=new Set,s=0,c=[r];for(o.add(i);c.length>0;){if(s>=n.maxDepth)return{complete:!1,rootMessageCid:i,edges:a,failure:{code:"ClosureDepthExceeded",edge:{dependencyClass:1,label:"depth",identifier:String(s),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:s};let l=c.length;for(let d=0;d<l;d++){let u=c.shift(),f=[...xye(u),...Eye(u),...Sye(u)],p=await WG(f,a,e,n,o,c,i,s);if(p)return p;let m=u.descriptor.protocol;if(m){let v=n.protocolCache.get(m)?.descriptor?.definition;if(v){let w=_ye(u,v),x=await WG(w,a,e,n,o,c,i,s);if(x)return x}}if(s===0){let y=Tye(u,a,n,i,s);if(y)return y}}s++}return{complete:!0,rootMessageCid:i,edges:a,depth:s}}async function Aye(r,e,t,n,i){let a=wb(n,i),o=[];for(let s of r){let c=await GE(s,e,t,a);o.push(c)}return o}function Tye(r,e,t,n,i){let a=e.find(p=>p.label==="permissionGrant");if(!a)return null;let o=r.descriptor.messageTimestamp;if(!o)return null;let s=t.grantCache.get(a.identifier);if(!s)return null;let c=s.descriptor.dateCreated,l,d=s.encodedData;if(d)try{l=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).dateExpires}catch{}if(c&&o<c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantNotYetActive",edge:a,detail:`grant '${a.identifier}' is not yet active at message timestamp ${o} (dateGranted: ${c})`},depth:i};if(l&&o>=l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantExpired",edge:a,detail:`grant '${a.identifier}' expired at ${l}, message timestamp is ${o}`},depth:i};let u=`revocation:${a.identifier}`,f=t.grantCache.get(u);if(f&&f.descriptor.interface!=="Synthetic"){let p=f.descriptor.messageTimestamp;if(p&&p<=o)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantRevocationMissing",edge:e.find(h=>h.label==="grantRevocation")??a,detail:`grant '${a.identifier}' was revoked at ${p}, before message timestamp ${o}`},depth:i}}return null}async function WG(r,e,t,n,i,a,o,s){for(let c of r){e.push(c);let l=`${c.label}:${c.identifierType}:${c.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:o,edges:e,failure:{code:JG(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) is missing`},depth:s};let d=await Iye(c,t,n);if(!d)return n.missingDeps.add(l),{complete:!1,rootMessageCid:o,edges:e,failure:{code:JG(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) not found locally`},depth:s};if(n.satisfiedDeps.add(l),!(c.identifierType==="grantId"||c.identifierType==="filter"||c.label==="contextKeyRecord")){let f=await ye.getCid(d);i.has(f)||(i.add(f),a.push(d))}}return null}async function Iye(r,e,t){switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return t.protocolCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.protocolCache.set(r.identifier,i),i}case"recordId":{if(r.label==="initialWrite"){let{messages:i}=await e.query(t.tenantDid,[{entryId:r.identifier}]);if(i.length>0)return i[0];let{messages:a}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return a.length>0?a[0]:null}if(r.label==="crossProtocolParent"){let i=r.identifier.indexOf("|");if(i>0){let a=r.identifier.substring(0,i),o=r.identifier.substring(i+1),{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:a,recordId:o,isLatestBaseState:!0}]);return s.length>0?s[0]:null}}let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return n.length>0?n[0]:null}case"grantId":{if(r.label==="grantRevocation"){let a=`revocation:${r.identifier}`;if(t.grantCache.has(a))return t.grantCache.get(a)??null;let{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),s;for(let d of o){let u=d.descriptor.messageTimestamp;(!s||u<s.descriptor.messageTimestamp)&&(s=d)}let l=s??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(a,l),l}if(t.grantCache.has(r.identifier))return t.grantCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.grantCache.set(r.identifier,i),i}case"messageCid":{if(r.label==="contextKeyRecord"){let n=r.identifier.indexOf("|");if(n>0){let i=r.identifier.substring(0,n),a=r.identifier.substring(n+1),{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":i,"tag.contextId":a}]);return o.length>0?o[0]:null}}return await e.get(t.tenantDid,r.identifier)??null}case"filter":{if(!r.filter)return null;let{messages:n}=await e.query(t.tenantDid,[r.filter]);return n.length>0?n[0]:null}default:return null}}function JG(r){switch(r.dependencyClass){case 1:return"ClosureProtocolMetadataMissing";case 2:return r.label==="initialWrite"?"ClosureInitialWriteMissing":r.label==="parentRecord"?"ClosureParentChainMissing":r.label==="contextRoot"?"ClosureContextChainMissing":"ClosureParentChainMissing";case 3:return r.label==="permissionGrant"?"ClosureGrantMissing":"ClosureGrantRevocationMissing";case 4:return r.label==="squashContextRoot"?"ClosureVisibilityFloorMissing":"ClosureVisibilityFloorMissing";case 5:return"ClosureEncryptionDependencyMissing";case 6:return"ClosureCrossProtocolReferenceMissing";default:return"ClosureDependencyForbidden"}}g();ea();Sr();var Bf=class extends hE{constructor({agent:t,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=t}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(t){this._agent=t}async get(t){try{let n=await this.cache.get(t),i=JSON.parse(n);if(!this._resolving.has(t)&&Date.now()>=i.ttlMillis){this._resolving.set(t,!0);let a=await this.agent.did.get({didUri:t,tenant:this.agent.agentDid.uri});if(typeof a<"u")try{let o=await this.agent.did.resolve(t);if(!o.didResolutionMetadata.error&&o.didDocument){let s={...a,document:o.didDocument,metadata:o.didDocumentMetadata};try{await this.agent.did.update({portableDid:s,tenant:this.agent.agentDid.uri,publish:!1})}catch(c){c.message&&!c.message.includes("No changes detected, update aborted")&&Ms.error(`Error updating DID: ${c.message}`)}}}finally{this._resolving.delete(t)}else this._resolving.delete(t),this.cache.nextTick(()=>this.cache.del(t))}return i.value}catch(n){if(n.notFound)return;throw n}}};g();Xn();g();ea();Xn();async function dg(r,e){let t=await e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(FC.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function nHe(r){return ye.getAuthor(r)}function iHe(r){return ut.decodePlainObjectPayload(r.authorization.signature)?.protocolRole}function jd(r){return!r||typeof r!="object"||r===null?!1:"message"in r&&typeof r.message=="object"&&r.message!==null&&"descriptor"in r.message&&typeof r.message.descriptor=="object"&&r.message.descriptor!==null&&"interface"in r.message.descriptor&&r.message.descriptor.interface===ve.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function Dye(r){return ye.getCid(r)}async function sHe(r,e){let t=e===Ut.CreatedAscending||e===Ut.CreatedDescending?r.descriptor.dateCreated:r.descriptor.datePublished;if(t===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await Dye(r),value:t}}function oHe(r,e=3e3,t=3e5,n){let i=Date.now()+t,a=null,o=!0;return new Promise((s,c)=>{n&&n.addEventListener("abort",()=>{o=!1,a!==null&&clearTimeout(a),console.log("Polling aborted by user"),s(null)});async function l(){if(!o)return;let d=i-Date.now();if(d<=0){o=!1,console.log("Polling stopped: TTL reached"),s(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(d/1e3)}s)`);try{let u=await r();if(u.ok){o=!1,a!==null&&clearTimeout(a),console.log("Polling stopped: Success condition met"),s(u);return}}catch(u){console.error("Error fetching data:",u),c(u)}o&&(a=setTimeout(l,e))}l()})}function vb(r,e){return r.endsWith("/")&&(r=r.slice(0,-1)),e.startsWith("/")&&(e=e.slice(1)),`${r}/${e}`}var ZG=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}async recordsQuery(e,t){let n=await ba.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,t){let n=await Sd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,t,n){let i=await Ia.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,t){let n=await hd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,t){let n=await Aa.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,t,n,i){let a=await dg(e,this._didResolver),o=[];for(let s of a)try{if(i!==void 0){if(!(await this._rpcClient.getServerInfo(s)).webSocketSupport){o.push({url:s,message:"WebSocket support is not enabled on the server."});continue}let d=new URL(s);d.protocol=d.protocol==="http:"?"ws:":"wss:",s=d.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:s,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(c){o.push({url:s,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(o)}`)}};g();var lg=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();Pn();var B6={"AES-GCM":{implementation:Mm,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Km,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Yc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:wP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:bP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:fc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:fc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:Iu,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Ru,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},xo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:t})}async bytesToPublicKey({algorithm:e,publicKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:t})}async decrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).decrypt(e)}async deriveKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:t}),i;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{i=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{i=e.algorithm.split(/[-+]/)[2];break}default:throw new Fe(Le.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new Fe(Le.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${i}`);let o=await n.deriveKeyBytes({...e,length:a});return await this.bytesToPrivateKey({algorithm:i,privateKeyBytes:o})}async deriveKeyBytes(e){let t=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)}async digest({algorithm:e,data:t}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})}async encrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).encrypt(e)}async generateKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:t}).generateKey({algorithm:e.algorithm});return i.kid??=await vt({jwk:i}),i}async getPublicKey({key:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:t}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:t,key:e})}async unwrapKey(e){let t=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:t}).unwrapKey(e)}async verify({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})}async wrapKey(e){let t=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:t}).wrapKey(e)}getAlgorithm({algorithm:e}){let t=B6[e]?.implementation;if(!t)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({algorithm:e,key:t}){let n=t?.alg??e,i=t?.crv;for(let a of Object.keys(B6)){let o=B6[a].names;if(n&&o.includes(n))return a;if(i&&o.includes(i))return a}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();ea();Pn();g();Sr();ea();g();var HE={protocol:"https://identity.foundation/protocols/web5/identity-store",published:!1,types:{portableDid:{schema:"https://identity.foundation/schemas/web5/portable-did",dataFormats:["application/json"]},identityMetadata:{schema:"https://identity.foundation/schemas/web5/identity-metadata",dataFormats:["application/json"]}},structure:{portableDid:{},identityMetadata:{}}},za={protocol:"https://identity.foundation/protocols/key-delivery",published:!1,types:{contextKey:{dataFormats:["application/json"]}},structure:{contextKey:{$actions:[{who:"recipient",of:"contextKey",can:["read"]}],$tags:{$requiredTags:["protocol","contextId"],$allowUndefinedTags:!1,protocol:{type:"string"},contextId:{type:"string"}}}}},YG={protocol:"https://identity.foundation/protocols/web5/jwk-store",published:!1,types:{privateJwk:{schema:"https://identity.foundation/schemas/web5/private-jwk",dataFormats:["application/json"],encryptionRequired:!0}},structure:{privateJwk:{}}};g();Pn();var Ri="^",VE=class extends Xc{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let t={};for(let n of e){n.kid??=await vt({jwk:n});let i=await this.getKeyUri({key:n});t[i]=n}this._predefinedKeys=new Map(Object.entries(t)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return t}async generateKey(e){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t}async getPublicKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=t;return i}async sign({keyUri:e,data:t}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await Un.sign({data:t,key:n})}};async function Md({agent:r,tenant:e,didUri:t}){if(e)return e;if(r.agentDid)return r.agentDid.uri;if(!t)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return t}g();var bb=Tn(JE(),1);Sr();Xn();var Of=class{constructor(){this.name="DwnDataStore";this._cache=new xi.default({ttl:(0,bb.default)("15 minutes"),max:100});this._index=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._protocolInitializedCache=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._tenantEncryptionActive=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:t});if(!a)return!1;let{reply:{status:o}}=await t.dwn.processRequest({author:i,target:i,messageType:Re.RecordsDelete,messageParams:{recordId:a}});if(o.code===202)return this._index.delete(`${i}${Ri}${e}`),this._cache.delete(a),!0;throw new Error(`${this.name}: Failed to delete '${e}' from store: (${o.code}) ${o.detail}`)}async get({id:e,agent:t,tenant:n,useCache:i=!1}){let a=await Md({agent:t,tenant:n,didUri:e}),o=await this.lookupRecordId({id:e,tenantDid:a,agent:t});if(o)return await this.getRecord({recordId:o,tenantDid:a,agent:t,useCache:i})}async list({agent:e,tenant:t}){let n=await Md({tenant:t,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:o=!1,useCache:s=!1}){let c=await Md({agent:i,tenant:n,didUri:e});await this.initialize({tenant:c,agent:i});let l={...this._recordProperties};if(o){let h=await this.getExistingRecordEntry({id:e,tenantDid:c,agent:i});if(!h)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=h.recordsWrite.recordId,l.dateCreated=h.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:c,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=he.object(t).toUint8Array(),u=this.isEncryptionActive(c),{message:f,reply:{status:p}}=await i.dwn.processRequest({author:c,target:c,messageType:Re.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([d],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${p.detail}`);this._index.set(`${c}${Ri}${e}`,f.recordId),s&&this._cache.set(f.recordId,t)}async initialize({tenant:e,agent:t}){let n=await Md({agent:t,tenant:e});if(this._protocolInitializedCache.has(n))return;let{reply:{status:i,entries:a}}=await t.dwn.processRequest({author:n,target:n,messageType:Re.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);if(a?.length===0)await this.installProtocol(n,t);else if(this.encryptionRequired&&!this._tenantEncryptionActive.has(n)){let o=a[0].descriptor?.definition,s=Object.keys(o?.structure??{})[0],c=!!(s&&o?.structure[s]?.$encryption);this._tenantEncryptionActive.set(n,c)}this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}async getAllRecords(e){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")}async getRecord({recordId:e,tenantDid:t,agent:n,useCache:i}){if(i){let c=this._cache.get(e);if(c)return c}let a=this.isEncryptionActive(t),{reply:o}=await n.dwn.processRequest({author:t,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:e}},...a?{encryption:!0}:{}});if(!o.entry?.data)throw new Error(`${this.name}: Failed to read data from DWN for: ${e}`);let s=await Bm.consumeToJson({readableStream:o.entry.data});return i&&this._cache.set(e,s),s}async installProtocol(e,t){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let o=await t.dwn.getEncryptionKeyDeriver(e);n=await xd.deriveAndInjectPublicEncryptionKeys(n,o),i=!0}this._tenantEncryptionActive.set(e,i);let{reply:{status:a}}=await t.dwn.processRequest({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`)}async lookupRecordId({id:e,tenantDid:t,agent:n}){let i=this._index.get(`${t}${Ri}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:t}),i=this._index.get(`${t}${Ri}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:t,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:t,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:t,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},jf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e});return this.store.has(`${i}${Ri}${e}`)?(this.store.delete(`${i}${Ri}${e}`),!0):!1}async get({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e});return this.store.get(`${i}${Ri}${e}`)}async list({agent:e,tenant:t}){let n=await Md({tenant:t,agent:e}),i=[];for(let[a,o]of this.store.entries())a.startsWith(`${n}${Ri}`)&&i.push(o);return i}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a,updateExisting:o}){let s=await Md({agent:i,tenant:n,didUri:e});if(o){if(!this.store.has(`${s}${Ri}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${s}${Ri}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=structuredClone(t);this.store.set(`${s}${Ri}${e}`,c)}};var hg=class extends Of{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=HE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(Ph(s)){let c=`${n}${Ri}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},mg=class extends jf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};var jye=(t=>(t.Create="Create",t.Resolve="Resolve",t))(jye||{});function QG(r,e){return r.messageType===e}var Dh=class extends tg{constructor({agent:t,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Bf({agent:t,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=t,this._store=a??new mg;for(let o of n)this._didMethods.set(o.methodName,o)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(t){this._agent=t,"agent"in this.cache&&(this.cache.agent=t)}async create({method:t,tenant:n,options:i,store:a}){let s=await this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(await this.cache.set(s.uri,{didDocument:s.document,didResolutionMetadata:{},didDocumentMetadata:s.metadata}),a??!0){let{uri:c,document:l,metadata:d}=s,u={uri:c,document:l,metadata:d};await this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return s}async export({didUri:t,tenant:n}){let i=await this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return await i.export()}async get({didUri:t,tenant:n}){let i=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?await Ss.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:t,methodId:n}){let i=Jn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let a=this.getMethod(i.method),{didDocument:o,didResolutionMetadata:s}=await this.resolve(t);if(!o)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(s)}`);return await a.getSigningMethod({didDocument:o,methodId:n})}async update({tenant:t,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:t??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(Xw(n.document)===Xw(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let o=await Ss.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:s,document:c,metadata:l}=o,d={uri:s,document:c,metadata:l};if(await this.cache.set(s,{didDocument:c,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:s,data:d,agent:this.agent,tenant:t??s,updateExisting:!0,useCache:!0}),i){let u=Jn.parse(s);u&&u.method==="dht"&&await vo.publish({did:o})}return o}async import({portableDid:t,tenant:n}){let i=await Ss.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:a,document:o,metadata:s}=i,c={uri:a,document:o,metadata:s};return await this.cache.set(a,{didDocument:o,didResolutionMetadata:{},didDocumentMetadata:s}),await this._store.set({id:c.uri,data:c,agent:this.agent,tenant:n??c.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:t,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(t),await this._store.delete({id:t,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});await this.agent.keyManager.deleteKey({keyUri:i})}}async processRequest(t){if(QG(t,"Create"))try{let n=await this.create({...t.messageParams});return{result:{uri:n.uri,document:n.document,metadata:n.metadata},ok:!0,status:{code:201,message:"Created"}}}catch(n){return{ok:!1,status:{code:500,message:n.message??"Unknown error occurred"}}}if(QG(t,"Resolve")){let{didUri:n,options:i}=t.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${t.messageType}`)}getMethod(t){let n=this._didMethods.get(t);if(n===void 0)throw new Error(`DID Method not supported: ${t}`);return n}};g();Xn();Sr();Pn();ea();g();Xn();Sr();var _s=class r{constructor({agent:e}={}){this._cachedPermissions=new xi.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:t,delegate:n,messageType:i,protocol:a,cached:o=!1}){let s=[e,t,i,a].join("~"),c=o?this._cachedPermissions.get(s):void 0;if(c)return c;let l=await this.fetchGrants({author:t,target:t,grantor:e,grantee:t}),d=await r.matchGrantFromArray(e,t,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(s,d),d}async fetchGrants({author:e,target:t,grantee:n,grantor:i,protocol:a,remote:o=!1,checkRevoked:s=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:rt.uri,protocolPath:rt.grantPath,tags:c}}},{reply:d}=o?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=s?await this.fetchRevokedGrantIds({author:e,target:t,grantor:i,remote:o,tags:c}):new Set,f=[];for(let p of d.entries){if(u.has(p.recordId))continue;let h=Ir.parse(p);f.push({grant:h,message:p})}return f}async fetchRevokedGrantIds({author:e,target:t,grantor:n,remote:i,tags:a}){let o={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:rt.uri,protocolPath:rt.revocationPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${s.status.detail}`);let c=new Set;for(let l of s.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:t,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,o={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:rt.uri,protocolPath:rt.requestPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${s.status.detail}`);let c=[];for(let l of s.entries){let d=md.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:t,grantRecordId:n,remote:i=!1}){let a={author:e,target:t,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:rt.uri,protocolPath:rt.revocationPath}}},{reply:o}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)}async createGrant(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,o;rt.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope};a.delegateKeyDelivery&&(s.delegateKeyDelivery=a.delegateKeyDelivery);let c=he.object(s).toUint8Array(),l={recipient:a.grantedTo,protocol:rt.uri,protocolPath:rt.grantPath,dataFormat:"application/json",tags:o},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,o;rt.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),l={protocol:rt.uri,protocolPath:rt.requestPath,dataFormat:"application/json",tags:o},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{request:md.parse(f),message:f}}async createRevocation(e){let{author:t,store:n=!1,grant:i,description:a}=e,o={description:a},s=he.object(o).toUint8Array(),c;rt.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:rt.uri,protocolPath:rt.revocationPath,dataFormat:"application/json",tags:c};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([s])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:he.uint8Array(s).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,t,n,i,a=!1){let o;for(let s of i){let{grant:c,message:l}=s;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:p}=n;if(this.matchScopeFromGrant(e,t,d,c,u,f,p)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};o||(o={grant:c,message:l})}}return o}static matchScopeFromGrant(e,t,n,i,a,o,s){if(i.grantee!==t||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(O6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===o||u.contextId!==void 0&&s?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var Mye="@enbox/dwn-server";function ZE(r){return r.endsWith("/")?r.slice(0,-1):r}var Rh=class{constructor(e,t=1e4,n){this._rpcClient=e;this._cacheTtlMs=t;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=await this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let t=ZE(e),n=await this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}async _tryDiscoveryFile(){if(this._discoveryFile)try{let e=await this._discoveryFile.read();return e&&await this._validateEndpoint(e.endpoint)?e.endpoint:void 0}catch{return}}async _validateEndpoint(e){try{return(await this._rpcClient.getServerInfo(e)).server===Mye}catch{return!1}}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};function Kye(){try{let r=mS,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(t.dirname(i),{recursive:!0}),await e.writeFile(i,a,{encoding:"utf-8",mode:384})},async removeFile(i){try{await e.unlink(i)}catch{}},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var Nye=".enbox",Uye="dwn.json",YE=class{constructor(e,t){let n=e??Kye();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,t)this._filePath=t;else{let a=mS("node:path");this._filePath=a.join(n.homedir(),Nye,Uye)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!Lye(t)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:ZE(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n}async write(e){let t={endpoint:ZE(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function Lye(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||e.capabilities!==void 0&&(!Array.isArray(e.capabilities)||!e.capabilities.every(t=>typeof t=="string")))}g();Xn();function Fa(r,e){return r.messageType===e}function qye(r,e){return e.descriptor.interface+e.descriptor.method===r}function O6(r){return r===Re.RecordsDelete||r===Re.RecordsQuery||r===Re.RecordsRead||r===Re.RecordsSubscribe||r===Re.RecordsWrite}function Ch(r){return r.interface===ve.Records}function zye(r){return r.interface===ve.Messages}g();Xn();Pn();function XE(r){return r===di.XC20P?24:12}function $h(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}async function QE(r,e,t,n=di.A256GCM){let{ciphertextStream:i,tag:a}=await Ei.aeadEncryptStream(n,e,t,Wt.fromBytes(r)),o=await Wt.toBytes(i),s=Wt.fromBytes(o),c=await mr.computeDagPbCidFromStream(s);return{encryptedBytes:o,dataCid:c,dataSize:o.length,authenticationTag:a}}async function na(r,e){let{didDocument:t,didResolutionMetadata:n}=await r.did.resolve(e);if(!t)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=t.keyAgreement;if(!i||i.length===0)throw new Error(`AgentDwnApi: DID '${e}' does not have a keyAgreement verification method. Create the identity with an X25519 key with keyAgreement purpose to use protocol encryption.`);let a=i[0],o;if(typeof a=="string"){let l=a.includes("#")?a.split("#").pop():a;o=t.verificationMethod?.find(d=>d.id.endsWith(`#${l}`))}else o=a;if(!o?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let s=o.publicKeyJwk;if(s.crv==="Ed25519")s=await Un.convertPublicKeyToX25519({publicKey:s});else if(s.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${s.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let c=await r.keyManager.getKeyUri({key:s});return{keyId:o.id,keyUri:c,publicKeyJwk:s}}async function tH(r,e,t,n,i){let{keyId:a,keyUri:o}=await na(r,e),s=Ie.constructKeyDerivationPathUsingProtocolContextScheme(t),c=await r.keyManager.derivePublicKey({keyUri:o,derivationPath:s});return{encryptionInput:$h(n,i,a,c,Pt.ProtocolContext),keyId:a,keyUri:o,contextDerivationPath:s}}function rH(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,o)=>i.jweKeyUnwrap({keyUri:t,derivationPath:a,encryptedKey:o.encryptedKey,ephemeralPublicKey:o.ephemeralPublicKey})}}async function xb(r,e){let{keyId:t,keyUri:n}=await na(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:Pt.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function j6(r,e){let{keyId:t,keyUri:n}=await na(r,e);return rH(r,t,n,Pt.ProtocolPath)}function Pb(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=await Ie.derivePrivateKey(r,e),i=await At.bytesToPrivateKey({privateKeyBytes:n});return Ei.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)}}}function Fye(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=r.derivationPath??[];if(n.length!==e.length||!n.every((o,s)=>o===e[s]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${n.join(", ")}], record path: [${e.join(", ")}].`);let i=await Ie.derivePrivateKey(r,e),a=await At.bytesToPrivateKey({privateKeyBytes:i});return Ei.ecdhEsUnwrapKey(a,t.ephemeralPublicKey,t.encryptedKey)}}}async function eH(r,e,t,n,i,a,o,s,c){let{encryption:l}=t;if(!l?.recipients.some(x=>x.header.derivationScheme===Pt.ProtocolContext)||!t.contextId){if(o&&s){let x=t.descriptor.protocol,_=t.descriptor.protocolPath;if(x){let A=`ddk~${s}`,D=o.get(A);if(D){let N=D.filter(z=>z.protocol===x);if(_){let z=N.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===_);if(z)return Fye(z.derivedPrivateKey)}let $=N.find(z=>z.scope.kind==="protocol");if($)return Pb($.derivedPrivateKey)}}}return j6(r,e)}let u=l.recipients.find(x=>x.header.derivationScheme===Pt.ProtocolContext),f=t.contextId.split("/")[0];if(c&&s){let x=t.descriptor.protocol;if(x){let _=`dctx~${s}~${x}~${f}`,A=c.get(_);if(A)return Pb(A);try{let D=await a({ownerDid:e,requesterDid:s,sourceProtocol:x,sourceContextId:f});if(D)return c.set(_,D),Pb(D)}catch{}}throw new Error(`AgentDwnApi: Delegate '${s}' does not have a context key for context '${f}'. No delivered contextKey record was found via the key-delivery protocol. The delegate may need to reconnect or wait for sync.`)}let{keyId:p,keyUri:h}=await na(r,e);if(u.header.kid===p)return rH(r,p,h,Pt.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return Pb(y);let v=t.descriptor.protocol,w=await a({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:x}=await Promise.resolve().then(()=>(Xn(),GG)),_=n??x.getSignerDid(t.authorization.signature.signatures[0]);w=await a({ownerDid:_,requesterDid:e,sourceProtocol:v,sourceContextId:f})}if(!w)throw new Error(`AgentDwnApi: Failed to decrypt record '${t.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(m,w),Pb(w)}async function nH(r,e,t,n,i,a,o){if(!(!("encryption"in r)||!r.encryption)){if(Fa(r,Re.RecordsRead)){let s=e;if(s.status.code===200&&s.entry?.recordsWrite?.encryption&&s.entry?.data){let c=await eH(t,r.author,s.entry.recordsWrite,r.target,n,i,a,r.granteeDid,o);try{s.entry.data=await Ie.decrypt(s.entry.recordsWrite,c,s.entry.data)}catch(l){throw new Error(`AgentDwnApi: Failed to decrypt record '${s.entry.recordsWrite.recordId}'. Original error: ${l.message}`)}}}if(Fa(r,Re.RecordsQuery)){let s=e;if(s.status.code===200&&s.entries){for(let c of s.entries)if(c.encryption&&c.encodedData){let l=await eH(t,r.author,c,r.target,n,i,a,r.granteeDid,o);try{let d=De.base64UrlToBytes(c.encodedData),u=Wt.fromBytes(d),f=await Ie.decrypt(c,l,u),p=await Wt.toBytes(f);c.encodedData=De.bytesToBase64Url(p)}catch(d){throw new Error(`AgentDwnApi: Failed to decrypt record '${c.recordId}'. Original error: ${d.message}`)}}}}}}g();Xn();async function iH(r,e,t,n,i,a){if(i.get(e))return;let o=za.protocol;if(!await n(e,o)){let c=await xb(r,e),l=await xd.deriveAndInjectPublicEncryptionKeys(za,c),{reply:{status:d}}=await t({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:l}});if(d.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${d.code} - ${d.detail}`);a.delete(`${e}~${o}`)}i.set(e,!0)}async function sH(r,e,t,n,i){let{tenantDid:a,recipientDid:o,contextKeyData:s,sourceProtocol:c,sourceContextId:l,recipientKeyDeliveryPublicKey:d}=e;await n(a);let u=za.protocol,f=new TextEncoder().encode(JSON.stringify(s)),p={protocol:u,protocolPath:"contextKey",dataFormat:"application/json",recipient:o,tags:{protocol:c,contextId:l}},h,m;if(d){let y=di.A256GCM,v=crypto.getRandomValues(new Uint8Array(32)),w=crypto.getRandomValues(new Uint8Array(XE(y))),{encryptedBytes:x,dataCid:_,dataSize:A,authenticationTag:D}=await QE(f,v,w,y),N={...$h(v,w,d.rootKeyId,d.publicKeyJwk,Pt.ProtocolPath),authenticationTag:D};({message:h,reply:{status:m}}=await t({author:a,target:a,messageType:Re.RecordsWrite,messageParams:{...p,dataCid:_,dataSize:A,encryptionInput:N},dataStream:new Blob([x])}))}else({message:h,reply:{status:m}}=await t({author:a,target:a,messageType:Re.RecordsWrite,messageParams:p,dataStream:new Blob([f],{type:"application/json"}),encryption:!0}));if(!(h&&m.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${o}: ${m.code} - ${m.detail}`);return i(a,h).catch(y=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${h.recordId}' to remote DWN failed: ${y.message}. Sync will deliver it later.`)}),h.recordId}async function oH(r,e,t,n,i,a){let o;try{o=await a(e)}catch{return}if(o.length===0)return;let{data:s}=await n({author:e,messageType:Re.RecordsWrite,messageCid:await ye.getCid(t)});await i({targetDid:e,dwnEndpointUrls:o,message:t,data:s})}async function Gye(r,e,t,n,i){try{let{reply:a}=await r({author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!a.entries?.length)return;let o=a.entries[0].recordId,{reply:s}=await r({author:e,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:o}},encryption:!0}),c=s;return c.entry?.data?i(await Wt.toBytes(c.entry.data)):void 0}catch{return}}async function aH(r,e,t){let{ownerDid:n,requesterDid:i,sourceProtocol:a,sourceContextId:o}=e,s=za.protocol,c=n===i,l={protocol:s,protocolPath:"contextKey",recipient:i,tags:{protocol:a,contextId:o}},d=u=>JSON.parse(new TextDecoder().decode(u));if(c){let{reply:u}=await t({author:i,target:n,messageType:Re.RecordsQuery,messageParams:{filter:l}});if(u.status.code!==200||!u.entries?.length)return;let f=u.entries[0].recordId,{reply:p}=await t({author:i,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:f}},encryption:!0}),h=p;return h.entry?.data?d(await Wt.toBytes(h.entry.data)):void 0}return Gye(t,i,n,l,d)}g();Xn();async function cH(r,e,t,n,i,a,o){let s=`${r}~${e}`,c=i.get(s);if(c)return c;let d=await n(a??r),u=await Ah[Re.ProtocolsQuery].create({filter:{protocol:e},signer:d,...o?{permissionGrantId:o}:{}}),f=await t.processMessage(r,u.message);if(f.status.code!==200||!f.entries?.length)return;let p=f.entries[0].descriptor.definition;return i.set(s,p),p}async function dH(r,e,t,n,i){let a=`remote~${r}~${e}`,o=i.get(a);if(o)return o;let s=await Ah[Re.ProtocolsQuery].create({filter:{protocol:e}}),c=await n({targetDid:r,dwnEndpointUrls:await t(r),message:s.message});if(c.status.code!==200||!c.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let l=c.entries[0].descriptor.definition;return i.set(a,l),l}async function lH(r,e,t,n,i,a,o){let s=await a(n),c=await Ah[Re.RecordsQuery].create({signer:s,filter:{protocol:e,contextId:t}}),l=await i(r),d=await o({targetDid:r,dwnEndpointUrls:l,message:c.message});if(!(d.status.code!==200||!d.entries?.length)){for(let u of d.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(p=>p.header.derivationScheme===Pt.ProtocolContext&&p.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Vl=class r{constructor(e){this._protocolDefinitionCache=new xi.default({ttl:30*60*1e3});this._contextKeyCache=new xi.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new xi.default({ttl:30*60*1e3});this._delegateDecryptionKeyCache=new xi.default({ttl:24*60*60*1e3});this._delegateContextKeyCache=new xi.default({ttl:24*60*60*1e3});this._delegateContextKeyCacheIndex=new Map;this._delegateMultiPartyProtocols=new Map;this._localManagedDidCache=new xi.default({ttl:30*60*1e3});this._keyDeliveryProtocolInstalledCache=new xi.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:t,localDwnStrategy:n="prefer"}=e;this._agent=t,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,t&&(this._localDwnDiscovery=new Rh(t.rpc,1e4,r._tryCreateDiscoveryFile()))}get isRemoteMode(){return this._dwn===void 0}get agent(){if(this._agent===void 0)throw new Error("AgentDwnApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._localDwnDiscovery=new Rh(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new Rh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return dg(e,this.agent.did);let n=await this.getLocalDwnEndpoint();if(this._localDwnStrategy==="only"){if(!n)throw new Error("AgentDwnApi: Local DWN strategy is 'only' but no local DWN endpoint was discovered. Ensure the local DWN server is running and discoverable via the discovery file (~/.enbox/dwn.json) or dwn://connect.");return[n]}let i=[];try{i=await dg(e,this.agent.did)}catch(o){if(!n)throw o}return n?[...new Set([n,...i])]:i}async getRemoteDwnEndpointUrls(e){return dg(e,this.agent.did)}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new Rh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new YE}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let t=this._localManagedDidCache.get(e);if(t!==void 0)return t;if(e===this.agent.agentDid.uri)return this._localManagedDidCache.set(e,!0),!0;let n=await this.agent.identity.list(),i=new Set;for(let o of n)i.add(o.did.uri),o.metadata.connectedDid&&i.add(o.metadata.connectedDid);for(let o of i)this._localManagedDidCache.set(o,!0);let a=i.has(e);return a||this._localManagedDidCache.set(e,!1),a}get node(){if(!this._dwn)throw new Error(`AgentDwnApi: The in-process DWN instance is not available. The agent is operating in remote mode (local DWN server at '${this._localDwnEndpoint}'). Use processRequest() instead of accessing the DWN node directly.`);return this._dwn}static async createDwn({dataPath:e,dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:o,tenantGate:s,resumableTaskStore:c}){return t??=new If({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new tg({didResolvers:[vo,bo],cache:new hE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new $f({location:`${e}/DWN_STATEINDEX`}),o??=new Df({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),c??=new Rf({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Cf,await rg.create({dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:o,tenantGate:s,resumableTaskStore:c})}async processRequest(e){let{message:t,dataStream:n}=await this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,a;if(e.store===!1)a={status:{code:202,detail:"Accepted"}};else if(this._dwn)a=await this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let o;if(n){let s=await Wt.toBytes(n);o=new Blob([s])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:o,subscriptionHandler:i})}return await this.postWriteKeyDelivery(e,t,a),await this.maybeDecryptReply(e,a),{reply:a,message:t,messageCid:await ye.getCid(t)}}async processRawMessage(e,t,n){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await Wt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})}async sendRequest(e){let t=await this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,a,o;if("messageCid"in e)({message:i,data:a}=await this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=await this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");a=e.dataStream,o=e.subscriptionHandler}let s;o!==void 0&&!("messageCid"in e)&&(s=async l=>{let d=l!==void 0?{...e.messageParams,cursor:l}:e.messageParams,u={...e,messageParams:d},{message:f}=await this.constructDwnMessage({request:u});return f});let c=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:a,subscriptionHandler:o,resubscribeFactory:s});return await this.maybeDecryptReply(e,c),n??=await ye.getCid(i),{reply:c,message:i,messageCid:n}}async postWriteKeyDelivery(e,t,n){if(!Fa(e,Re.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==za.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let o=t,s=ut.getSignerDid(o.authorization.signature.signatures[0]),c=s!==e.target,l=!i.parentContextId,d=i.protocolPath.split("/")[0],u=Th(a,d),f=$6({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:c?s:void 0}),p=o.contextId?.split("/")[0]||o.contextId||o.recordId,h=u&&l&&!c&&this.hasEligibleDelegatesForProtocol(i.protocol);if(f.size>0||h){let{keyId:m,keyUri:y}=await na(this.agent,e.target),v=[Pt.ProtocolContext,p],w=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:y,derivationPath:v}),x=await At.bytesToPrivateKey({privateKeyBytes:w}),_={rootKeyId:m,derivationScheme:Pt.ProtocolContext,derivationPath:v,derivedPrivateKey:x};if(f.size>0){let A=o.authorization?.authorKeyDeliveryPublicKey;for(let D of f)try{let N=D===s&&A?A:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:D,contextKeyData:_,sourceProtocol:i.protocol,sourceContextId:p,recipientKeyDeliveryPublicKey:N})}catch(N){console.warn(`AgentDwnApi: Key delivery to '${D}' for context '${p}' failed: ${N.message}. The participant may not be able to decrypt records in this context.`)}}h&&this.deliverContextKeyToDelegates(i.protocol,p,_)}if(u&&l&&!c){let{keyId:m,keyUri:y}=await na(this.agent,e.target),v=[Pt.ProtocolContext,p],w=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:y,derivationPath:v}),x=await At.bytesToPrivateKey({privateKeyBytes:w}),_={rootKeyId:m,derivationScheme:Pt.ProtocolContext,derivationPath:v,derivedPrivateKey:x};await this.deliverContextKeyToDelegatesViaDwn(e.target,i.protocol,p,_)}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:t,message:n,data:i,subscriptionHandler:a,resubscribeFactory:o}){let s=[];if(n.descriptor.method===me.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let c of t)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(c)).webSocketSupport){s.push({url:c,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(c);u.protocol=u.protocol==="http:"?"ws:":"wss:",c=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:c,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:o}:void 0})}catch(l){s.push({url:c,message:l instanceof Error?l.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(s)}`)}async constructDwnMessage({request:e}){if(e.granteeDid&&!this.hasGrantParams(e.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let t=e.rawMessage,n;if(Fa(e,Re.RecordsWrite)){let s=e.messageParams;if(e.dataStream&&!s?.data){let{dataStream:c}=e,l;if(c instanceof Blob){let[d,u]=c.stream().tee();l=d,n=u}else if(c instanceof ReadableStream){let[d,u]=c.tee();l=d,n=u}!t&&s&&(s.dataCid=await mr.computeDagPbCidFromStream(l),s.dataSize===void 0&&c instanceof Blob&&(s.dataSize=c.size))}}if(Fa(e,Re.ProtocolsConfigure)&&e.encryption&&!t){let s=e.messageParams,c=await xb(this.agent,e.author);s.definition=await xd.deriveAndInjectPublicEncryptionKeys(s.definition,c),this._protocolDefinitionCache.delete(`${e.target}~${s.definition.protocol}`)}if(Fa(e,Re.ProtocolsConfigure)&&!e.encryption&&!t){let s=e.messageParams?.definition;s?.protocol&&this._protocolDefinitionCache.set(`${e.target}~${s.protocol}`,s)}let i;if(Fa(e,Re.RecordsWrite)&&e.encryption&&!t){let s=e.messageParams;if(s?.protocol&&s.protocolPath){let c=e.target!==e.author,l;if(c?l=await this.fetchRemoteProtocolDefinition(e.target,s.protocol):l=await this.getProtocolDefinition(e.target,s.protocol,e.granteeDid),!l)throw new Error(`AgentDwnApi: Protocol '${s.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let d=s.protocolPath.split("/"),u=l.structure;for(let L of d)u=u[L];if(!u?.$encryption)throw new Error(`AgentDwnApi: Protocol '${s.protocol}' at path '${s.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let f=s.protocolPath.split("/")[0],h=s.protocol===za.protocol?!1:Th(l,f),m=!s.parentContextId,y;if(s.data)y=s.data instanceof Uint8Array?s.data:new TextEncoder().encode(String(s.data));else if(e.dataStream instanceof Blob)y=new Uint8Array(await e.dataStream.arrayBuffer());else if(e.dataStream instanceof ReadableStream)y=await Wt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let v=di.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),x=crypto.getRandomValues(new Uint8Array(XE(v))),_,A=()=>$h(w,x,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,Pt.ProtocolPath);if(c&&h&&m)_=A();else if(c&&h&&!m){let L=s.parentContextId.split("/")[0]||s.parentContextId,j=await this.extractDerivedPublicKey(e.target,s.protocol,L,e.author);j?_=$h(w,x,j.rootKeyId,j.derivedPublicKey,Pt.ProtocolContext):_=A()}else if(c)_=A();else if(h&&!m){let L=s.parentContextId.split("/")[0]||s.parentContextId,j=this._contextKeyCache.get(L);if(!j){let{keyId:Y,keyUri:R}=await na(this.agent,e.author),C=Ie.constructKeyDerivationPathUsingProtocolContextScheme(L);j={keyId:Y,keyUri:R,contextDerivationPath:C},this._contextKeyCache.set(L,j)}let H=await this.agent.keyManager.derivePublicKey({keyUri:j.keyUri,derivationPath:j.contextDerivationPath});_=$h(w,x,j.keyId,H,Pt.ProtocolContext)}else h&&m?_=void 0:_=A();let{encryptedBytes:D,dataCid:N,dataSize:$,authenticationTag:z}=await QE(y,w,x,v);if(s.dataCid=N,s.dataSize=$,delete s.data,n=Wt.fromBytes(D),e.dataStream=void 0,_?(_.authenticationTag=z,s.encryptionInput=_):i={dataEncryptionKey:w,dataEncryptionIV:x,encryptedBytes:D,authenticationTag:z},c&&h){let{keyId:L,keyUri:j}=await na(this.agent,e.author),H=[Pt.ProtocolPath,za.protocol,"contextKey"],Y=await this.agent.keyManager.derivePublicKey({keyUri:j,derivationPath:H});s.authorKeyDeliveryPublicKey={rootKeyId:L,publicKeyJwk:Y}}}}let a,o=Ah[e.messageType];if(t){if(a=await o.parse(t),jd(a)&&e.signAsOwner){let s=await this.getSigner(e.author);await a.signAsOwner(s)}else if(e.granteeDid&&jd(a)&&e.signAsOwnerDelegate){let s=await this.getSigner(e.granteeDid),c=e.messageParams;await a.signAsOwnerDelegate(s,c.delegatedGrant)}}else{if(e.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let s=e.granteeDid?await this.getSigner(e.granteeDid):await this.getSigner(e.author),c={...e.messageParams};if(e.granteeDid&&c.permissionGrantId&&!c.delegatedGrant&&Fa(e,Re.RecordsWrite)){let{reply:l}=await this.processRequest({author:e.granteeDid,target:e.author,messageType:Re.RecordsRead,messageParams:{filter:{recordId:c.permissionGrantId}}});if(l.status.code===200&&l.entry?.recordsWrite&&l.entry?.data){let d=await Wt.toBytes(l.entry.data);c.delegatedGrant={...l.entry.recordsWrite,encodedData:he.uint8Array(d).toBase64Url()}}}if(a=await o.create({...c,signer:s}),i&&Fa(e,Re.RecordsWrite)){let l=a,d=l.message.recordId,{encryptionInput:u,keyId:f,keyUri:p,contextDerivationPath:h}=await tH(this.agent,e.author,d,i.dataEncryptionKey,i.dataEncryptionIV),m={...u,authenticationTag:i.authenticationTag};await l.encryptSymmetricEncryptionKey(m),await l.sign({signer:s}),this._contextKeyCache.set(d,{keyId:f,keyUri:p,contextDerivationPath:h})}}return{message:a.message,dataStream:n}}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}async getSigner(e){if(e===this.agent.agentDid.uri){let t=await this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:async n=>await t.sign({data:n})}}else try{let t=await this.agent.did.get({didUri:e});if(t){let s=await t.getSigner();return{algorithm:s.algorithm,keyId:s.keyId,sign:async c=>await s.sign({data:c})}}let n=await this.agent.did.getSigningMethod({didUri:e});if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.agent.keyManager.getPublicKey({keyUri:i}),o=this.agent.keyManager;return{algorithm:bn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async s=>await o.sign({data:s,keyUri:i})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}}async getEncryptionKeyDeriver(e){return xb(this.agent,e)}async getEncryptionKeyInfo(e){return na(this.agent,e)}async getKeyDecrypter(e){return j6(this.agent,e)}detectNewParticipants(e){return $6(e)}async getProtocolDefinition(e,t,n){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,t)}catch(a){let o=a instanceof Error?a.message:"";if(o.includes("not found")||o.includes("404")||o.includes("No protocol"))return;throw a}let i;if(n)try{let a=new _s({agent:this.agent}),{grant:o}=await a.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:Re.ProtocolsQuery});i=o.id}catch{}return cH(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)}async fetchRemoteProtocolDefinition(e,t){return dH(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,t,n,i){return lH(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,t){return nH(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)}async getDwnMessage({author:e,messageCid:t}){let n=await this.getSigner(e),i=await Ah[Re.MessagesRead].create({messageCid:t,signer:n}),a;if(this._dwn?a=await this._dwn.processMessage(e,i.message):a=await this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:i.message}),a.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${a.status.code} - ${a.status.detail}`);let o=a.entry,c={message:o.message};if(jd(o)){let l=o.data;if(l){let d=await Wt.toBytes(l);c.data=new Blob([d],{type:o.message.descriptor.dataFormat})}}return c}async ensureKeyDeliveryProtocol(e){return iH(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}set onDelegateContextKeysChanged(e){this._onDelegateContextKeysChanged=e}importDelegateDecryptionKeys(e,t){let n=`ddk~${e}`;this._delegateDecryptionKeyCache.set(n,t)}importDelegateContextKeys(e,t,n){let i=this._delegateContextKeyCacheIndex.get(e);if(i)for(let s of i)this._delegateContextKeyCache.delete(s);let a=[];for(let s of t){let c=`dctx~${e}~${s.protocol}~${s.contextId}`;this._delegateContextKeyCache.set(c,s.derivedPrivateKey),a.push(c)}this._delegateContextKeyCacheIndex.set(e,a);let o=new Set(n??[]);for(let s of t)o.add(s.protocol);o.size>0?this._delegateMultiPartyProtocols.set(e,o):this._delegateMultiPartyProtocols.delete(e)}clearDelegateDecryptionKeys(e){if(e){this._delegateDecryptionKeyCache.delete(`ddk~${e}`);let t=this._delegateContextKeyCacheIndex.get(e);if(t){for(let n of t)this._delegateContextKeyCache.delete(n);this._delegateContextKeyCacheIndex.delete(e)}this._delegateMultiPartyProtocols.delete(e)}else this._delegateDecryptionKeyCache.clear(),this._delegateContextKeyCache.clear(),this._delegateContextKeyCacheIndex.clear(),this._delegateMultiPartyProtocols.clear()}exportDelegateContextKeys(e){let t=this._delegateContextKeyCacheIndex.get(e);if(!t)return[];let n=[],i=`dctx~${e}~`;for(let a of t){let o=this._delegateContextKeyCache.get(a);if(!o||!a.startsWith(i))continue;let s=a.slice(i.length),c=s.lastIndexOf("~");c!==-1&&n.push({protocol:s.slice(0,c),contextId:s.slice(c+1),derivedPrivateKey:o})}return n}exportDelegateMultiPartyProtocols(e){let t=this._delegateMultiPartyProtocols.get(e);return t?[...t]:[]}hasEligibleDelegatesForProtocol(e){for(let[,t]of this._delegateMultiPartyProtocols)if(t.has(e))return!0;return!1}deliverContextKeyToDelegates(e,t,n){for(let[i,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let o=`dctx~${i}~${e}~${t}`;if(this._delegateContextKeyCache.get(o))continue;this._delegateContextKeyCache.set(o,n);let s=this._delegateContextKeyCacheIndex.get(i)??[];s.push(o),this._delegateContextKeyCacheIndex.set(i,s),this._onDelegateContextKeysChanged?.(i)}}async deliverContextKeyToDelegatesViaDwn(e,t,n,i){try{let o=await new _s({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),s=new Set(["Read","Query","Subscribe"]),c=Date.now(),l=new Set;for(let d of o){if(!d.grant.delegated||new Date(d.grant.dateExpires).getTime()<=c)continue;let u=d.grant.scope;if(u.interface!=="Records"||!s.has(u.method)||u.protocolPath||u.contextId)continue;let f=d.grant.grantee,p=d.grant.delegateKeyDelivery;if(!p?.rootKeyId||!p?.publicKeyJwk||l.has(f))continue;let h=p.publicKeyJwk;try{await this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:p.rootKeyId,publicKeyJwk:h}}),l.add(f)}catch(m){console.warn(`AgentDwnApi: Cross-device key delivery to delegate '${f}' for context '${n}' failed: ${m.message}. The delegate may need to reconnect.`)}}}catch(a){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${a.message}`)}}async writeContextKeyRecord(e){return sH(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this))}async eagerSendContextKeyRecord(e,t){return oH(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return aH(this.agent,e,this.processRequest.bind(this))}};g();var fH="dwn",pH="connect";function LVe(r){return`${fH}://${pH}?callback=${encodeURIComponent(r)}`}function Hye(r){let e=JSON.stringify(r);return Jye(e)}function uH(r){try{let e=Zye(r),t=JSON.parse(e);return Vye(t)?t:void 0}catch{return}}function qVe(r){try{let e=`${fH}://`;if(!r.startsWith(e))return;let t=r.slice(e.length),n=t.indexOf("?");if(n===-1||t.slice(0,n)!==pH)return;let a=t.slice(n+1),s=new URLSearchParams(a).get("callback");return!s||s.length===0?void 0:{callback:s}}catch{return}}function zVe(r,e){let t=Hye(e);return`${r.split("#")[0]}#${t}`}function FVe(r){let e=r.indexOf("#");if(e===-1)return uH(r);let t=r.slice(e+1);if(t.length!==0)return uH(t)}function Vye(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Wye(e.endpoint))}function Wye(r){try{let t=new URL(r).hostname.toLowerCase();return!!(t==="127.0.0.1"||t==="::1"||t==="[::1]"||t==="localhost"||t.endsWith(".localhost"))}catch{return!1}}function Jye(r){let e=new TextEncoder().encode(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Zye(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4;t===2?e+="==":t===3&&(e+="=");let n=atob(e),i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new TextDecoder().decode(i)}g();g();pP();Yb();g();n1();Ja();var Yye=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),mH=Uint8Array.from({length:16},(r,e)=>e),Xye=mH.map(r=>(9*r+5)%16),K6=[mH],N6=[Xye];for(let r=0;r<4;r++)for(let e of[K6,N6])e.push(e[r].map(t=>Yye[t]));var yH=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(r=>new Uint8Array(r)),Qye=K6.map((r,e)=>r.map(t=>yH[e][t])),ege=N6.map((r,e)=>r.map(t=>yH[e][t])),tge=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),rge=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),eS=(r,e)=>r<<e|r>>>32-e;function hH(r,e,t,n){return r===0?e^t^n:r===1?e&t|~e&n:r===2?(e|~t)^n:r===3?e&n|t&~n:e^(t|~n)}var tS=new Uint32Array(16),M6=class extends ru{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:n,h3:i,h4:a}=this;return[e,t,n,i,a]}set(e,t,n,i,a){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,t){for(let p=0;p<16;p++,t+=4)tS[p]=e.getUint32(t,!0);let n=this.h0|0,i=n,a=this.h1|0,o=a,s=this.h2|0,c=s,l=this.h3|0,d=l,u=this.h4|0,f=u;for(let p=0;p<5;p++){let h=4-p,m=tge[p],y=rge[p],v=K6[p],w=N6[p],x=Qye[p],_=ege[p];for(let A=0;A<16;A++){let D=eS(n+hH(p,a,s,l)+tS[v[A]]+m,x[A])+u|0;n=u,u=l,l=eS(s,10)|0,s=a,a=D}for(let A=0;A<16;A++){let D=eS(i+hH(h,o,c,d)+tS[w[A]]+y,_[A])+f|0;i=f,f=d,d=eS(c,10)|0,c=o,o=D}}this.set(this.h1+s+d|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+o|0,this.h0+a+c|0)}roundClean(){tS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},gH=rm(()=>new M6);Yg();lP();Ja();em();var nge=Wg("ed25519 seed"),U6=2147483648,wH=new Uint8Array([0]);function vH(r,...e){return typeof r=="string"&&(r=I$(r)),zd(r,...e),r}var ige=r=>gH(su(r)),sge=r=>Gd(r).getUint32(0,!1),L6=r=>{if(!Number.isSafeInteger(r)||r<0||r>2**32-1)throw new Error(`Invalid number=${r}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Gd(e).setUint32(0,r,!1),e},rS=class r{get publicKeyRaw(){return ma.getPublicKey(this.privateKey)}get publicKey(){return Hf(wH,this.publicKeyRaw)}get pubHash(){return ige(this.publicKey)}get fingerprint(){return sge(this.pubHash)}get fingerprintHex(){return GS(L6(this.fingerprint))}get parentFingerprintHex(){return GS(L6(this.parentFingerprint))}static fromMasterSeed(e){if(e=vH(e),8*e.length<128||8*e.length>512)throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);let t=eu(Tu,nge,e);return new r({privateKey:t.slice(0,32),chainCode:t.slice(32)})}constructor(e){if(this.depth=0,this.index=0,this.parentFingerprint=0,!e||typeof e!="object")throw new Error("HDKey.constructor must not be called directly");if(zd(e.privateKey,32),zd(e.chainCode,32),this.depth=e.depth||0,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");this.chainCode=e.chainCode,this.privateKey=e.privateKey}derive(e,t=!1){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;let n=e.replace(/^[mM]'?\//,"").split("/"),i=this;for(let a of n){let o=/^(\d+)('?)$/.exec(a);if(!o||o.length!==3)throw new Error(`Invalid child index: ${a}`);let s=+o[1];if(!Number.isSafeInteger(s)||s>=U6)throw new Error("Invalid index");(t||o[2]==="'")&&(s+=U6),i=i.deriveChild(s)}return i}deriveChild(e){if(e<U6)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Hf(wH,this.privateKey,L6(e)),n=eu(Tu,this.chainCode,t);return new r({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return ma.sign(e,this.privateKey)}verify(e,t){return t=vH(t,64),ma.verify(t,e,this.publicKeyRaw)}};g();var q6=`abandon
10
+ deps: ${t}}`};var Zoe={keyword:"dependencies",type:"object",schemaType:"object",error:Pd.error,code(r){let[e,t]=Yoe(r);yL(r,e),gL(r,t)}};function Yoe({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function yL(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let o in e){let s=e[o];if(s.length===0)continue;let c=(0,h0.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of s)(0,h0.checkReportMissingProp)(r,l)}):(t.if((0,iR._)`${c} && (${(0,h0.checkMissingProp)(r,s,a)})`),(0,h0.reportMissingProp)(r,a),t.else())}}Pd.validatePropertyDeps=yL;function gL(r,e=r.schema){let{gen:t,data:n,keyword:i,it:a}=r,o=t.name("valid");for(let s in e)(0,Joe.alwaysValidSchema)(a,e[s])||(t.if((0,h0.propertyInData)(t,n,s,a.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:s},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}Pd.validateSchemaDeps=gL;Pd.default=Zoe});var vL=Ae(sR=>{"use strict";g();Object.defineProperty(sR,"__esModule",{value:!0});var wL=jt(),Xoe=Xt(),Qoe={message:"property name must be valid",params:({params:r})=>(0,wL._)`{propertyName: ${r.propertyName}}`},eae={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qoe,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Xoe.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,wL.not)(a),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(a)}};sR.default=eae});var aR=Ae(oR=>{"use strict";g();Object.defineProperty(oR,"__esModule",{value:!0});var Vx=Ea(),kc=jt(),tae=xa(),Wx=Xt(),rae={message:"must NOT have additional properties",params:({params:r})=>(0,kc._)`{additionalProperty: ${r.additionalProperty}}`},nae={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rae,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:a,it:o}=r;if(!a)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Wx.alwaysValidSchema)(o,t))return;let l=(0,Vx.allSchemaProperties)(n.properties),d=(0,Vx.allSchemaProperties)(n.patternProperties);u(),r.ok((0,kc._)`${a} === ${tae.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(l.length>8){let w=(0,Wx.schemaRefOrVal)(o,n.properties,"properties");v=(0,Vx.isOwnProperty)(e,w,y)}else l.length?v=(0,kc.or)(...l.map(w=>(0,kc._)`${y} === ${w}`)):v=kc.nil;return d.length&&(v=(0,kc.or)(v,...d.map(w=>(0,kc._)`${(0,Vx.usePattern)(r,w)}.test(${y})`))),(0,kc.not)(v)}function p(y){e.code((0,kc._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),s||e.break();return}if(typeof t=="object"&&!(0,Wx.alwaysValidSchema)(o,t)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,kc.not)(v),()=>{r.reset(),p(y)})):(m(y,v),s||e.if((0,kc.not)(v),()=>e.break()))}}function m(y,v,w){let x={keyword:"additionalProperties",dataProp:y,dataPropType:Wx.Type.Str};w===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(x,v)}}};oR.default=nae});var xL=Ae(dR=>{"use strict";g();Object.defineProperty(dR,"__esModule",{value:!0});var iae=Qv(),bL=Ea(),cR=Xt(),PL=aR(),sae={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&PL.default.code(new iae.KeywordCxt(a,PL.default,"additionalProperties"));let o=(0,bL.allSchemaProperties)(t);for(let u of o)a.definedProperties.add(u);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=cR.mergeEvaluated.props(e,(0,cR.toHash)(o),a.props));let s=o.filter(u=>!(0,cR.alwaysValidSchema)(a,t[u]));if(s.length===0)return;let c=e.name("valid");for(let u of s)l(u)?d(u):(e.if((0,bL.propertyInData)(e,i,u,a.opts.ownProperties)),d(u),a.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return a.opts.useDefaults&&!a.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};dR.default=sae});var _L=Ae(lR=>{"use strict";g();Object.defineProperty(lR,"__esModule",{value:!0});var EL=Ea(),Jx=jt(),SL=Xt(),kL=Xt(),oae={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:a}=r,{opts:o}=a,s=(0,EL.allSchemaProperties)(t),c=s.filter(m=>(0,SL.alwaysValidSchema)(a,t[m]));if(s.length===0||c.length===s.length&&(!a.opts.unevaluated||a.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof Jx.Name)&&(a.props=(0,kL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of s)l&&p(m),a.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,SL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,Jx._)`${(0,EL.usePattern)(r,m)}.test(${y})`,()=>{let v=c.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kL.Type.Str},d),a.opts.unevaluated&&u!==!0?e.assign((0,Jx._)`${u}[${y}]`,!0):!v&&!a.allErrors&&e.if((0,Jx.not)(d),()=>e.break())})})}}};lR.default=oae});var AL=Ae(uR=>{"use strict";g();Object.defineProperty(uR,"__esModule",{value:!0});var aae=Xt(),cae={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,aae.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};uR.default=cae});var TL=Ae(fR=>{"use strict";g();Object.defineProperty(fR,"__esModule",{value:!0});var dae=Ea(),lae={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dae.validateUnion,error:{message:"must match a schema in anyOf"}};fR.default=lae});var IL=Ae(pR=>{"use strict";g();Object.defineProperty(pR,"__esModule",{value:!0});var Zx=jt(),uae=Xt(),fae={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Zx._)`{passingSchemas: ${r.passing}}`},pae={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fae,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=t,o=e.let("valid",!1),s=e.let("passing",null),c=e.name("_valid");r.setParams({passing:s}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){a.forEach((d,u)=>{let f;(0,uae.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Zx._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Zx._)`[${s}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(s,u),f&&r.mergeEvaluated(f,Zx.Name)})})}}};pR.default=pae});var DL=Ae(hR=>{"use strict";g();Object.defineProperty(hR,"__esModule",{value:!0});var hae=Xt(),mae={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,o)=>{if((0,hae.alwaysValidSchema)(n,a))return;let s=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(s)})}};hR.default=mae});var $L=Ae(mR=>{"use strict";g();Object.defineProperty(mR,"__esModule",{value:!0});var Yx=jt(),CL=Xt(),yae={message:({params:r})=>(0,Yx.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Yx._)`{failingKeyword: ${r.ifClause}}`},gae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yae,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,CL.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=RL(n,"then"),a=RL(n,"else");if(!i&&!a)return;let o=e.let("valid",!0),s=e.name("_valid");if(c(),r.reset(),i&&a){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(s,l("then",d),l("else",d))}else i?e.if(s,l("then")):e.if((0,Yx.not)(s),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},s);e.assign(o,s),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Yx._)`${d}`):r.setParams({ifClause:d})}}}};function RL(r,e){let t=r.schema[e];return t!==void 0&&!(0,CL.alwaysValidSchema)(r,t)}mR.default=gae});var BL=Ae(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var wae=Xt(),vae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,wae.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};yR.default=vae});var OL=Ae(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var bae=QD(),Pae=fL(),xae=eR(),Eae=hL(),Sae=mL(),kae=Hx(),_ae=vL(),Aae=aR(),Tae=xL(),Iae=_L(),Dae=AL(),Rae=TL(),Cae=IL(),$ae=DL(),Bae=$L(),Oae=BL();function jae(r=!1){let e=[Dae.default,Rae.default,Cae.default,$ae.default,Bae.default,Oae.default,_ae.default,Aae.default,kae.default,Tae.default,Iae.default];return r?e.push(Pae.default,Eae.default):e.push(bae.default,xae.default),e.push(Sae.default),e}gR.default=jae});var vR=Ae(m0=>{"use strict";g();Object.defineProperty(m0,"__esModule",{value:!0});m0.dynamicAnchor=void 0;var wR=jt(),Mae=xa(),jL=t0(),Kae=Ux(),Nae={keyword:"$dynamicAnchor",schemaType:"string",code:r=>ML(r,r.schema)};function ML(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,wR._)`${Mae.default.dynamicAnchors}${(0,wR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Uae(r);t.if((0,wR._)`!${i}`,()=>t.assign(i,a))}m0.dynamicAnchor=ML;function Uae(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:a,localRefs:o,meta:s}=e.root,{schemaId:c}=n.opts,l=new jL.SchemaEnv({schema:t,schemaId:c,root:i,baseId:a,localRefs:o,meta:s});return jL.compileSchema.call(n,l),(0,Kae.getValidate)(r,l)}m0.default=Nae});var bR=Ae(y0=>{"use strict";g();Object.defineProperty(y0,"__esModule",{value:!0});y0.dynamicRef=void 0;var KL=jt(),Lae=xa(),NL=Ux(),qae={keyword:"$dynamicRef",schemaType:"string",code:r=>UL(r,r.schema)};function UL(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0,KL._)`${Lae.default.dynamicAnchors}${(0,KL.getProperty)(a)}`);t.if(l,s(l,c),s(i.validateName,c))}else s(i.validateName,c)()}function s(c,l){return l?()=>t.block(()=>{(0,NL.callRef)(r,c),t.let(l,!0)}):()=>(0,NL.callRef)(r,c)}}y0.dynamicRef=UL;y0.default=qae});var LL=Ae(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var zae=vR(),Fae=Xt(),Gae={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,zae.dynamicAnchor)(r,""):(0,Fae.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};PR.default=Gae});var qL=Ae(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var Hae=bR(),Vae={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Hae.dynamicRef)(r,r.schema)};xR.default=Vae});var zL=Ae(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var Wae=vR(),Jae=bR(),Zae=LL(),Yae=qL(),Xae=[Wae.default,Jae.default,Zae.default,Yae.default];ER.default=Xae});var GL=Ae(SR=>{"use strict";g();Object.defineProperty(SR,"__esModule",{value:!0});var FL=Hx(),Qae={keyword:"dependentRequired",type:"object",schemaType:"object",error:FL.error,code:r=>(0,FL.validatePropertyDeps)(r)};SR.default=Qae});var HL=Ae(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var ece=Hx(),tce={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,ece.validateSchemaDeps)(r)};kR.default=tce});var VL=Ae(_R=>{"use strict";g();Object.defineProperty(_R,"__esModule",{value:!0});var rce=Xt(),nce={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,rce.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};_R.default=nce});var WL=Ae(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var ice=GL(),sce=HL(),oce=VL(),ace=[ice.default,sce.default,oce.default];AR.default=ace});var ZL=Ae(TR=>{"use strict";g();Object.defineProperty(TR,"__esModule",{value:!0});var tf=jt(),JL=Xt(),cce=xa(),dce={message:"must NOT have unevaluated properties",params:({params:r})=>(0,tf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},lce={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:dce,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:s}=a;s instanceof tf.Name?e.if((0,tf._)`${s} !== true`,()=>e.forIn("key",n,u=>e.if(l(s,u),()=>c(u)))):s!==!0&&e.forIn("key",n,u=>s===void 0?c(u):e.if(d(s,u),()=>c(u))),a.props=!0,r.ok((0,tf._)`${i} === ${cce.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,JL.alwaysValidSchema)(a,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:JL.Type.Str},f),o||e.if((0,tf.not)(f),()=>e.break())}}function l(u,f){return(0,tf._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let h in u)u[h]===!0&&p.push((0,tf._)`${f} !== ${h}`);return(0,tf.and)(...p)}}};TR.default=lce});var XL=Ae(IR=>{"use strict";g();Object.defineProperty(IR,"__esModule",{value:!0});var Yp=jt(),YL=Xt(),uce={message:({params:{len:r}})=>(0,Yp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Yp._)`{limit: ${r}}`},fce={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:uce,code(r){let{gen:e,schema:t,data:n,it:i}=r,a=i.items||0;if(a===!0)return;let o=e.const("len",(0,Yp._)`${n}.length`);if(t===!1)r.setParams({len:a}),r.fail((0,Yp._)`${o} > ${a}`);else if(typeof t=="object"&&!(0,YL.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,Yp._)`${o} <= ${a}`);e.if((0,Yp.not)(c),()=>s(c,a)),r.ok(c)}i.items=!0;function s(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:YL.Type.Num},c),i.allErrors||e.if((0,Yp.not)(c),()=>e.break())})}}};IR.default=fce});var QL=Ae(DR=>{"use strict";g();Object.defineProperty(DR,"__esModule",{value:!0});var pce=ZL(),hce=XL(),mce=[pce.default,hce.default];DR.default=mce});var e9=Ae(RR=>{"use strict";g();Object.defineProperty(RR,"__esModule",{value:!0});var Gn=jt(),yce={message:({schemaCode:r})=>(0,Gn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Gn._)`{format: ${r}}`},gce={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:yce,code(r,e){let{gen:t,data:n,$data:i,schema:a,schemaCode:o,it:s}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=s;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),m=t.const("fDef",(0,Gn._)`${h}[${o}]`),y=t.let("fType"),v=t.let("format");t.if((0,Gn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,Gn._)`${m}.type || "string"`).assign(v,(0,Gn._)`${m}.validate`),()=>t.assign(y,(0,Gn._)`"string"`).assign(v,m)),r.fail$data((0,Gn.or)(w(),x()));function w(){return c.strictSchema===!1?Gn.nil:(0,Gn._)`${o} && !${v}`}function x(){let _=d.$async?(0,Gn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Gn._)`${v}(${n})`,A=(0,Gn._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,Gn._)`${v} && ${v} !== true && ${y} === ${e} && !${A}`}}function p(){let h=u.formats[a];if(!h){w();return}if(h===!0)return;let[m,y,v]=x(h);m===e&&r.pass(_());function w(){if(c.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function x(A){let D=A instanceof RegExp?(0,Gn.regexpCode)(A):c.code.formats?(0,Gn._)`${c.code.formats}${(0,Gn.getProperty)(a)}`:void 0,N=t.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Gn._)`${N}.validate`]:["string",A,N]}function _(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Gn._)`await ${v}(${n})`}return typeof y=="function"?(0,Gn._)`${v}(${n})`:(0,Gn._)`${v}.test(${n})`}}}};RR.default=gce});var t9=Ae(CR=>{"use strict";g();Object.defineProperty(CR,"__esModule",{value:!0});var wce=e9(),vce=[wce.default];CR.default=vce});var r9=Ae(Ty=>{"use strict";g();Object.defineProperty(Ty,"__esModule",{value:!0});Ty.contentVocabulary=Ty.metadataVocabulary=void 0;Ty.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ty.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var i9=Ae($R=>{"use strict";g();Object.defineProperty($R,"__esModule",{value:!0});var bce=ZU(),Pce=cL(),xce=OL(),Ece=zL(),Sce=WL(),kce=QL(),_ce=t9(),n9=r9(),Ace=[Ece.default,bce.default,Pce.default,(0,xce.default)(!0),_ce.default,n9.metadataVocabulary,n9.contentVocabulary,Sce.default,kce.default];$R.default=Ace});var o9=Ae(Xx=>{"use strict";g();Object.defineProperty(Xx,"__esModule",{value:!0});Xx.DiscrError=void 0;var s9;(function(r){r.Tag="tag",r.Mapping="mapping"})(s9||(Xx.DiscrError=s9={}))});var c9=Ae(OR=>{"use strict";g();Object.defineProperty(OR,"__esModule",{value:!0});var Iy=jt(),BR=o9(),a9=t0(),Tce=e0(),Ice=Xt(),Dce={message:({params:{discrError:r,tagName:e}})=>r===BR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Iy._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},Rce={keyword:"discriminator",type:"object",schemaType:"object",error:Dce,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:a}=r,{oneOf:o}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Iy._)`${t}${(0,Iy.getProperty)(s)}`);e.if((0,Iy._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:BR.DiscrError.Tag,tag:l,tagName:s})),r.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Iy._)`${l} === ${h}`),e.assign(c,u(p[h]));e.else(),r.error(!1,{discrError:BR.DiscrError.Mapping,tag:l,tagName:s}),e.endIf()}function u(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Iy.Name),h}function f(){var p;let h={},m=v(i),y=!0;for(let _=0;_<o.length;_++){let A=o[_];if(A?.$ref&&!(0,Ice.schemaHasRulesButRef)(A,a.self.RULES)){let N=A.$ref;if(A=a9.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),A instanceof a9.SchemaEnv&&(A=A.schema),A===void 0)throw new Tce.default(a.opts.uriResolver,a.baseId,N)}let D=(p=A?.properties)===null||p===void 0?void 0:p[s];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);y=y&&(m||v(A)),w(D,_)}if(!y)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:_}){return Array.isArray(_)&&_.includes(s)}function w(_,A){if(_.const)x(_.const,A);else if(_.enum)for(let D of _.enum)x(D,A);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function x(_,A){if(typeof _!="string"||_ in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[_]=A}}}};OR.default=Rce});var d9=Ae((jOe,Cce)=>{Cce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var l9=Ae((MOe,$ce)=>{$ce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var u9=Ae((KOe,Bce)=>{Bce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var f9=Ae((NOe,Oce)=>{Oce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var p9=Ae((UOe,jce)=>{jce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var h9=Ae((LOe,Mce)=>{Mce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var m9=Ae((qOe,Kce)=>{Kce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var y9=Ae((zOe,Nce)=>{Nce.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var g9=Ae(jR=>{"use strict";g();Object.defineProperty(jR,"__esModule",{value:!0});var Uce=d9(),Lce=l9(),qce=u9(),zce=f9(),Fce=p9(),Gce=h9(),Hce=m9(),Vce=y9(),Wce=["/properties"];function Jce(r){return[Uce,Lce,qce,zce,Fce,e(this,Gce),Hce,e(this,Vce)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,Wce):n}}jR.default=Jce});var NR=Ae((dn,KR)=>{"use strict";g();Object.defineProperty(dn,"__esModule",{value:!0});dn.MissingRefError=dn.ValidationError=dn.CodeGen=dn.Name=dn.nil=dn.stringify=dn.str=dn._=dn.KeywordCxt=dn.Ajv2020=void 0;var Zce=GU(),Yce=i9(),Xce=c9(),Qce=g9(),MR="https://json-schema.org/draft/2020-12/schema",Dy=class extends Zce.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Yce.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xce.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Qce.default.call(this,e),this.refs["http://json-schema.org/schema"]=MR)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(MR)?MR:void 0)}};dn.Ajv2020=Dy;KR.exports=dn=Dy;KR.exports.Ajv2020=Dy;Object.defineProperty(dn,"__esModule",{value:!0});dn.default=Dy;var ede=Qv();Object.defineProperty(dn,"KeywordCxt",{enumerable:!0,get:function(){return ede.KeywordCxt}});var Ry=jt();Object.defineProperty(dn,"_",{enumerable:!0,get:function(){return Ry._}});Object.defineProperty(dn,"str",{enumerable:!0,get:function(){return Ry.str}});Object.defineProperty(dn,"stringify",{enumerable:!0,get:function(){return Ry.stringify}});Object.defineProperty(dn,"nil",{enumerable:!0,get:function(){return Ry.nil}});Object.defineProperty(dn,"Name",{enumerable:!0,get:function(){return Ry.Name}});Object.defineProperty(dn,"CodeGen",{enumerable:!0,get:function(){return Ry.CodeGen}});var tde=Rx();Object.defineProperty(dn,"ValidationError",{enumerable:!0,get:function(){return tde.default}});var rde=e0();Object.defineProperty(dn,"MissingRefError",{enumerable:!0,get:function(){return rde.default}})});var rf,Qx=G(()=>{"use strict";g();SP();Et();rf=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:o}=e;await Ko.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:o}),r.verifyScope(t,a.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:o}=e;await Ko.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:a,messageStore:o});let c=a.scope.protocol,l=i.descriptor.filter?.protocol;if(c!==void 0&&l!==c)throw new ie(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${c} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ie(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function Ws(r){let e=r.indexOf(":");if(e===-1)return;let t=r.substring(0,e),n=r.substring(e+1);return{alias:t,protocolPath:n}}function nf(r){return r.includes(":")}function e2(r){return r.split("/").slice(-1)[0]}function Ed(r,e){let t=r.split("/"),n,i=e;for(let a of t){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var xd,Xp=G(()=>{"use strict";g();Pn();Um();xd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,d=[Pt.ProtocolPath,e.protocol];async function u(f,p){for(let h in f)if(!h.startsWith("$")){let m=[...p,h],y=f[h];if(y.$ref!==void 0){await u(y,m);continue}let v=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:v},await u(y,m)}}return await u(i.structure,d),i}let a=t;async function o(l,d){for(let u in l)if(!u.startsWith("$")){let f=await Ni.derivePrivateKey(d,[u]),p=l[u];if(p.$ref!==void 0){await o(p,f);continue}let h=await At.getPublicKey({key:f.derivedPrivateKey});p.$encryption={rootKeyId:a,publicKeyJwk:h},await o(p,f)}}let s={derivationScheme:Pt.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},c=await Ni.derivePrivateKey(s,[Pt.ProtocolPath,e.protocol]);return await o(i.structure,c),i}}});var w9,_a,t2=G(()=>{"use strict";g();Pc();w9=Tn(NR(),1);vr();dc();Qx();ms();Et();ur();Xp();ga();Bg();_a=class r extends On{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),definition:r.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await ye.createAuthorization({descriptor:t,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),r.validateProtocolDefinition(i.descriptor.definition),new r(i)}async authorizeAuthorDelegate(e){let t=Ir.parse(this.message.authorization.authorDelegatedGrant);await rf.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}static validateProtocolDefinition(e){let{protocol:t,types:n,uses:i}=e;li(t);for(let a in n){let o=n[a].schema;o!==void 0&&td(o)}i!==void 0&&r.validateUses(i,t),r.validateStructure(e)}static validateUses(e,t){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ie(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{li(e[i])}catch{throw new ie(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ie(re.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${t}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:t}=e,n=Object.keys(e.types),i=r.fetchAllRolePathsRecursively("",e.structure,[]);r.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:t,types:e.types})}static fetchAllRolePathsRecursively(e,t,n){if(e.split("/").length>10)throw new ie(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let a=t[i],o;e===""?o=i:o=`${e}/${i}`,a.$role?n.push(o):r.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:o,types:s}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ie(re.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);r.validateRefNode(t,n,o)}if(t.$size!==void 0){let{min:l=0,max:d}=t.$size;if(d!==void 0&&d<l)throw new ie(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${d} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:d}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ie(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Wl);if(!u.includes(d))throw new ie(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new w9.default.default,{$allowUndefinedTags:d,$requiredTags:u,...f}=t.$tags;for(let p in f){let h=f[p];if(!l.validateSchema(h)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${p}`});throw new ie(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let c=t.$actions??[];for(let l=0;l<c.length;l++){let d=c[l];if(d.role!==void 0){if(nf(d.role))r.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ie(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ie(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(d.who===$c.Recipient&&d.of===void 0&&d.can.some(f=>![xr.CoUpdate,xr.CoDelete,xr.CoPrune].includes(f)))throw new ie(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who===$c.Author&&!d.of)throw new ie(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(nf(d.of))r.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ie(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes(xr.Update)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes(xr.Delete)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes(xr.Prune)&&!d.can.includes(xr.Create))throw new ie(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<c.length;u++){let f=c[u];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ie(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ie(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let l=n.split("/").pop();s[l]?.encryptionRequired===!0&&c.some(f=>f.who===$c.Anyone&&f.can.includes(xr.Read))&&console.warn(`ProtocolsConfigure: type '${l}' at path '${n}' has encryptionRequired: true but allows { who: 'anyone', can: ['read'] }. Anyone can read the record but no one outside the key holders can decrypt it.`)}t.$delivery!==void 0&&(t.$actions===void 0||t.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${t.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),t.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes(xr.Update)||d.can.includes(xr.CoUpdate))&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $immutable: true but $actions include 'update' or 'co-update'. The $immutable directive takes precedence \u2014 updates will always be rejected regardless of action rules.`);for(let l in t){if(l.startsWith("$"))continue;let d=t[l];if(d.$ref===void 0&&!i.includes(l))throw new ie(re.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,r.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:o,types:s})}}static validateRefNode(e,t,n){let i=e.$ref,a=Ws(i);if(a===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${t}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let s of o)if(e[s]!==void 0)throw new ie(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${s}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let a=Ws(e);if(a===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(o,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t===void 0||t[a.alias]===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(o,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let t={};for(let i in e.types)t[i]={...e.types[i]};for(let i in t){let a=t[i].schema;a!==void 0&&(t[i].schema=Ep(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Ns(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Ns(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var r2,v9=G(()=>{"use strict";g();Fo();vr();Go();Ho();t2();Qx();Et();ur();Xp();r2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _a.parse(t)}catch(d){return wt(d,400)}try{await yn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return wt(d,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(d){return wt(d,400)}let i={interface:ve.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),o=await ye.getCid(t);for(let d of a)if(await ye.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let s=await ye.getNewestMessage(a),c=!1;(s===void 0||await ye.isNewer(t,s))&&(c=!0,s=t);let l;if(c){let d=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},d,u),l={status:{code:202,detail:"Accepted"}}}else{let d=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),l={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==s){let u=await _a.parse(d),f=r.constructIndexes(u,!1),p=await ye.getCid(d);await this.deps.messageStore.delete(e,p),await this.deps.messageStore.put(e,d,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:t}}static async authorizeProtocolsConfigure(e,t,n){if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await rt.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await rf.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ie(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let a=new Map;for(let o in i){let s=i[o],c=await r.fetchInstalledProtocolDefinition(e,s,n);if(c===void 0)throw new ie(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${s}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}r.validateRefsAndRolesRecursively(t.structure,"",a)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:ve.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],o=t===""?i:`${t}/${i}`;if(a.$ref!==void 0){let c=Ws(a.$ref);if(c!==void 0){let l=n.get(c.alias);if(l===void 0)throw new ie(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),u=l.structure;for(let f=0;f<d.length;f++){let p=d[f],h=u[p];if(h===void 0)throw new ie(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(h.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ie(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${l.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}u=h}}}let s=a.$actions??[];for(let c of s){if(c.role!==void 0){let l=Ws(c.role);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let u=Ed(l.protocolPath,d.structure);if(u===void 0||!u.$role)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let l=Ws(c.of);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(Ed(l.protocolPath,d.structure)===void 0)throw new ie(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}r.validateRefsAndRolesRecursively(a,o,n)}}}});var Aa,n2=G(()=>{"use strict";g();Pc();vr();Ho();Qx();Oi();ms();Et();ur();ga();Aa=class r extends On{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&li(e.descriptor.filter.protocol),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};rr(t);let n;e.signer!==void 0&&(n=await ye.createAuthorization({descriptor:t,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),new r(i)}static normalizeFilter(e){return{...e,protocol:Ns(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await rt.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await rf.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ie(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var i2,b9=G(()=>{"use strict";g();Fo();Et();Go();n2();Oi();ur();i2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Aa.parse(t)}catch(o){return wt(o,400)}try{await yn(t.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code===re.AuthenticateJwsMissing||o.code===re.ProtocolsQueryUnauthorized||o.code===re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let s=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:s}}else return wt(o,401)}let i={...t.descriptor.filter,interface:ve.Protocols,method:me.Configure,isLatestBaseState:!0};rr(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:ve.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function g0(r,e,t,n,i,a,o,s){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let l=t,d=c;if(nf(c)){let h=Ws(c);if(h===void 0)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(i.uses===void 0||i.uses[h.alias]===void 0)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${h.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);l=i.uses[h.alias],d=h.protocolPath;let m=await o(r,l,a,s),y=Ed(d,m.structure);if(y===void 0||!y.$role)throw new ie(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${c} does not match role record type.`)}else{let h=Ed(c,i.structure);if(h===void 0||!h.$role)throw new ie(re.ProtocolAuthorizationNotARole,`Protocol path ${c} does not match role record type.`)}let u={interface:ve.Records,method:me.Write,protocol:l,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ie(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=nr.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:p}=await a.query(r,[u]);if(p.length===0)throw new ie(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${d}`)}async function nde(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,a=await _t.fetchInitialRecordsWrite(t,r,i);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push(xr.CoPrune),e.author===a.author&&o.push(xr.Prune)):(o.push(xr.CoDelete),e.author===a.author&&o.push(xr.Delete)),o;case me.Count:return[xr.Read];case me.Query:return[xr.Read];case me.Read:return[xr.Read];case me.Subscribe:return[xr.Read];case me.Write:let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?[xr.Squash,xr.Create]:[xr.Create];{let l=e.message.recordId,d=await _t.fetchInitialRecordsWrite(t,r,l);return d===void 0?[]:e.author===d.author?[xr.CoUpdate,xr.Update]:[xr.CoUpdate]}}return[]}async function w0(r,e,t,n,i,a){let o=e.message.descriptor.method,s=await nde(r,e,i),c=e.author,l=t.$actions;if(l===void 0)throw new ie(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(h=>s.includes(h)))continue;if(u.who===$c.Anyone)return;if(c===void 0)continue;if(d!==void 0){if(u.role===d)return;continue}if(u.who===$c.Recipient&&u.of===void 0){let h;if(e.message.descriptor.method===me.Write?h=e.message:h=n[n.length-1],h.descriptor.recipient===c)return;continue}if(await ide(c,u,n,a))return}throw new ie(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function ide(r,e,t,n){let i=e.of;if(i===void 0)return!1;let a;if(nf(i)&&n?.uses!==void 0){let o=Ws(i);if(o!==void 0){let s=n.uses[o.alias];s!==void 0&&(a=t.find(c=>c.descriptor.protocol===s&&c.descriptor.protocolPath===o.protocolPath))}}else a=t.find(o=>o.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===$c.Recipient)return r===a.descriptor.recipient;{let o=(await _t.parse(a)).author;return r===o}}var P9=G(()=>{"use strict";g();yc();Gs();Et();ur();Xp();Bg()});async function Cy(r,e,t){let n={interface:ve.Records,method:me.Write,recordId:e},{messages:i}=await t.query(r,[n]);return i.length===0?void 0:await _t.getInitialWrite(i)}async function v0(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await Cy(r,i,t);if(a===void 0)throw new ie(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(a),i=a.descriptor.parentId}return n.reverse()}async function UR(r,e,t){let n=await Cy(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var x9=G(()=>{"use strict";g();Gs();Et();ur()});async function S9(r,e,t,n,i){let a=e.message.descriptor.protocolPath,o=e2(a),s=e.message.descriptor.parentId;if(s===void 0){if(a!==o)throw new ie(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,l=await sde(r,c,a,t,n,i),d={isLatestBaseState:!0,interface:ve.Records,method:me.Write,protocol:l,recordId:s},{messages:u}=await t.query(r,[d]),f=u[0];if(f===void 0)throw l!==c?new ie(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${s}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ie(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new ie(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ie(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function sde(r,e,t,n,i,a){let o=t.split("/");if(o.length<=1)return e;let s=await i(r,e,n,a),c=s.structure[o[0]];if(c?.$ref!==void 0){let l=Ws(c.$ref);if(l!==void 0&&s.uses!==void 0){let d=s.uses[l.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function k9(r,e,t,n,i,a){let o=e.descriptor.protocolPath,s=e2(o),c=await ode(r,o,t,n,i,a);ade(e,c,s)}async function ode(r,e,t,n,i,a){let o=e.split("/"),s=t.structure[o[0]];if(s?.$ref!==void 0&&o.length===1){let c=Ws(s.$ref);if(c!==void 0&&t.uses!==void 0){let l=t.uses[c.alias];if(l!==void 0)return(await i(r,l,n,a)).types}}return t.types}function ade(r,e,t){let n=t??e2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ie(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=r.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ie(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:s}=r.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(s))throw new ie(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${s}'`);if(a.encryptionRequired===!0&&r.encryption===void 0)throw new ie(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function _9(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ie(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ie(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function A9(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...s}=e.$tags,c=a||!1,l=o||[],d=new E9.default.default,u=d.compile({type:"object",properties:s,required:l,additionalProperties:c});if(!u(t)){let p=d.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ie(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${p}`)}}}async function T9(r,e,t,n){if(!t.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ie(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let o=i.message.descriptor.protocolPath,s={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:o,recipient:a},c=Ie.getParentContextFromOfContextId(i.message.contextId);if(c!==""){let f=nr.constructPrefixFilterAsRangeFilter(c);s.contextId=f}let{messages:l}=await n.query(r,[s]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ie(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function I9(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=t.$recordLimit,s=e.message.descriptor.protocolPath,c={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:s},l=Ie.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=nr.constructPrefixFilterAsRangeFilter(l);c.contextId=u}if(await n.count(r,[c])>=a)throw o===Wl.Reject?new ie(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${a} reached at protocol path '${s}'${l!==""?` under parent context '${l}'`:""}: new records are rejected until existing records are deleted.`):new ie(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${o}' is not yet implemented.`)}async function D9(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ie(re.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${r.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await r.isInitialWrite())throw new ie(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function R9(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ie(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var E9,C9=G(()=>{"use strict";g();Bg();E9=Tn(NR(),1);yc();ti();Et();ur();Xp()});var bs,Qp=G(()=>{"use strict";g();Xp();ed();Et();ur();P9();x9();C9();bs=class r{static async validateReferentialIntegrity(e,t,n,i){let a=await UR(e,t,n),o=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),s=r.createBoundFetchDefinition(i);await k9(e,t.message,o,n,s,a),await S9(e,t,n,s,a);let c=r.getRuleSet(t.message.descriptor.protocolPath,o);await T9(e,t,c,n),_9(t,c),A9(t,c),await R9(t,c),await D9(t,c),await I9(e,t,c,n)}static async authorizeWrite(e,t,n,i){let a=await Cy(e,t.message.recordId,n),o;a===void 0?o=await v0(e,t.message.descriptor.parentId,n):o=await v0(e,t.message.recordId,n);let s=await UR(e,t,n),c=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,s,i),l=r.getRuleSet(t.message.descriptor.protocolPath,c),d=r.createBoundFetchDefinition(i);await g0(e,t,t.message.descriptor.protocol,t.message.contextId,c,n,d,s),await w0(e,t,l,o,n,c)}static async authorizeRead(e,t,n,i,a){let o=await v0(e,n.message.recordId,i),s=await Cy(e,n.message.recordId,i),c=s!==void 0?s.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await g0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await w0(e,t,d,o,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:a,protocolPath:o,contextId:s}=t.message.descriptor.filter,c=await r.fetchProtocolDefinition(e,a,n,void 0,i),l=r.getRuleSet(o,c),d=r.createBoundFetchDefinition(i);await g0(e,t,a,s,c,n,d),await w0(e,t,l,[],n,c)}static async authorizeDelete(e,t,n,i,a){let o=await v0(e,t.message.descriptor.recordId,i),s=await Cy(e,t.message.descriptor.recordId,i),c=s!==void 0?s.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await g0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await w0(e,t,d,o,i,l)}static async fetchProtocolDefinition(e,t,n,i,a){if(a!==void 0){let l=a.getDefinition(t);if(l!==void 0)return l}let o={interface:ve.Protocols,method:me.Configure,protocol:t};i!==void 0?o.messageTimestamp={lte:i}:o.isLatestBaseState=!0;let{messages:s}=await n.query(e,[o],{messageTimestamp:Rt.Descending},{limit:1});if(s.length===0)throw new ie(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return s[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,a)=>r.fetchProtocolDefinition(t,n,i,a,e)}static getRuleSet(e,t){let n=Ed(e,t.structure);if(n===void 0)throw new ie(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var s2,$9=G(()=>{"use strict";g();Fo();vr();Go();Qp();ti();dx();ur();s2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await hd.parse(t)}catch(a){return wt(a,400)}let i;if(Ie.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return wt(a,401)}n.author===e?i=await this.countRecordsAsOwner(e,n):i=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:i}}async countRecordsAsOwner(e,t){let{filter:n}=t.message.descriptor,i={...Ie.convertFilter(n),interface:ve.Records,method:me.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,t){let{filter:n}=t.message.descriptor,i=[];return Ie.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),Ie.filterIncludesUnpublishedRecords(n)&&(Ie.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),Ie.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ie.shouldBuildUnpublishedRecipientFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsForCountAuthorFilter(t))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,t){let n=r.buildPublishedRecordsFilter(t);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ie.convertFilter(t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var Ta,b0=G(()=>{"use strict";g();Pc();vr();dc();ti();rd();Oi();ms();ur();Ta=class r extends On{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=kt.getCurrentTimestamp(),i={interface:ve.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},a=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:i,authorization:a};return ye.validateJsonSchema(o),new r(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:o,schema:s,parentId:c,dateCreated:l}=e.descriptor,d={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:o,schema:s,parentId:c,dateCreated:l,contextId:e.contextId,author:this.author,...n};return rr(d),d}async authorizeDelegate(e,t){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var sf,o2,a2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(sf||(sf={}));o2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[sf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[sf.RecordsSquash]:async n=>await t.performRecordsSquash(n)}}async run(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,t);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,t)},r.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{r.clearTimeoutExtensionTimer(n)}}static clearTimeoutExtensionTimer(e){clearInterval(e)}async resumeTasksAndWaitForCompletion(){for(;;){let e=await this.resumableTaskStore.grab(this.resumableTaskBatchSize);if(e===void 0||e.length===0)break;await this.retryTasksUntilCompletion(e)}}async retryTasksUntilCompletion(e){let t=e;for(;t.length>0;){let n=t;t=[];for(let i of n)try{await this.runWithAutomaticTimeoutExtension(i)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",i),t.push(i)}}}}});var c2,B9=G(()=>{"use strict";g();Fo();ur();vr();Go();Ho();Qp();ti();b0();rd();Gs();a2();c2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Ta.parse(t)}catch(l){return wt(l,400)}try{await yn(t.authorization,this.deps.didResolver)}catch(l){return wt(l,401)}let i={interface:ve.Records,recordId:t.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),o=await ye.getNewestMessage(a);if(!Ie.canPerformDeleteAgainstRecord(t,o))return{status:{code:404,detail:"Not Found"}};if(!await ye.isNewer(t,o))return{status:{code:409,detail:"Conflict"}};try{let l=await _t.fetchInitialRecordsWrite(this.deps.messageStore,e,t.descriptor.recordId);await r.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return wt(l,401)}return await this.deps.resumableTaskManager.run({name:sf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,a){if(ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let o=await rt.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Ln.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await bs.authorizeDelete(e,t,n,i,a)}}});var d2,O9=G(()=>{"use strict";g();Fo();mp();vr();Go();Qp();ti();lx();Gs();ed();ur();d2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await ba.parse(t)}catch(o){return wt(o,400)}let i,a;if(Ie.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);i=o.messages,a=o.cursor}else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return wt(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);i=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);i=o.messages,a=o.cursor}}for(let o of i)if(!await _t.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:Rt.Ascending};case Ut.CreatedDescending:return{dateCreated:Rt.Descending};case Ut.PublishedAscending:return{datePublished:Rt.Ascending};case Ut.PublishedDescending:return{datePublished:Rt.Descending};case Ut.UpdatedAscending:return{messageTimestamp:Rt.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:Rt.Descending};default:return{dateCreated:Rt.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:a}=t.message.descriptor,o={...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0},s=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],s,a)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:a}=t.message.descriptor,o=[];Ie.filterIncludesPublishedRecords(a)&&o.push(r.buildPublishedRecordsFilter(t)),Ie.filterIncludesUnpublishedRecords(a)&&(Ie.shouldBuildUnpublishedAuthorFilter(a,t.author)&&o.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),Ie.shouldProtocolAuthorize(t.signaturePayload)&&o.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ie.shouldBuildUnpublishedRecipientFilter(a,t.author)&&o.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let s=this.convertDateSort(n);return this.deps.messageStore.query(e,o,s,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,a=r.buildPublishedRecordsFilter(t),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var Sd,LR=G(()=>{"use strict";g();Pc();mp();vr();dc();ti();rd();Oi();ms();Et();ur();Sd=class r extends On{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ut.PublishedAscending||e.descriptor.dateSort===Ut.PublishedDescending))throw new ie(re.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:a,dateSort:o}=e,s=kt.getCurrentTimestamp();if(e.filter.published===!1&&(o===Ut.PublishedAscending||o===Ut.PublishedDescending))throw new ie(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:ve.Records,method:me.Read,filter:Ie.normalizeFilter(t),messageTimestamp:e.messageTimestamp??s,permissionGrantId:i,dateSort:o};rr(c);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:c,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:l};return ye.validateJsonSchema(d),new r(d)}async authorizeDelegate(e,t){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var l2,j9=G(()=>{"use strict";g();Fo();yu();In();vr();Go();Ho();Qp();ti();rd();LR();Gs();Et();ur();l2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Sd.parse(t)}catch(u){return wt(u,400)}try{n.author!==void 0&&await yn(t.authorization,this.deps.didResolver)}catch(u){return wt(u,401)}let i={interface:ve.Records,isLatestBaseState:!0,...Ie.convertFilter(t.descriptor.filter)},a=Ie.convertDateSort(t.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[i],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let s=o[0];if(s.descriptor.method===me.Delete){let u=s,f=u.descriptor.recordId,p=await _t.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(p===void 0)return wt(new ie(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let h;try{h=await _t.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{h=p}let m=await _t.parse(h);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return wt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:p}}}let c=s;try{let u=await _t.parse(c);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return wt(u,401)}let l;if(c.encodedData!==void 0){let u=De.base64UrlToBytes(c.encodedData);l=Wt.fromBytes(u),delete c.encodedData}else{let u=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};l=u.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:l}};if(!await _t.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,t,n,i,a){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i);let{descriptor:o}=n.message;if(t.author!==e){if(o.published===!0)return;if(t.author!==void 0&&(t.author===o.recipient||t.author===n.author))return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let s=await rt.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Ln.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:s,messageStore:i})}else await bs.authorizeRead(e,t,n,i,a)}}}});var Ia,u2=G(()=>{"use strict";g();Pc();vr();dc();ti();rd();Oi();ms();Et();ur();ga();Ia=class r extends On{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ie.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ie(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&li(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&td(e.descriptor.filter.schema),kt.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??kt.getCurrentTimestamp(),filter:Ie.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};rr(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:t,authorization:i};return ye.validateJsonSchema(a),new r(a)}async authorizeDelegate(e){let t=Ir.parse(this.message.authorization.authorDelegatedGrant);await Ln.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var f2,M9=G(()=>{"use strict";g();Fo();mp();vr();Go();Qp();ti();u2();Gs();ed();Et();ur();f2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return wt(new ie(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Ia.parse(t)}catch(f){return wt(f,400)}let a=[],o=[];if(Ie.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[r.buildPublishedEventFilter(i)],o=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await yn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return wt(f,401)}i.author===e?(a=r.buildOwnerEventFilters(i),o=r.buildOwnerQueryFilters(i)):(a=r.buildNonOwnerEventFilters(i),o=r.buildNonOwnerQueryFilters(i))}let s=await ye.getCid(t),{cursor:c}=i.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,s,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ie&&f.code===re.EventLogProgressGap){let p=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:p!==void 0?{code:"ProgressGap",...p}:void 0}}return wt(f,500)}let l=await this.deps.eventLog.subscribe(e,s,n,{filters:a}),d,u;try{let{dateSort:f,pagination:p}=i.message.descriptor,h=r.convertDateSort(f),m=await this.deps.messageStore.query(e,o,h,p);d=m.messages,u=m.cursor;for(let y of d)if(!await _t.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),wt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:d,cursor:u}}static convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:Rt.Ascending};case Ut.CreatedDescending:return{dateCreated:Rt.Descending};case Ut.PublishedAscending:return{datePublished:Rt.Ascending};case Ut.PublishedDescending:return{datePublished:Rt.Descending};case Ut.UpdatedAscending:return{messageTimestamp:Rt.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:Rt.Descending};default:return{dateCreated:Rt.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...Ie.convertFilter(t),interface:ve.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return Ie.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),Ie.filterIncludesUnpublishedRecords(n)&&(Ie.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...Ie.convertFilter(n),author:e.author,interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ie.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ie.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ie.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...Ie.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...Ie.convertFilter(e.message.descriptor.filter),interface:ve.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return Ie.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),Ie.filterIncludesUnpublishedRecords(i)&&(Ie.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...Ie.convertFilter(i,n),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ie.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ie.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...Ie.convertFilter(i,n),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ie.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ie.shouldProtocolAuthorize(t.signaturePayload)&&await bs.authorizeQueryOrSubscribe(e,t,n,i)}}});var $y,qR=G(()=>{"use strict";g();my();yc();vr();ti();b0();Gs();ur();$y=class r{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:t,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=t,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:t}){let n={interface:ve.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await ye.getNewestMessage(i);if(!Ie.canPerformDeleteAgainstRecord(t,a))return;let o=await Ta.parse(t),s=await _t.getInitialWrite(i),c=o.constructIndexes(s),l=await ye.getCid(t);await this.messageStore.put(e,t,c),await this.stateIndex.insert(e,l,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:s},c,l),t.descriptor.prune&&await r.purgeRecordDescendants(e,t.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await r.deleteAllOlderMessagesButKeepInitialWrite(e,i,t,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:t}){let{protocol:n,protocolPath:i,messageTimestamp:a}=t.descriptor,o={interface:ve.Records,protocol:n,protocolPath:i},s=Ie.getParentContextFromOfContextId(t.contextId);if(s!==void 0&&s!==""){let d=nr.constructPrefixFilterAsRangeFilter(s);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),l=new Map;for(let d of c){let u;Ie.isRecordsWrite(d)?u=d.recordId:u=d.descriptor.recordId;let f=l.get(u);f!==void 0?f.push(d):l.set(u,[d])}for(let[d,u]of l){if(d===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await r.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,t,n,i){if(n.descriptor.method!==me.Write)return;let a=n;a.descriptor.dataSize<=lo.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,a){let o={interface:ve.Records,parentId:t},{messages:s}=await n.query(e,[o]),c=new Map;for(let l of s){let d;Ie.isRecordsWrite(l)?d=l.recordId:d=l.descriptor.recordId;let u=c.get(d);u?u.push(l):c.set(d,[l])}for(let l of c.keys())await r.purgeRecordDescendants(e,l,n,i,a);for(let l of c.keys())await r.purgeRecordMessages(e,c.get(l),n,i,a)}static async purgeRecordMessages(e,t,n,i,a){let o=t.filter(l=>l.descriptor.method===me.Write),s=await ye.getNewestMessage(o);await i.delete(e,s.recordId,s.descriptor.dataCid);let c=await Promise.all(t.map(l=>ye.getCid(l)));await a.delete(e,c),await Promise.all(c.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,a,o){let s=[];for(let c of t){if(await ye.isOlder(c,n)){await r.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ye.getCid(c);if(await i.delete(e,d),await _t.isInitialWrite(c)){let h=await(await _t.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await i.put(e,m,h)}else{let f=await ye.getCid(c);s.push(f)}}await o.delete(e,s)}}}});var p2,K9=G(()=>{"use strict";g();Fo();ll();yu();my();In();yc();vr();Go();Ho();Qp();ti();rd();Gs();a2();ed();qR();Et();ur();p2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,dataStream:n}){let i;try{i=await _t.parse(t),await bs.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(h){return wt(h,400)}try{await yn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(h){return wt(h,401)}let a={interface:ve.Records,recordId:t.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),s=await i.isInitialWrite(),c;if(!s)try{c=await _t.getInitialWrite(o),_t.verifyEqualityOfImmutableProperties(c,t)}catch(h){return wt(h,400)}try{await this.enforceSquashBackstop(e,t)}catch(h){return wt(h,409)}let l=await ye.getNewestMessage(o),d=!1,u;if(l===void 0||await ye.isNewer(t,l)?(d=!0,u=t):u=l,!d){let h=!1;if(l!==void 0&&n!==void 0&&await _t.isInitialWrite(l)){let y=!!l.encodedData,v=this.deps.dataStore?!!await this.deps.dataStore.get(e,i.message.recordId,t.descriptor.dataCid):!1;h=!y&&!v}if(!h)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(t.descriptor.protocol):void 0;try{if(l?.descriptor.method===me.Delete)throw new ie(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let h=!1,m=t;if(n!==void 0)m=await this.processMessageWithDataStream(e,t,n),h=!0;else if(!s){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),h=!0}let y=await i.constructIndexes(h);await this.deps.messageStore.put(e,m,y);let v=await ye.getCid(t);await this.deps.stateIndex.insert(e,v,y),this.deps.eventLog!==void 0&&h&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,v)}catch(h){if(h instanceof ie&&(h.code===re.RecordsWriteMissingEncodedDataInPrevious||h.code===re.RecordsWriteMissingDataInPrevious||h.code===re.RecordsWriteNotAllowedAfterDelete||h.code===re.RecordsWriteDataCidMismatch||h.code===re.RecordsWriteDataSizeMismatch||h.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(h.code)!==void 0))return wt(h,400);throw h}let p={status:s&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await $y.deleteAllOlderMessagesButKeepInitialWrite(e,o,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:sf.RecordsSquash,data:{tenant:e,message:t}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),p}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=De.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=lo.maxDataSizeAllowedToBeEncoded){let a=await Wt.toBytes(n),o=await mr.computeDagPbCidFromBytes(a);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,a.length);let s=t.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(t.descriptor.protocol):void 0;s?.validateRecord!==void 0&&s.validateRecord(t,a),i=await this.cloneAndAddEncodedData(t,a)}else{let[a,o]=Wt.duplicateDataStream(n,2);try{let[s,c]=await Promise.all([mr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,o)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,s,c.dataSize)}catch(s){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),s}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:a,dataSize:o}=t.descriptor;if(r.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=lo.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)i.encodedData=n.encodedData;else throw new ie(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ie(re.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,t,n,i){if(e!==n)throw new ie(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ie(re.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${t}`)}async enforceSquashBackstop(e,t){if(t.descriptor.protocol===void 0||t.descriptor.protocolPath===void 0)return;let n;try{n=await bs.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,d);return}let i=t.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let d=1;d<i.length&&a!==void 0;d++)a=a[i[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},s=Ie.getParentContextFromOfContextId(t.contextId);if(s!==void 0&&s!==""){let d=nr.constructPrefixFilterAsRangeFilter(s);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:Rt.Descending},{limit:1});if(c.length===0)return;let l=c[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ie(re.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${t.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${t.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,t,n){if(t.owner!==void 0&&t.owner!==e)throw new ie(re.RecordsWriteOwnerAndTenantMismatch,`Owner ${t.owner} must be the same as tenant ${e} when specified.`);if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.isSignedByOwnerDelegate&&await t.authorizeOwnerDelegate(n),t.owner===void 0){if(t.author===e)return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await rt.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Ln.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await bs.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function Mde(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var a=r.charAt(i),o=a.charCodeAt(0);if(t[o]!==255)throw new TypeError(a+" is ambiguous");t[o]=i}var s=r.length,c=r.charAt(0),l=Math.log(s)/Math.log(256),d=Math.log(256)/Math.log(s);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,y=0,v=0,w=h.length;v!==w&&h[v]===0;)v++,m++;for(var x=(w-v)*d+1>>>0,_=new Uint8Array(x);v!==w;){for(var A=h[v],D=0,N=x-1;(A!==0||D<y)&&N!==-1;N--,D++)A+=256*_[N]>>>0,_[N]=A%s>>>0,A=A/s>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,v++}for(var $=x-y;$!==x&&_[$]===0;)$++;for(var z=c.repeat(m);$<x;++$)z+=r.charAt(_[$]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var y=0,v=0;h[m]===c;)y++,m++;for(var w=(h.length-m)*l+1>>>0,x=new Uint8Array(w);h[m];){var _=t[h.charCodeAt(m)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<v)&&D!==-1;D--,A++)_+=s*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=A,m++}if(h[m]!==" "){for(var N=w-v;N!==w&&x[N]===0;)N++;for(var $=new Uint8Array(y+(w-N)),z=y;N!==w;)$[z++]=x[N++];return $}}}function p(h){var m=f(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}function Wde(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Jde(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function QR(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function w7(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tle;)e[t++]=r&255|q9,r/=128;for(;r&ele;)e[t++]=r&255|q9,r>>>=7;return e[t]=r|0,w7.bytes=t-n+1,e}function eC(r,n){var t=0,n=n||0,i=0,a=n,o,s=r.length;do{if(a>=s)throw eC.bytes=0,new RangeError("Could not decode varint");o=r[a++],t+=i<28?(o&z9)<<i:(o&z9)*Math.pow(2,i),i+=7}while(o>=nle);return eC.bytes=a-n,t}function v7(r){Object.keys(r).forEach(e=>{r[e]===void 0?delete r[e]:typeof r[e]=="object"&&v7(r[e])})}function $d(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function uh(r){if(!$d(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=_le[r[t]];return e}function x7(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function _C(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function V9(r){if(r>=Bl._0&&r<=Bl._9)return r-Bl._0;if(r>=Bl._A&&r<=Bl._F)return r-(Bl._A-10);if(r>=Bl._a&&r<=Bl._f)return r-(Bl._a-10)}function Hy(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,a=0;i<t;i++,a+=2){let o=V9(r.charCodeAt(a)),s=V9(r.charCodeAt(a+1));if(o===void 0||s===void 0){let c=r[a]+r[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[i]=o*16+s}return n}function ch(r){return _C(uh(r))}function Pf(r){if(!$d(r))throw new Error("Uint8Array expected");return _C(uh(Uint8Array.from(r).reverse()))}function Bd(r,e){return Hy(r.toString(16).padStart(e*2,"0"))}function Vy(r,e){return Bd(r,e).reverse()}function Ale(r){return Hy(x7(r))}function Wn(r,e,t){let n;if(typeof e=="string")try{n=Hy(e)}catch(a){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${a}`)}else if($d(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(`${r} expected ${t} bytes, got ${i}`);return n}function fh(...r){let e=0;for(let i=0;i<r.length;i++){let a=r[i];if(!$d(a))throw new Error("Uint8Array expected");e+=a.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let a=r[i];t.set(a,n),n+=a.length}return t}function Tle(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ile(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Dle(r){let e;for(e=0;r>P7;r>>=nE,e+=1);return e}function Rle(r,e){return r>>BigInt(e)&nE}function E7(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=zR(r),i=zR(r),a=0,o=()=>{n.fill(1),i.fill(0),a=0},s=(...d)=>t(i,n,...d),c=(d=zR())=>{i=s(W9([0]),d),n=s(),d.length!==0&&(i=s(W9([1]),d),n=s())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,u=[];for(;d<e;){n=s();let f=n.slice();u.push(f),d+=n.length}return fh(...u)};return(d,u)=>{o(),c(d);let f;for(;!(f=u(l()));)c();return o(),f}}function mh(r,e,t={}){let n=(i,a,o)=>{let s=$le[a];if(typeof s!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=r[i];if(!(o&&c===void 0)&&!s(c,r))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(t))n(i,a,!0);return r}function J9(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function Ble(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function S7(r,...e){if(!Ble(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function Ole(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J9(r.outputLen),J9(r.blockLen)}function F2(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function jle(r,e){S7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function k7(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function _7(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function TC(r){if(typeof r=="string"&&(r=_7(r)),!k7(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function A7(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!k7(i))throw new Error("Uint8Array expected");e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let a=r[n];t.set(a,i),i+=a.length}return t}function I7(r){let e=n=>r().update(TC(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function IC(r=32){if(FR&&typeof FR.getRandomValues=="function")return FR.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Kle(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),o=Number(t>>i&a),s=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+l,s,n)}function Xr(r,e){let t=r%e;return t>=yi?t:e+t}function C7(r,e,t){if(t<=yi||e<yi)throw new Error("Expected power/modulo > 0");if(t===gn)return yi;let n=gn;for(;e>yi;)e&gn&&(n=n*r%t),r=r*r%t,e>>=gn;return n}function Sn(r,e,t){let n=r;for(;e-- >yi;)n*=n,n%=t;return n}function nC(r,e){if(r===yi||e<=yi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Xr(r,e),n=e,i=yi,a=gn,o=gn,s=yi;for(;t!==yi;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}if(n!==gn)throw new Error("invert: does not exist");return Xr(i,e)}function Gle(r){let e=(r-gn)/nh,t,n,i;for(t=r-gn,n=0;t%nh===yi;t/=nh,n++);for(i=nh;i<r&&C7(i,e,r)!==r-gn;i++);if(n===1){let o=(r+gn)/rC;return function(s,c){let l=s.pow(c,o);if(!s.eql(s.sqr(l),c))throw new Error("Cannot find square root");return l}}let a=(t+gn)/nh;return function(o,s){if(o.pow(s,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,l=o.pow(o.mul(o.ONE,i),t),d=o.pow(s,a),u=o.pow(s,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let f=1;for(let h=o.sqr(u);f<c&&!o.eql(h,o.ONE);f++)h=o.sqr(h);let p=o.pow(l,gn<<BigInt(c-f-1));l=o.sqr(p),d=o.mul(d,p),u=o.mul(u,l),c=f}return d}}function Hle(r){if(r%rC===zle){let e=(r+gn)/rC;return function(t,n){let i=t.pow(n,e);if(!t.eql(t.sqr(i),n))throw new Error("Cannot find square root");return i}}if(r%Y9===Z9){let e=(r-Z9)/Y9;return function(t,n){let i=t.mul(n,nh),a=t.pow(i,e),o=t.mul(n,a),s=t.mul(t.mul(o,nh),a),c=t.mul(o,t.sub(s,t.ONE));if(!t.eql(t.sqr(c),n))throw new Error("Cannot find square root");return c}}return r%Fle,Gle(r)}function Jle(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Wle.reduce((n,i)=>(n[i]="function",n),e);return mh(r,t)}function Zle(r,e,t){if(t<yi)throw new Error("Expected power > 0");if(t===yi)return r.ONE;if(t===gn)return e;let n=r.ONE,i=e;for(;t>yi;)t&gn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=gn;return n}function Yle(r,e){let t=new Array(e.length),n=e.reduce((a,o,s)=>r.is0(o)?a:(t[s]=a,r.mul(a,o)),r.ONE),i=r.inv(n);return e.reduceRight((a,o,s)=>r.is0(o)?a:(t[s]=r.mul(a,t[s]),r.mul(a,o)),i),t}function $7(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function DC(r,e,t=!1,n={}){if(r<=yi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:a}=$7(r,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Hle(r),s=Object.freeze({ORDER:r,BITS:i,BYTES:a,MASK:AC(i),ZERO:yi,ONE:gn,create:c=>Xr(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return yi<=c&&c<r},is0:c=>c===yi,isOdd:c=>(c&gn)===gn,neg:c=>Xr(-c,r),eql:(c,l)=>c===l,sqr:c=>Xr(c*c,r),add:(c,l)=>Xr(c+l,r),sub:(c,l)=>Xr(c-l,r),mul:(c,l)=>Xr(c*l,r),pow:(c,l)=>Zle(s,c,l),div:(c,l)=>Xr(c*nC(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>nC(c,r),sqrt:n.sqrt||(c=>o(s,c)),invertBatch:c=>Yle(s,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Vy(c,a):Bd(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return t?Pf(c):ch(c)}});return Object.freeze(s)}function Xle(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function B7(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function O7(r){let e=B7(r);return e+Math.ceil(e/2)}function Qle(r,e,t=!1){let n=r.length,i=B7(e),a=O7(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=t?ch(r):Pf(r),s=Xr(o,e-gn)+gn;return t?Vy(s,i):Bd(s,i)}function j7(r,e){let t=(i,a)=>{let o=a.negate();return i?o:a},n=i=>{let a=Math.ceil(e/i)+1,o=2**(i-1);return{windows:a,windowSize:o}};return{constTimeNegate:t,unsafeLadder(i,a){let o=r.ZERO,s=i;for(;a>eue;)a&HR&&(o=o.add(s)),s=s.double(),a>>=HR;return o},precomputeWindow(i,a){let{windows:o,windowSize:s}=n(a),c=[],l=i,d=l;for(let u=0;u<o;u++){d=l,c.push(d);for(let f=1;f<s;f++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(i,a,o){let{windows:s,windowSize:c}=n(i),l=r.ZERO,d=r.BASE,u=BigInt(2**i-1),f=2**i,p=BigInt(i);for(let h=0;h<s;h++){let m=h*c,y=Number(o&u);o>>=p,y>c&&(y-=f,o+=HR);let v=m,w=m+Math.abs(y)-1,x=h%2!==0,_=y<0;y===0?d=d.add(t(x,a[v])):l=l.add(t(_,a[w]))}return{p:l,f:d}},wNAFCached(i,a,o,s){let c=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&a.set(i,s(l))),this.wNAF(c,l,o)}}}function RC(r){return Jle(r.Fp),mh(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$7(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function tue(r){let e=RC(r);mh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:i}=e;if(t){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function iue(r){let e=tue(r),{Fp:t}=e,n=e.toBytes||((h,m,y)=>{let v=m.toAffine();return fh(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(h=>{let m=h.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),v=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:v}});function a(h){let{a:m,b:y}=e,v=t.sqr(h),w=t.mul(v,h);return t.add(t.add(w,t.mul(h,m)),y)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function o(h){return typeof h=="bigint"&&Ul<h&&h<e.n}function s(h){if(!o(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof h!="bigint"){if($d(h)&&(h=uh(h)),typeof h!="string"||!m.includes(h.length))throw new Error("Invalid key");h=h.padStart(y*2,"0")}let x;try{x=typeof h=="bigint"?h:ch(Wn("private key",h,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof h}`)}return v&&(x=Xr(x,w)),s(x),x}let l=new Map;function d(h){if(!(h instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,v){if(this.px=m,this.py=y,this.pz=v,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(v==null||!t.isValid(v))throw new Error("z required")}static fromAffine(m){let{x:y,y:v}=m||{};if(!m||!t.isValid(y)||!t.isValid(v))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(v)?u.ZERO:new u(y,v,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(v=>v.pz));return m.map((v,w)=>v.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(Wn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let v=t.sqr(y),w=a(m);if(!t.eql(v,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:v,pz:w}=this,{px:x,py:_,pz:A}=m,D=t.eql(t.mul(y,A),t.mul(x,w)),N=t.eql(t.mul(v,A),t.mul(_,w));return D&&N}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,X9),{px:w,py:x,pz:_}=this,A=t.ZERO,D=t.ZERO,N=t.ZERO,$=t.mul(w,w),z=t.mul(x,x),L=t.mul(_,_),j=t.mul(w,x);return j=t.add(j,j),N=t.mul(w,_),N=t.add(N,N),A=t.mul(m,N),D=t.mul(v,L),D=t.add(A,D),A=t.sub(z,D),D=t.add(z,D),D=t.mul(A,D),A=t.mul(j,A),N=t.mul(v,N),L=t.mul(m,L),j=t.sub($,L),j=t.mul(m,j),j=t.add(j,N),N=t.add($,$),$=t.add(N,$),$=t.add($,L),$=t.mul($,j),D=t.add(D,$),L=t.mul(x,_),L=t.add(L,L),$=t.mul(L,j),A=t.sub(A,$),N=t.mul(L,z),N=t.add(N,N),N=t.add(N,N),new u(A,D,N)}add(m){d(m);let{px:y,py:v,pz:w}=this,{px:x,py:_,pz:A}=m,D=t.ZERO,N=t.ZERO,$=t.ZERO,z=e.a,L=t.mul(e.b,X9),j=t.mul(y,x),H=t.mul(v,_),Y=t.mul(w,A),R=t.add(y,v),C=t.add(x,_);R=t.mul(R,C),C=t.add(j,H),R=t.sub(R,C),C=t.add(y,w);let P=t.add(x,A);return C=t.mul(C,P),P=t.add(j,Y),C=t.sub(C,P),P=t.add(v,w),D=t.add(_,A),P=t.mul(P,D),D=t.add(H,Y),P=t.sub(P,D),$=t.mul(z,C),D=t.mul(L,Y),$=t.add(D,$),D=t.sub(H,$),$=t.add(H,$),N=t.mul(D,$),H=t.add(j,j),H=t.add(H,j),Y=t.mul(z,Y),C=t.mul(L,C),H=t.add(H,Y),Y=t.sub(j,Y),Y=t.mul(z,Y),C=t.add(C,Y),j=t.mul(H,C),N=t.add(N,j),j=t.mul(P,C),D=t.mul(R,D),D=t.sub(D,j),j=t.mul(R,H),$=t.mul(P,$),$=t.add($,j),new u(D,N,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return p.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,x)=>w.toAffine(v[x])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Ul)return y;if(s(m),m===Oa)return this;let{endo:v}=e;if(!v)return p.unsafeLadder(this,m);let{k1neg:w,k1:x,k2neg:_,k2:A}=v.splitScalar(m),D=y,N=y,$=this;for(;x>Ul||A>Ul;)x&Oa&&(D=D.add($)),A&Oa&&(N=N.add($)),$=$.double(),x>>=Oa,A>>=Oa;return w&&(D=D.negate()),_&&(N=N.negate()),N=new u(t.mul(N.px,v.beta),N.py,N.pz),D.add(N)}multiply(m){s(m);let y=m,v,w,{endo:x}=e;if(x){let{k1neg:_,k1:A,k2neg:D,k2:N}=x.splitScalar(y),{p:$,f:z}=this.wNAF(A),{p:L,f:j}=this.wNAF(N);$=p.constTimeNegate(_,$),L=p.constTimeNegate(D,L),L=new u(t.mul(L.px,x.beta),L.py,L.pz),v=$.add(L),w=z.add(j)}else{let{p:_,f:A}=this.wNAF(y);v=_,w=A}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,x=(A,D)=>D===Ul||D===Oa||!A.equals(w)?A.multiplyUnsafe(D):A.multiply(D),_=x(this,y).add(x(m,v));return _.is0()?void 0:_}toAffine(m){let{px:y,py:v,pz:w}=this,x=this.is0();m==null&&(m=x?t.ONE:t.inv(w));let _=t.mul(y,m),A=t.mul(v,m),D=t.mul(w,m);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(D,t.ONE))throw new Error("invZ was invalid");return{x:_,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Oa)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Oa?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return uh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=j7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function sue(r){let e=RC(r);return mh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function oue(r){let e=sue(r),{Fp:t,n}=e,i=t.BYTES+1,a=2*t.BYTES+1;function o(C){return Ul<C&&C<t.ORDER}function s(C){return Xr(C,n)}function c(C){return nC(C,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:f}=iue({...e,toBytes(C,P,S){let E=P.toAffine(),k=t.toBytes(E.x),I=fh;return S?I(Uint8Array.from([P.hasEvenY()?2:3]),k):I(Uint8Array.from([4]),k,t.toBytes(E.y))},fromBytes(C){let P=C.length,S=C[0],E=C.subarray(1);if(P===i&&(S===2||S===3)){let k=ch(E);if(!o(k))throw new Error("Point is not on curve");let I=u(k),K=t.sqrt(I),F=(K&Oa)===Oa;return(S&1)===1!==F&&(K=t.neg(K)),{x:k,y:K}}else if(P===a&&S===4){let k=t.fromBytes(E.subarray(0,t.BYTES)),I=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:k,y:I}}else throw new Error(`Point of length ${P} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),p=C=>uh(Bd(C,e.nByteLength));function h(C){let P=n>>Oa;return C>P}function m(C){return h(C)?s(-C):C}let y=(C,P,S)=>ch(C.slice(P,S));class v{constructor(P,S,E){this.r=P,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(P){let S=e.nByteLength;return P=Wn("compactSignature",P,S*2),new v(y(P,0,S),y(P,S,2*S))}static fromDER(P){let{r:S,s:E}=oh.toSig(Wn("DER",P));return new v(S,E)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(P){return new v(this.r,this.s,P)}recoverPublicKey(P){let{r:S,s:E,recovery:k}=this,I=N(Wn("msgHash",P));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let K=k===2||k===3?S+e.n:S;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let F=k&1?"03":"02",V=l.fromHex(F+p(K)),W=c(K),J=s(-I*W),Q=s(E*W),q=l.BASE.multiplyAndAddUnsafe(V,J,Q);if(!q)throw new Error("point at infinify");return q.assertValidity(),q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Hy(this.toDERHex())}toDERHex(){return oh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Hy(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let w={isValidPrivateKey(C){try{return d(C),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let C=O7(e.n);return Qle(e.randomBytes(C),e.n)},precompute(C=8,P=l.BASE){return P._setWindowSize(C),P.multiply(BigInt(3)),P}};function x(C,P=!0){return l.fromPrivateKey(C).toRawBytes(P)}function _(C){let P=$d(C),S=typeof C=="string",E=(P||S)&&C.length;return P?E===i||E===a:S?E===2*i||E===2*a:C instanceof l}function A(C,P,S=!0){if(_(C))throw new Error("first arg must be private key");if(!_(P))throw new Error("second arg must be public key");return l.fromHex(P).multiply(d(C)).toRawBytes(S)}let D=e.bits2int||function(C){let P=ch(C),S=C.length*8-e.nBitLength;return S>0?P>>BigInt(S):P},N=e.bits2int_modN||function(C){return s(D(C))},$=AC(e.nBitLength);function z(C){if(typeof C!="bigint")throw new Error("bigint expected");if(!(Ul<=C&&C<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Bd(C,e.nByteLength)}function L(C,P,S=j){if(["recovered","canonical"].some(se=>se in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:k}=e,{lowS:I,prehash:K,extraEntropy:F}=S;I==null&&(I=!0),C=Wn("msgHash",C),K&&(C=Wn("prehashed msgHash",E(C)));let V=N(C),W=d(P),J=[z(W),z(V)];if(F!=null){let se=F===!0?k(t.BYTES):F;J.push(Wn("extraEntropy",se))}let Q=fh(...J),q=V;function ee(se){let ne=D(se);if(!f(ne))return;let X=c(ne),le=l.BASE.multiply(ne).toAffine(),ue=s(le.x);if(ue===Ul)return;let pe=s(X*s(q+ue*W));if(pe===Ul)return;let xe=(le.x===ue?0:2)|Number(le.y&Oa),de=pe;return I&&h(pe)&&(de=m(pe),xe^=1),new v(ue,de,xe)}return{seed:Q,k2sig:ee}}let j={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function Y(C,P,S=j){let{seed:E,k2sig:k}=L(C,P,S),I=e;return E7(I.hash.outputLen,I.nByteLength,I.hmac)(E,k)}l.BASE._setWindowSize(8);function R(C,P,S,E=H){let k=C;if(P=Wn("msgHash",P),S=Wn("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:K}=E,F,V;try{if(typeof k=="string"||$d(k))try{F=v.fromDER(k)}catch(X){if(!(X instanceof oh.Err))throw X;F=v.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:X,s:le}=k;F=new v(X,le)}else throw new Error("PARSE");V=l.fromHex(S)}catch(X){if(X.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&F.hasHighS())return!1;K&&(P=e.hash(P));let{r:W,s:J}=F,Q=N(P),q=c(J),ee=s(Q*q),se=s(W*q),ne=l.BASE.multiplyAndAddUnsafe(V,ee,se)?.toAffine();return ne?s(ne.x)===W:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:A,sign:Y,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function aue(r){return{hash:r,hmac:(e,...t)=>K7(r,e,A7(...t)),randomBytes:IC}}function N7(r,e){let t=n=>oue({...r,...aue(n)});return Object.freeze({...t(e),create:t})}function due(r){let e=U7,t=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),o=BigInt(23),s=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Sn(d,t,e)*d%e,f=Sn(u,t,e)*d%e,p=Sn(f,iC,e)*l%e,h=Sn(p,i,e)*p%e,m=Sn(h,a,e)*h%e,y=Sn(m,s,e)*m%e,v=Sn(y,c,e)*y%e,w=Sn(v,s,e)*m%e,x=Sn(w,t,e)*d%e,_=Sn(x,o,e)*h%e,A=Sn(_,n,e)*l%e,D=Sn(A,iC,e);if(!sC.eql(sC.sqr(D),r))throw new Error("Cannot find square root");return D}function lue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function L7(r,...e){if(!lue(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function tq(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function uue(r,e){L7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function fue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function q7(r){return typeof r=="string"&&(r=fue(r)),L7(r),r}function hue(r){let e=n=>r().update(q7(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function mue(r=32){if(E2&&typeof E2.getRandomValues=="function")return E2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function yue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),o=Number(t>>i&a),s=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+l,s,n)}function xue(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),a={};for(let o of i)a[o]=e(n[o]);return a}return n},t=e(r);return JSON.stringify(t)}function _r(r){return Sue(this,arguments,void 0,function*({jwk:e}){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);v7(n);let i=xue(n),a=st.string(i).toUint8Array(),o=yield z7.digest({data:a});return st.uint8Array(o).toBase64Url()})}function dh(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="EC"||typeof r.d!="string"||typeof r.x!="string")}function CC(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r)||"d"in r||r.kty!=="EC"||typeof r.x!="string")}function zl(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="OKP"||typeof r.d!="string"||typeof r.x!="string")}function $C(r){return!(!r||typeof r!="object"||"d"in r||!("kty"in r&&"crv"in r&&"x"in r)||r.kty!=="OKP"||typeof r.x!="string")}function kue(r){if(!r||typeof r!="object")return!1;switch(r.kty){case"EC":case"OKP":case"RSA":return"d"in r;case"oct":return"k"in r;default:return!1}}function G7(r,e=!1){return e?{h:Number(r&m2),l:Number(r>>oC&m2)}:{h:Number(r>>oC&m2)|0,l:Number(r&m2)|0}}function Rue(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:a,l:o}=G7(r[i],e);[t[i],n[i]]=[a,o]}return[t,n]}function Gue(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function ife(r){let e=RC(r);return mh(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function BC(r){let e=ife(r),{Fp:t,n,prehash:i,hash:a,randomBytes:o,nByteLength:s,h:c}=e,l=y2<<BigInt(s*8)-Vo,d=t.create,u=e.uvRatio||((S,E)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(E))}}catch{return{isValid:!1,value:_c}}}),f=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,k)=>{if(E.length||k)throw new Error("Contexts/pre-hash are not supported");return S}),h=S=>typeof S=="bigint"&&_c<S,m=(S,E)=>h(S)&&h(E)&&S<E,y=S=>S===_c||m(S,l);function v(S,E){if(m(S,E))return S;throw new Error(`Expected valid scalar < ${E}, got ${typeof S} ${S}`)}function w(S){return S===_c?S:v(S,n)}let x=new Map;function _(S){if(!(S instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(E,k,I,K){if(this.ex=E,this.ey=k,this.ez=I,this.et=K,!y(E))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(K))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof A)throw new Error("extended point not allowed");let{x:k,y:I}=E||{};if(!y(k)||!y(I))throw new Error("invalid affine point");return new A(k,I,Vo,d(k*I))}static normalizeZ(E){let k=t.invertBatch(E.map(I=>I.ez));return E.map((I,K)=>I.toAffine(k[K])).map(A.fromAffine)}_setWindowSize(E){this._WINDOW_SIZE=E,x.delete(this)}assertValidity(){let{a:E,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:K,ez:F,et:V}=this,W=d(I*I),J=d(K*K),Q=d(F*F),q=d(Q*Q),ee=d(W*E),se=d(Q*d(ee+J)),ne=d(q+d(k*d(W*J)));if(se!==ne)throw new Error("bad point: equation left != right (1)");let X=d(I*K),le=d(F*V);if(X!==le)throw new Error("bad point: equation left != right (2)")}equals(E){_(E);let{ex:k,ey:I,ez:K}=this,{ex:F,ey:V,ez:W}=E,J=d(k*W),Q=d(F*K),q=d(I*W),ee=d(V*K);return J===Q&&q===ee}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:E}=e,{ex:k,ey:I,ez:K}=this,F=d(k*k),V=d(I*I),W=d(y2*d(K*K)),J=d(E*F),Q=k+I,q=d(d(Q*Q)-F-V),ee=J+V,se=ee-W,ne=J-V,X=d(q*se),le=d(ee*ne),ue=d(q*ne),pe=d(se*ee);return new A(X,le,pe,ue)}add(E){_(E);let{a:k,d:I}=e,{ex:K,ey:F,ez:V,et:W}=this,{ex:J,ey:Q,ez:q,et:ee}=E;if(k===BigInt(-1)){let Bt=d((F-K)*(Q+J)),_e=d((F+K)*(Q-J)),at=d(_e-Bt);if(at===_c)return this.double();let It=d(V*y2*ee),$t=d(W*y2*q),Ht=$t+It,T=_e+Bt,M=$t-It,U=d(Ht*at),te=d(T*M),ce=d(Ht*M),ge=d(at*T);return new A(U,te,ge,ce)}let se=d(K*J),ne=d(F*Q),X=d(W*I*ee),le=d(V*q),ue=d((K+F)*(J+Q)-se-ne),pe=le-X,xe=le+X,de=d(ne-k*se),Pe=d(ue*pe),Ne=d(xe*de),He=d(ue*de),Je=d(pe*xe);return new A(Pe,Ne,Je,He)}subtract(E){return this.add(E.negate())}wNAF(E){return $.wNAFCached(this,x,E,A.normalizeZ)}multiply(E){let{p:k,f:I}=this.wNAF(v(E,n));return A.normalizeZ([k,I])[0]}multiplyUnsafe(E){let k=w(E);return k===_c?N:this.equals(N)||k===Vo?this:this.equals(D)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(E){let{ex:k,ey:I,ez:K}=this,F=this.is0();E==null&&(E=F?rfe:t.inv(K));let V=d(k*E),W=d(I*E),J=d(K*E);if(F)return{x:_c,y:Vo};if(J!==Vo)throw new Error("invZ was invalid");return{x:V,y:W}}clearCofactor(){let{h:E}=e;return E===Vo?this:this.multiplyUnsafe(E)}static fromHex(E,k=!1){let{d:I,a:K}=e,F=t.BYTES;E=Wn("pointHex",E,F);let V=E.slice(),W=E[F-1];V[F-1]=W&-129;let J=Pf(V);J===_c||(k?v(J,l):v(J,t.ORDER));let Q=d(J*J),q=d(Q-Vo),ee=d(I*Q-K),{isValid:se,value:ne}=u(q,ee);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let X=(ne&Vo)===Vo,le=(W&128)!==0;if(!k&&ne===_c&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==X&&(ne=d(-ne)),A.fromAffine({x:ne,y:J})}static fromPrivateKey(E){return j(E).point}toRawBytes(){let{x:E,y:k}=this.toAffine(),I=Vy(k,t.BYTES);return I[I.length-1]|=E&Vo?128:0,I}toHex(){return uh(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,Vo,d(e.Gx*e.Gy)),A.ZERO=new A(_c,Vo,Vo,_c);let{BASE:D,ZERO:N}=A,$=j7(A,s*8);function z(S){return Xr(S,n)}function L(S){return z(Pf(S))}function j(S){let E=s;S=Wn("private key",S,E);let k=Wn("hashed private key",a(S),2*E),I=f(k.slice(0,E)),K=k.slice(E,2*E),F=L(I),V=D.multiply(F),W=V.toRawBytes();return{head:I,prefix:K,scalar:F,point:V,pointBytes:W}}function H(S){return j(S).pointBytes}function Y(S=new Uint8Array,...E){let k=fh(...E);return L(a(p(k,Wn("context",S),!!i)))}function R(S,E,k={}){S=Wn("message",S),i&&(S=i(S));let{prefix:I,scalar:K,pointBytes:F}=j(E),V=Y(k.context,I,S),W=D.multiply(V).toRawBytes(),J=Y(k.context,W,F,S),Q=z(V+J*K);w(Q);let q=fh(W,Vy(Q,t.BYTES));return Wn("result",q,s*2)}let C=nfe;function P(S,E,k,I=C){let{context:K,zip215:F}=I,V=t.BYTES;S=Wn("signature",S,2*V),E=Wn("message",E),i&&(E=i(E));let W=Pf(S.slice(V,2*V)),J,Q,q;try{J=A.fromHex(k,F),Q=A.fromHex(S.slice(0,V),F),q=D.multiplyUnsafe(W)}catch{return!1}if(!F&&J.isSmallOrder())return!1;let ee=Y(K,Q.toRawBytes(),J.toRawBytes(),E);return Q.add(J.multiplyUnsafe(ee)).subtract(q).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:P,ExtendedPoint:A,utils:{getExtendedPublicKey:j,randomPrivateKey:()=>o(t.BYTES),precompute(S=8,E=A.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}function sfe(r){return mh(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function ofe(r){let e=sfe(r),{P:t}=e,n=x=>Xr(x,t),i=e.montgomeryBits,a=Math.ceil(i/8),o=e.nByteLength,s=e.adjustScalarBytes||(x=>x),c=e.powPminus2||(x=>C7(x,t-BigInt(2),t));function l(x,_,A){let D=n(x*(_-A));return _=n(_-D),A=n(A+D),[_,A]}function d(x){if(typeof x=="bigint"&&E0<=x&&x<t)return x;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(x,_){let A=d(x),D=d(_),N=A,$=WR,z=E0,L=A,j=WR,H=E0,Y;for(let C=BigInt(i-1);C>=E0;C--){let P=D>>C&WR;H^=P,Y=l(H,$,L),$=Y[0],L=Y[1],Y=l(H,z,j),z=Y[0],j=Y[1],H=P;let S=$+z,E=n(S*S),k=$-z,I=n(k*k),K=E-I,F=L+j,V=L-j,W=n(V*S),J=n(F*k),Q=W+J,q=W-J;L=n(Q*Q),j=n(N*n(q*q)),$=n(E*I),z=n(K*(E+n(u*K)))}Y=l(H,$,L),$=Y[0],L=Y[1],Y=l(H,z,j),z=Y[0],j=Y[1];let R=c(z);return n($*R)}function p(x){return Vy(n(x),a)}function h(x){let _=Wn("u coordinate",x,a);return o===32&&(_[31]&=127),Pf(_)}function m(x){let _=Wn("scalar",x),A=_.length;if(A!==a&&A!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${A}`);return Pf(s(_))}function y(x,_){let A=h(_),D=m(x),N=f(A,D);if(N===E0)throw new Error("Invalid private or public key received");return p(N)}let v=p(e.Gu);function w(x){return y(x,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(x,_)=>y(x,_),getPublicKey:x=>w(x),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function V7(r){let e=W0,t=r*r%e*r%e,n=Sn(t,aC,e)*t%e,i=Sn(n,afe,e)*r%e,a=Sn(i,cfe,e)*i%e,o=Sn(a,sq,e)*a%e,s=Sn(o,dfe,e)*o%e,c=Sn(s,lfe,e)*s%e,l=Sn(c,oq,e)*c%e,d=Sn(l,oq,e)*c%e,u=Sn(d,sq,e)*a%e;return{pow_p_5_8:Sn(u,aC,e)*r%e,b2:t}}function W7(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ufe(r,e){let t=W0,n=Xr(e*e*e,t),i=Xr(n*n*e,t),a=V7(r*i).pow_p_5_8,o=Xr(r*n*a,t),s=Xr(e*o*o,t),c=o,l=Xr(o*iq,t),d=s===r,u=s===Xr(-r,t),f=s===Xr(-r*iq,t);return d&&(o=c),(u||f)&&(o=l),Vle(o,t)&&(o=Xr(-o,t)),{isValid:d||u,value:o}}function J7(r,e,t){if(e.length>255)throw new Error("Context is too big");return A7(_7("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function ffe(r){let{y:e}=th.ExtendedPoint.fromHex(r),t=BigInt(1);return Na.toBytes(Na.create((t+e)*Na.inv(t-e)))}function pfe(r){let e=J0.hash(r.subarray(0,32));return J0.adjustScalarBytes(e).subarray(0,32)}function Efe(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(r)?"Array":r instanceof Uint8Array?"Uint8Array":r.constructor===Object?"Object":Sfe(r)||"Object"}function Sfe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(xfe.includes(e))return e}function G2(r){return tb&&globalThis.Buffer.isBuffer(r)}function Z7(r){return r instanceof Uint8Array?G2(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function Y7(r,e){if(G2(r)&&G2(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function aq(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function Xy(r,e,t){if(r.length-e<t)throw new Error(`${kn} not enough data for type`)}function yh(r,e,t){Xy(r,e,1);let n=r[e];if(t.strict===!0&&n<ss[0])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function gh(r,e,t){Xy(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ss[1])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function wh(r,e,t){Xy(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ss[2])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function vh(r,e,t){Xy(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&a<ss[3])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(t.allowBigInt===!0)return a;throw new Error(`${kn} integers outside of the safe integer range are not supported`)}function Bfe(r,e,t,n){return new tt(Se.uint,yh(r,e+1,n),2)}function Ofe(r,e,t,n){return new tt(Se.uint,gh(r,e+1,n),3)}function jfe(r,e,t,n){return new tt(Se.uint,wh(r,e+1,n),5)}function Mfe(r,e,t,n){return new tt(Se.uint,vh(r,e+1,n),9)}function bh(r,e){return La(r,0,e.value)}function La(r,e,t){if(t<ss[0]){let n=Number(t);r.push([e|n])}else if(t<ss[1]){let n=Number(t);r.push([e|24,n])}else if(t<ss[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ss[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ss[4]){let i=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=a&255,a=a>>8,i[7]=a&255,a=a>>8,i[6]=a&255,a=a>>8,i[5]=a&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${kn} encountered BigInt larger than allowable range`)}}function Kfe(r,e,t,n){return new tt(Se.negint,-1-yh(r,e+1,n),2)}function Nfe(r,e,t,n){return new tt(Se.negint,-1-gh(r,e+1,n),3)}function Ufe(r,e,t,n){return new tt(Se.negint,-1-wh(r,e+1,n),5)}function Lfe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new tt(Se.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${kn} integers outside of the safe integer range are not supported`);return new tt(Se.negint,OC-BigInt(i),9)}function jC(r,e){let t=e.value,n=typeof t=="bigint"?t*OC-ez:t*-1-1;La(r,e.type.majorEncoded,n)}function nb(r,e,t,n){Xy(r,e,t+n);let i=r.slice(e+t,e+t+n);return new tt(Se.bytes,i,t+n)}function qfe(r,e,t,n){return nb(r,e,1,t)}function zfe(r,e,t,n){return nb(r,e,2,yh(r,e+1,n))}function Ffe(r,e,t,n){return nb(r,e,3,gh(r,e+1,n))}function Gfe(r,e,t,n){return nb(r,e,5,wh(r,e+1,n))}function Hfe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer bytes lengths not supported`);return nb(r,e,9,i)}function H2(r){return r.encodedBytes===void 0&&(r.encodedBytes=Se.equals(r.type,Se.string)?Tfe(r.value):r.value),r.encodedBytes}function iE(r,e){let t=H2(e);La(r,e.type.majorEncoded,t.length),r.push(t)}function Vfe(r,e){return r.length<e.length?-1:r.length>e.length?1:Y7(r,e)}function Jfe(r,e,t){if(t-e<Wfe){let n="";for(let i=e;i<t;i++){let a=r[i];if(a&128)return cq.decode(r.subarray(e,t));n+=String.fromCharCode(a)}return n}return cq.decode(r.subarray(e,t))}function ib(r,e,t,n,i){let a=t+n;Xy(r,e,a);let o=new tt(Se.string,Jfe(r,e+t,e+a),a);return i.retainStringBytes===!0&&(o.byteValue=r.slice(e+t,e+a)),o}function Zfe(r,e,t,n){return ib(r,e,1,t,n)}function Yfe(r,e,t,n){return ib(r,e,2,yh(r,e+1,n),n)}function Xfe(r,e,t,n){return ib(r,e,3,gh(r,e+1,n),n)}function Qfe(r,e,t,n){return ib(r,e,5,wh(r,e+1,n),n)}function epe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer string lengths not supported`);return ib(r,e,9,i,n)}function Qy(r,e,t,n){return new tt(Se.array,n,t)}function rpe(r,e,t,n){return Qy(r,e,1,t)}function npe(r,e,t,n){return Qy(r,e,2,yh(r,e+1,n))}function ipe(r,e,t,n){return Qy(r,e,3,gh(r,e+1,n))}function spe(r,e,t,n){return Qy(r,e,5,wh(r,e+1,n))}function ope(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer array lengths not supported`);return Qy(r,e,9,i)}function ape(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Qy(r,e,1,1/0)}function MC(r,e){La(r,Se.array.majorEncoded,e.value)}function eg(r,e,t,n){return new tt(Se.map,n,t)}function cpe(r,e,t,n){return eg(r,e,1,t)}function dpe(r,e,t,n){return eg(r,e,2,yh(r,e+1,n))}function lpe(r,e,t,n){return eg(r,e,3,gh(r,e+1,n))}function upe(r,e,t,n){return eg(r,e,5,wh(r,e+1,n))}function fpe(r,e,t,n){let i=vh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer map lengths not supported`);return eg(r,e,9,i)}function ppe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return eg(r,e,1,1/0)}function KC(r,e){La(r,Se.map.majorEncoded,e.value)}function hpe(r,e,t,n){return new tt(Se.tag,t,1)}function mpe(r,e,t,n){return new tt(Se.tag,yh(r,e+1,n),2)}function ype(r,e,t,n){return new tt(Se.tag,gh(r,e+1,n),3)}function gpe(r,e,t,n){return new tt(Se.tag,wh(r,e+1,n),5)}function wpe(r,e,t,n){return new tt(Se.tag,vh(r,e+1,n),9)}function NC(r,e){La(r,Se.tag.majorEncoded,e.value)}function vpe(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${kn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new tt(Se.null,null,1):new tt(Se.undefined,void 0,1)}function bpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return new tt(Se.break,void 0,1)}function UC(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${kn} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${kn} Infinity values are not supported`)}return new tt(Se.float,r,e)}function Ppe(r,e,t,n){return UC(qC(r,e+1),3,n)}function xpe(r,e,t,n){return UC(zC(r,e+1),5,n)}function Epe(r,e,t,n){return UC(cz(r,e+1),9,n)}function LC(r,e,t){let n=e.value;if(n===!1)r.push([Se.float.majorEncoded|tz]);else if(n===!0)r.push([Se.float.majorEncoded|rz]);else if(n===null)r.push([Se.float.majorEncoded|nz]);else if(n===void 0)r.push([Se.float.majorEncoded|iz]);else{let i,a=!1;(!t||t.float64!==!0)&&(oz(n),i=qC(Ac,1),n===i||Number.isNaN(n)?(Ac[0]=249,r.push(Ac.slice(0,3)),a=!0):(az(n),i=zC(Ac,1),n===i&&(Ac[0]=250,r.push(Ac.slice(0,5)),a=!0))),a||(Spe(n),i=cz(Ac,1),Ac[0]=251,r.push(Ac.slice(0,9)))}}function oz(r){if(r===1/0)$a.setUint16(0,31744,!1);else if(r===-1/0)$a.setUint16(0,64512,!1);else if(Number.isNaN(r))$a.setUint16(0,32256,!1);else{$a.setFloat32(0,r);let e=$a.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)$a.setUint16(0,31744,!1);else if(t===0)$a.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?$a.setUint16(0,0):i<-14?$a.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$a.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function qC(r,e){if(r.length-e<2)throw new Error(`${kn} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,t&32768?-a:a}function az(r){$a.setFloat32(0,r,!1)}function zC(r,e){if(r.length-e<4)throw new Error(`${kn} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Spe(r){$a.setFloat64(0,r,!1)}function cz(r,e){if(r.length-e<8)throw new Error(`${kn} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function yr(r,e,t){throw new Error(`${kn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function sE(r){return()=>{throw new Error(`${kn} ${r}`)}}function kpe(r){switch(r.type){case Se.false:return Kl([244]);case Se.true:return Kl([245]);case Se.null:return Kl([246]);case Se.bytes:return r.value.length?void 0:Kl([64]);case Se.string:return r.value===""?Kl([96]):void 0;case Se.array:return r.value===0?Kl([128]):void 0;case Se.map:return r.value===0?Kl([160]):void 0;case Se.uint:return r.value<24?Kl([Number(r.value)]):void 0;case Se.negint:if(r.value>=-24)return Kl([31-Number(r.value)])}}function Ape(){let r=[];return r[Se.uint.major]=bh,r[Se.negint.major]=jC,r[Se.bytes.major]=iE,r[Se.string.major]=tpe,r[Se.array.major]=MC,r[Se.map.major]=KC,r[Se.tag.major]=NC,r[Se.float.major]=LC,r}function S2(r,e={},t){let n=Efe(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Ef[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let a=Ef[n];if(!a)throw new Error(`${Q7} unsupported type: ${n}`);return a(r,n,e,t)}function Dpe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Rpe(r,e){if(r[0]instanceof tt&&e[0]instanceof tt){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=lq(t.value)),n._keyBytes||(n._keyBytes=lq(n.value)),Y7(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function lq(r){return Cpe(r,Tpe,_pe)}function lz(r,e,t,n){if(Array.isArray(e))for(let i of e)lz(r,i,t,n);else t[e.type.major](r,e,n)}function Cpe(r,e,t,n){let i=n instanceof Uint8Array,a=i?new $fe(n):Ipe,o=S2(r,t);if(!Array.isArray(o)&&t.quickEncodeToken){let s=t.quickEncodeToken(o);if(s)return i?(a.push(s),a.toBytes()):s;let c=e[o.type.major];if(c.encodedSize){let l=c.encodedSize(o,t);if(i||(a=new X7(l)),c(a,o,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return i?a.toBytes():Z7(a.chunks[0])}}return a.reset(),lz(a,o,e,t),a.toBytes(!0)}function Zs(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function $pe({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function Bpe({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=oE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await _r({jwk:e})===await _r({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function oE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(V2)??[]),Object.keys(tE).forEach(t=>{e.push(...r[t]?.filter(V2)??[])}),e}function uz({didDocument:r}){let e=oE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function fz({didDocument:r,methodId:e}){let t=[];return Object.keys(tE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],a=Zs(e);i.some(o=>{let s=Zs(o)===a,c=V2(o)&&Zs(o.id)===a;return s||c})&&t.push(n)}}),t}function pz(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function Ope(r){return!(!pz(r)||r.type!=="DecentralizedWebNode")}function V2(r){return!(!r||typeof r!="object"||r===null||!("id"in r&&"type"in r&&"controller"in r)||typeof r.id!="string"||typeof r.type!="string"||typeof r.controller!="string")}function Ph(r){return!(!r||typeof r!="object"||r===null)&&"uri"in r&&"document"in r&&"metadata"in r&&(!("keyManager"in r)||r.keyManager===void 0)}function hz({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=Ua.addPrefix({code:e,data:r,name:t}),i=st.uint8Array(n).toBase58Btc();return st.base58Btc(i).toMultibase()}function mz({multibaseKeyId:r}){try{let e=st.multibase(r).toBase58Btc(),t=st.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Ua.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new nt("invalidDid",`Invalid multibase identifier: ${r}`)}}function ob(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function Pz(r){return ArrayBuffer.isView(r)?"arraybufferview":Array.isArray(r)?"array":r instanceof Number?"number":r instanceof Boolean?"boolean":r instanceof Set?"set":r instanceof Map?"map":r instanceof String?"string":r instanceof ArrayBuffer?"arraybuffer":typeof r}function br(r,e,t){let n=[],i=null;return br._encode(n,r),i=Mpe(n),br.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function Sz(r,e,t){let n=0,i=1;for(let a=e;a<t;a++){let o=r[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){i=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*i}function bt(r,e,t,n){return r==null||r.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof t!="number"&&n==null&&(n=t,t=void 0),bt.position=0,bt.encoding=n||null,bt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):Fl(r),bt.bytes=bt.data.length,bt.next())}function Vpe(r){let e=2;for(let t of r)e+=cE(t);return e}function Wpe(r){let e=2;for(let[t,n]of r){let i=Fl(t).byteLength;e+=ob(i)+1+i,e+=cE(n)}return e}function Jpe(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=Fl(t[n]).byteLength;e+=ob(i)+1+i,e+=cE(r[t[n]])}return e}function Zpe(r){let e=Fl(r).byteLength;return ob(e)+1+e}function Ype(r){let e=r.byteLength-r.byteOffset;return ob(e)+1+e}function cE(r){if(r==null)return 0;let e=Pz(r);switch(e){case"arraybufferview":return Ype(r);case"string":return Zpe(r);case"array":case"set":return Vpe(r);case"number":return 1+ob(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Jpe(r);case"map":return Wpe(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function Az(r){if(Cd.isFormat(r))return Cd.size;if(xf.isFormat(r))return xf.size;throw Error(`Invalid ip address: ${r}`)}function the(r){return Az(r)===Cd.size?1:2}function rhe(r,e,t){t=~~t;let n=Az(r);return typeof e=="function"&&(e=e(t+n)),n===Cd.size?Cd.encode(r,e,t):xf.encode(r,e,t)}function nhe(r,e,t){if(e=~~e,t=t||r.length-e,t===Cd.size)return Cd.decode(r,e,t);if(t===xf.size)return xf.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${Cd.size} for v4 or ${xf.size} for v6.`)}function dE(r){switch(r){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+r}function Z0(r){switch(r.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}function ihe(r){switch(r){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+r}function she(r){switch(r){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+r}function Tz(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r}function Iz(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function ohe(r){switch(r){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return r<0?null:`OPTION_${r}`}function Eq(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function Dz(r){let e=0,t=r.length;for(let n=0;n<t;n+=1){let i=r.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let a=n+1;a===t||i>=56320||(r.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Y0(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(Dz(r)+t));let i=t;for(let a=0;a<n;a+=1){let o=r.charCodeAt(a);if(o<=127)e[i++]=o;else if(o<=2047)e[i++]=192|(o&1984)>>6,e[i++]=128|o&63;else if((o&63488)!==55296)e[i++]=224|(o&61440)>>12,e[i++]=128|(o&4032)>>6,e[i++]=128|o&63;else{let s=a+1;if(s===n||o>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let c=r.charCodeAt(s);(c&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=s,o=65536|(o&1023)<<10|c&1023,e[i++]=240|(o&1835008)>>18,e[i++]=128|(o&258048)>>12,e[i++]=128|(o&4032)>>6,e[i++]=128|o&63)}}}return Y0.bytes=i-t,e}function ab(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let a=r[i++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|r[i++]&63;else if(a>239&&a<365){o=((a&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let s=55296|o>>10&1023;n+=String.fromCharCode(s),o=56320|o&1023}else o=(a&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(o)}return ab.bytes=t-e,n}function Sf(r){return typeof r=="string"?Dz(r):r.byteLength}function VC(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):Y0(r)}function WC(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return Y0(e,r,t),Y0.bytes}function ahe(r,e,t){let n="";for(let i=e;i<t;){let a=r[i++];n+=Rz[a]}return n}function Sq(r){return r.length>>>1}function che(r,e,t,n){let i=0;for(;t<n;){let a=e.substr(i,2),o=R0[a];if(o===void 0)return;r[t++]=o,i+=2}return r}function Xo(r,e,t,n,i){return t<0&&(n-=t,t=0),n<0&&(n=0),i<0?new Uint8Array(0):t>=e.length||n>=i?0:fhe(r,e,t,n,i)}function fhe(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let a=i-n,o=r.length-n;return a>o&&(a=o),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,a)),e.set(r,t),a}function Hr({bytes:r=0,encode:e,decode:t,encodingLength:n}){return e.bytes=r,t.bytes=r,{encode:e,decode:t,encodingLength:n||(()=>r)}}function lC(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function ZR(r){switch(r.toUpperCase()){case"A":return $z;case"PTR":return zy;case"CNAME":return zy;case"DNAME":return zy;case"TXT":return T2;case"NULL":return I2;case"AAAA":return $2;case"SRV":return R2;case"HINFO":return D2;case"CAA":return vf;case"NS":return _2;case"SOA":return A2;case"MX":return C2;case"OPT":return bf;case"DNSKEY":return Rd;case"RRSIG":return C0;case"RP":return $0;case"NSEC":return B0;case"NSEC3":return O0;case"SSHFP":return Uy;case"DS":return j0}return k2}function W2(r,e){if(r.questions)throw new Error("Only one .question object expected instead of a .questions array!");let t=Object.assign({type:e},r);return t.question&&(t.questions=[t.question],delete t.question),t}function Bz(r){let e=Y2(r),t=new Uint8Array(2+e.byteLength);return ot(t,e.byteLength),Xo(e,t,2,0,e.length),Bz.bytes=t.byteLength,t}function Oz(r){let e=qt(r,0);if(r.byteLength<e+2)return null;let t=uC(r.slice(2));return Oz.bytes=uC.bytes,t}function Ly(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function M0(r,e,t,n){for(let i=0;i<r.length;i++)e.encode(r[i],t,n),n+=e.encode.bytes;return n}function g2(r,e,t,n){for(let i=0;i<r.length;i++)r[i]=e.decode(t,n),n+=e.decode.bytes;return n}function jz(r,e){let t=st.uint8Array(r).toBase32Z();return new URL(t,e).href}async function whe({gatewayUri:r,publicKeyBytes:e}){let t=st.uint8Array(e).toBase32Z(),n=jz(e,r),i;try{if(i=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!i.ok)throw new nt("notFound",`Pkarr record not found for: ${t}`)}catch(o){throw o instanceof nt?o:new nt("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await i.arrayBuffer();if(!a)throw new nt("notFound",`Pkarr record not found for: ${t}`);if(a.byteLength<72)throw new nt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new nt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function vhe({gatewayUri:r,bep44Message:e}){let t=st.uint8Array(e.k).toBase32Z(),n=jz(e.k,r),i=new Uint8Array(e.v.length+72);i.set(e.sig,0),new DataView(i.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),i.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:i,signal:AbortSignal.timeout(3e4)})}catch(o){throw new nt("internalError",`Failed to put Pkarr record for identifier ${t}: ${o.message}`)}return a.ok}async function bhe({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=Y2(r),a=_z.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new nt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await t.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:i}}async function Phe({bep44Message:r}){let e=await is.bytesToPublicKey({publicKeyBytes:r.k}),t=_z.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await is.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new nt("invalidSignature","Invalid signature for DHT BEP44 message");return uC(r.v)}async function Kz({didUri:r}){let e=JC({didUri:r});return await is.bytesToPublicKey({publicKeyBytes:e})}function JC({didUri:r}){let e=Jn.parse(r);if(!e)throw new nt("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==Mz)throw new nt("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=st.base32Z(e.id).toUint8Array()}catch{throw new nt("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new nt("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function xhe({identityKey:r}){let e=await is.publicKeyToBytes({publicKey:r}),t=st.uint8Array(e).toBase32Z();return`did:${Mz}:${t}`}function ZC(r){let e={Ed25519:is,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await xs.publicKeyToBytes({publicKey:t});return await xs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:xs.bytesToPublicKey,privateKeyToBytes:xs.privateKeyToBytes,bytesToPrivateKey:xs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await ns.publicKeyToBytes({publicKey:t});return await ns.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ns.bytesToPublicKey,privateKeyToBytes:ns.privateKeyToBytes,bytesToPrivateKey:ns.bytesToPrivateKey},X25519:Oy}[r];if(!e)throw new nt("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function Nz({newDid:r,previousDidProof:e}){let t=await Kz({didUri:e.previousDid}),n=JC({didUri:r}),i=st.base64Url(e.signature).toUint8Array();if(!await is.verify({key:t,data:n,signature:i}))throw new nt("invalidPreviousDidProof","The previous DID proof is invalid.")}function X0(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return st.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>X0(e)).join("");throw new nt("internalError","Pkarr returned DNS TXT record with invalid data type")}function K0(r){return X0(r).split(B2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function qz(r){if(r.length<=255)return r;let e=[];for(let t=0;t<r.length;t+=255)e.push(r.slice(t,t+255));return e}async function She({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let s=X0(a.data);t.alsoKnownAs=s.split(Js);break}case o.startsWith("cnt"):{let s=X0(a.data);t.controller=s.includes(Js)?s.split(Js):s;break}case o.startsWith("k"):{let{id:s,t:c,k:l,c:d,a:u}=K0(a.data),f=st.base64Url(l).toUint8Array(),p=GC[Number(c)],h=await ZC(p).bytesToPublicKey({publicKeyBytes:f});h.alg=u||Lz[Number(c)];let m=o==="k0"?"0":s!==void 0?s:await _r({jwk:h});t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??r,publicKeyJwk:h}),i.set(o,y);break}case o.startsWith("s"):{let{id:s,t:c,se:l,...d}=K0(a.data),u=l.includes(Js)?l.split(Js):[l],f=Object.fromEntries(Object.entries(d).map(([p,h])=>[p,h.includes(Js)?h.split(Js):h]));t.service??=[],t.service.push({...f,id:`${r}#${s}`,type:c,serviceEndpoint:u});break}case o.startsWith("typ"):{let{id:s}=K0(a.data);n.types=s.split(Js).map(c=>Number(c));break}case o.startsWith("did"):{let s=p=>p.split(Js).map(h=>i.get(h)).filter(h=>typeof h=="string"),{auth:c,asm:l,del:d,inv:u,agm:f}=K0(a.data);c&&(t.authentication=s(c)),l&&(t.assertionMethod=s(l)),d&&(t.capabilityDelegation=s(d)),u&&(t.capabilityInvocation=s(u)),f&&(t.keyAgreement=s(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function khe({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],a=[],o=new Map,s=[],c=[];if(n!==void 0){let{signature:d,previousDid:u}=n;await Nz({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:mf,data:`id=${u};s=${d}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:mf,data:r.alsoKnownAs.join(Js)}),r.controller){let d=Array.isArray(r.controller)?r.controller.join(Js):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:mf,data:d})}for(let[d,u]of r.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let p=u.id.split("#").pop();o.set(p,f);let h=u.publicKeyJwk;if(!(h?.crv&&h.crv in Uz))throw new nt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${h?.crv??"undefined"}`);let m=GC[h.crv],y=await ZC(h.crv).publicKeyToBytes({publicKey:h}),v=st.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];p!=="0"&&await _r({jwk:h})!==p&&w.unshift(`id=${p}`),h.alg!==Lz[m]&&w.push(`a=${h.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:mf,data:w.join(B2)})}r.service?.forEach((d,u)=>{let f=`s${u}`;s.push(f);let{id:p,type:h,serviceEndpoint:m,...y}=d;p=Zs(p),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:p,t:h,se:m,...y}).map(([x,_])=>`${x}=${_}`).join(B2),w=qz(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:mf,data:w})});let l=[`v=${Ehe}`];if(c.length&&l.push(`vm=${c.join(Js)}`),Object.keys(tE).forEach(d=>{let u=r[d]?.map(f=>o.get(f.split("#").pop()));if(u){let f=wz[d];l.push(`${f}=${u.join(Js)}`)}}),s.length&&l.push(`svc=${s.join(Js)}`),e.types?.length){let d=e.types.map(u=>typeof u=="string"?gz[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:mf,data:`id=${d.join(Js)}`})}i.push({type:"TXT",name:"_did."+Aq(r.id)+".",ttl:mf,data:l.join(B2)});for(let d of t||[])a.push({type:"NS",name:"_did."+Aq(r.id)+".",ttl:mf,data:d+"."});return{id:0,type:"response",flags:yhe,answers:[...i,...a]}}function Aq(r){return r.split(":")[2]}function Gz(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nhe;)e[t++]=r&255|Rq,r/=128;for(;r&Khe;)e[t++]=r&255|Rq,r>>>=7;return e[t]=r|0,Gz.bytes=t-n+1,e}function mC(r,n){var t=0,n=n||0,i=0,a=n,o,s=r.length;do{if(a>=s)throw mC.bytes=0,new RangeError("Could not decode varint");o=r[a++],t+=i<28?(o&Cq)<<i:(o&Cq)*Math.pow(2,i),i+=7}while(o>=Lhe);return mC.bytes=a-n,t}function pme(r){r=n6(r);let e=Gy+8;(r.length<e||r.length>1024)&&Ii("expected proper params");let t=et(pE(r),r6-1n)+1n;return s6(t)}function Eme(r){let e=r.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let t=e.split(".");if(t.length===4){let i=t.map(Number);if(i.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=i;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var cde,bC,dde,lde,ude,fde,er,PC,pde,hh,hde,mde,Od,yde,gde,xC,r7,n7,i7,wde,vde,bde,Pde,eE,EC,ah,xde,Ede,s7,Sde,kde,o7,_de,Ade,Tde,N9,a7,Ide,c7,d7,Dde,Rde,Cde,l7,$de,Bde,u7,tE,Di,ts,Jn,nt,Ode,Ka,wo,jde,Kde,Nde,Ude,KNe,Lde,SC,qde,zde,Fde,m7,Gde,y7,g7,Hde,Vde,Qo,x2,NNe,UNe,LNe,qNe,zNe,FNe,GNe,U9,ja,HNe,VNe,WNe,$l,JNe,P0,L9,h2,eh,st,z0,Zde,Yde,T0,Xde,q9,Qde,ele,tle,rle,nle,z9,ile,sle,ole,ale,cle,dle,lle,ule,fle,ple,hle,mle,q2,z2,G0,H0,yle,gle,wle,kC,F9,G9,tC,ZNe,vle,ble,Ple,x0,xle,H9,Ele,Ua,YNe,of,Sle,rE,b7,P7,nE,kle,_le,Bl,Cle,AC,zR,W9,$le,FR,GR,kd,Mle,T7,XNe,D7,Nle,Ule,Lle,af,cf,qle,R7,yi,gn,nh,zle,rC,Z9,Y9,QNe,Fle,Vle,Wle,eue,HR,rue,nue,oh,Ul,Oa,eUe,X9,tUe,M7,K7,U7,Q9,cue,iC,eq,sC,Jo,rUe,nUe,E2,VR,_d,iUe,pue,sUe,gue,wue,vue,bue,df,lf,Pue,V0,Eue,z7,Sue,rq,Qi,_ue,ns,F7,Aue,Tue,Iue,Da,es,Due,xs,Ol,nq,m2,oC,Cue,$ue,Bue,Oue,jue,Mue,Kue,Nue,Uue,Lue,que,zue,Fue,Hue,Vue,Wue,Jue,Zue,Yue,Xue,Lt,Que,efe,uf,ff,tfe,H7,_c,Vo,y2,rfe,nfe,E0,WR,W0,iq,oUe,afe,aC,cfe,sq,dfe,lfe,oq,Na,J0,th,aUe,cUe,I0,hfe,dUe,lUe,uUe,fUe,pUe,hUe,mUe,yUe,gUe,wUe,Ra,mfe,is,jl,yfe,gfe,wfe,pf,vfe,Oy,S0,bfe,Ml,JR,Ic,Pfe,xfe,Se,tt,tb,kfe,_fe,Afe,Tfe,Kl,Ife,Dfe,Rfe,Cfe,X7,$fe,kn,Q7,rb,ss,OC,ez,cq,Wfe,tpe,tz,rz,nz,iz,sz,$a,Ac,je,Gl,_pe,Tpe,Ipe,dq,hf,Ef,vUe,bUe,PUe,xUe,EUe,SUe,kUe,_Ue,AUe,TUe,IUe,DUe,RUe,uq,Es,Ma,fq,pq,CUe,$Ue,BUe,OUe,hq,mq,yq,gq,FC,Ss,sb,gz,GC,wz,wq,vz,vq,jpe,Mpe,bq,Kpe,k0,Npe,bz,Upe,Fl,Pq,xq,jUe,aE,xz,Ez,Lpe,qpe,zpe,Fpe,Gpe,HC,Hpe,kz,Xpe,_z,Qpe,ehe,Cd,xf,ph,R0,Rz,dhe,lhe,uhe,Ll,qt,ql,ot,phe,kq,dC,hhe,Cz,mhe,Ze,mi,jy,k2,_2,A2,T2,I2,D2,zy,R2,vf,C2,$z,$2,_q,Nl,bf,Rd,C0,$0,Yo,B0,O0,j0,Uy,Ba,Fy,yhe,os,J2,Z2,Y2,uC,ghe,Mz,Ehe,mf,B2,Js,Uz,Lz,Tq,zz,vo,Iq,qy,Hn,Vn,MUe,_he,Ahe,The,Ihe,Fz,Dhe,Rhe,Che,$he,lE,KUe,NUe,Dq,UUe,Wy,Bhe,pC,Dd,Wo,YC,Tc,Ohe,Q0,jhe,Rq,Mhe,Khe,Nhe,Uhe,Lhe,Cq,qhe,zhe,Fhe,Ghe,Hhe,Vhe,Whe,Jhe,Zhe,Yhe,Xhe,Qhe,X2,$q,Bq,Oq,jq,eme,Hz,Vz,tme,Wz,Mq,LUe,_0,Zo,yC,w2,gC,By,v2,Jz,Kq,rme,rs,j2,wC,vC,b2,go,Yz,XC,Jy,nme,lt,Nq,Uq,Zy,Q2,M2,Xz,QC,e6,ime,sme,Lq,Qz,Ad,ome,qq,ame,YR,zq,cme,ih,dme,lme,t6,lh,r6,eF,tF,rF,Gy,Fq,Ii,uE,nF,XR,iF,sF,eb,n6,et,Gq,Hq,Yy,F0,K2,oF,i6,fE,pE,Vq,s6,Wq,Jq,aF,ume,fme,Zq,N2,hme,sh,mme,yme,Yq,Xq,A0,gme,wme,Qq,vme,cF,bo,bme,U2,P2,Pme,e7,dF,cb,xme,lF,uF,Sme,kme,hE,_me,mE,Ame,tg,ea=G(()=>{"use strict";g();cde=Object.create,bC=Object.defineProperty,dde=Object.getOwnPropertyDescriptor,lde=Object.getOwnPropertyNames,ude=Object.getPrototypeOf,fde=Object.prototype.hasOwnProperty,er=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),PC=(r,e)=>{for(var t in e)bC(r,t,{get:e[t],enumerable:!0})},pde=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of lde(e))!fde.call(r,i)&&i!==t&&bC(r,i,{get:()=>e[i],enumerable:!(n=dde(e,i))||n.enumerable});return r},hh=(r,e,t)=>(t=r!=null?cde(ude(r)):{},pde(e||!r||!r.__esModule?bC(t,"default",{value:r,enumerable:!0}):t,r)),hde=er((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),a=s=>s===1/0||i(s),o=class t7{constructor({max:c=1/0,ttl:l,updateAgeOnGet:d=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:p,noDisposeOnSet:h=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!a(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!h,p!==void 0){if(typeof p!="function")throw new TypeError("dispose must be function if set");this.dispose=p}this.timer=void 0,this.timerExpiration=void 0}setTimer(c,l){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==t7.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,d]of c)this.dispose(d,l,"delete")}setTTL(c,l=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let u=this.expirations[d];!u||u.length<=1?delete this.expirations[d]:this.expirations[d]=u.filter(f=>f!==c)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(c,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(c)}else this.expirationMap.set(c,1/0)}set(c,l,{ttl:d=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){u||this.setTTL(c,d);let p=this.data.get(c);p!==l&&(this.data.set(c,l),f||this.dispose(p,c,"set"))}else this.setTTL(c,d),this.data.set(c,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let l=this.expirationMap.get(c);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(c,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(c);if(u&&this.getRemainingTTL(c)===0){this.delete(c);return}return l&&this.setTTL(c,d),f}dispose(c,l){}delete(c){let l=this.expirationMap.get(c);if(l!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let l=this.expirations[c];if(this.size-l.length>=this.max){delete this.expirations[c];let d=[];for(let u of l)d.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of d)this.dispose(f,u,"evict")}else{let d=this.size-this.max,u=[];for(let f of l.splice(0,d))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>c)return;let d=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of d)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let l of this.expirations[c])yield[l,this.data.get(l)]}*keys(){for(let c in this.expirations)for(let l of this.expirations[c])yield l}*values(){for(let c in this.expirations)for(let l of this.expirations[c])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=o}),mde=er(r=>{"use strict";r.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}}),Od=er((r,e)=>{"use strict";e.exports=class extends Error{constructor(t,n){super(t||""),typeof n=="object"&&n!==null&&(n.code&&(this.code=String(n.code)),n.expected&&(this.expected=!0),n.transient&&(this.transient=!0),n.cause&&(this.cause=n.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}}),yde=er(r=>{"use strict";r.byteLength=c,r.toByteArray=d,r.fromByteArray=p;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=i.length;a<o;++a)e[a]=i[a],t[i.charCodeAt(a)]=a;var a,o;t[45]=62,t[95]=63;function s(h){var m=h.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=h.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function c(h){var m=s(h),y=m[0],v=m[1];return(y+v)*3/4-v}function l(h,m,y){return(m+y)*3/4-y}function d(h){var m,y=s(h),v=y[0],w=y[1],x=new n(l(h,v,w)),_=0,A=w>0?v-4:v,D;for(D=0;D<A;D+=4)m=t[h.charCodeAt(D)]<<18|t[h.charCodeAt(D+1)]<<12|t[h.charCodeAt(D+2)]<<6|t[h.charCodeAt(D+3)],x[_++]=m>>16&255,x[_++]=m>>8&255,x[_++]=m&255;return w===2&&(m=t[h.charCodeAt(D)]<<2|t[h.charCodeAt(D+1)]>>4,x[_++]=m&255),w===1&&(m=t[h.charCodeAt(D)]<<10|t[h.charCodeAt(D+1)]<<4|t[h.charCodeAt(D+2)]>>2,x[_++]=m>>8&255,x[_++]=m&255),x}function u(h){return e[h>>18&63]+e[h>>12&63]+e[h>>6&63]+e[h&63]}function f(h,m,y){for(var v,w=[],x=m;x<y;x+=3)v=(h[x]<<16&16711680)+(h[x+1]<<8&65280)+(h[x+2]&255),w.push(u(v));return w.join("")}function p(h){for(var m,y=h.length,v=y%3,w=[],x=16383,_=0,A=y-v;_<A;_+=x)w.push(f(h,_,_+x>A?A:_+x));return v===1?(m=h[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(h[y-2]<<8)+h[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),gde=er(r=>{r.read=function(e,t,n,i,a){var o,s,c=a*8-i-1,l=(1<<c)-1,d=l>>1,u=-7,f=n?a-1:0,p=n?-1:1,h=e[t+f];for(f+=p,o=h&(1<<-u)-1,h>>=-u,u+=c;u>0;o=o*256+e[t+f],f+=p,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=i;u>0;s=s*256+e[t+f],f+=p,u-=8);if(o===0)o=1-d;else{if(o===l)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(h?-1:1)*s*Math.pow(2,o-i)},r.write=function(e,t,n,i,a,o){var s,c,l,d=o*8-a-1,u=(1<<d)-1,f=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:o-1,m=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+f>=1?t+=p/l:t+=p*Math.pow(2,1-f),t*l>=2&&(s++,l/=2),s+f>=u?(c=0,s=u):s+f>=1?(c=(t*l-1)*Math.pow(2,a),s=s+f):(c=t*Math.pow(2,f-1)*Math.pow(2,a),s=0));a>=8;e[n+h]=c&255,h+=m,c/=256,a-=8);for(s=s<<a|c,d+=a;d>0;e[n+h]=s&255,h+=m,s/=256,d-=8);e[n+h-m]|=y*128}}),xC=er(r=>{"use strict";var e=yde(),t=gde(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=s,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(T){if(T>i)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,s.prototype),M}function s(T,M,U){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(T)}return c(T,M,U)}s.poolSize=8192;function c(T,M,U){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return h(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(_e(T,ArrayBuffer)||T&&_e(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(_e(T,SharedArrayBuffer)||T&&_e(T.buffer,SharedArrayBuffer)))return m(T,M,U);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return s.from(te,M,U);let ce=y(T);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return s.from(T[Symbol.toPrimitive]("string"),M,U);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}s.from=function(T,M,U){return c(T,M,U)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,U){return l(T),T<=0?o(T):M!==void 0?typeof U=="string"?o(T).fill(M,U):o(T).fill(M):o(T)}s.alloc=function(T,M,U){return d(T,M,U)};function u(T){return l(T),o(T<0?0:v(T)|0)}s.allocUnsafe=function(T){return u(T)},s.allocUnsafeSlow=function(T){return u(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!s.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let U=x(T,M)|0,te=o(U),ce=te.write(T,M);return ce!==U&&(te=te.slice(0,ce)),te}function p(T){let M=T.length<0?0:v(T.length)|0,U=o(M);for(let te=0;te<M;te+=1)U[te]=T[te]&255;return U}function h(T){if(_e(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return p(T)}function m(T,M,U){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(U||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&U===void 0?te=new Uint8Array(T):U===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,U),Object.setPrototypeOf(te,s.prototype),te}function y(T){if(s.isBuffer(T)){let M=v(T.length)|0,U=o(M);return U.length===0||T.copy(U,0,0,M),U}if(T.length!==void 0)return typeof T.length!="number"||at(T.length)?o(0):p(T);if(T.type==="Buffer"&&Array.isArray(T.data))return p(T.data)}function v(T){if(T>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return T|0}function w(T){return+T!=T&&(T=0),s.alloc(+T)}s.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==s.prototype},s.compare=function(T,M){if(_e(T,Uint8Array)&&(T=s.from(T,T.offset,T.byteLength)),_e(M,Uint8Array)&&(M=s.from(M,M.offset,M.byteLength)),!s.isBuffer(T)||!s.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let U=T.length,te=M.length;for(let ce=0,ge=Math.min(U,te);ce<ge;++ce)if(T[ce]!==M[ce]){U=T[ce],te=M[ce];break}return U<te?-1:te<U?1:0},s.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return s.alloc(0);let U;if(M===void 0)for(M=0,U=0;U<T.length;++U)M+=T[U].length;let te=s.allocUnsafe(M),ce=0;for(U=0;U<T.length;++U){let ge=T[U];if(_e(ge,Uint8Array))ce+ge.length>te.length?(s.isBuffer(ge)||(ge=s.from(ge)),ge.copy(te,ce)):Uint8Array.prototype.set.call(te,ge,ce);else if(s.isBuffer(ge))ge.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=ge.length}return te};function x(T,M){if(s.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||_e(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let U=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&U===0)return 0;let ce=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return U;case"utf8":case"utf-8":return Pe(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U*2;case"hex":return U>>>1;case"base64":return Je(T).length;default:if(ce)return te?-1:Pe(T).length;M=(""+M).toLowerCase(),ce=!0}}s.byteLength=x;function _(T,M,U){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((U===void 0||U>this.length)&&(U=this.length),U<=0)||(U>>>=0,M>>>=0,U<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,M,U);case"utf8":case"utf-8":return R(this,M,U);case"ascii":return S(this,M,U);case"latin1":case"binary":return E(this,M,U);case"base64":return Y(this,M,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,M,U);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}s.prototype._isBuffer=!0;function A(T,M,U){let te=T[M];T[M]=T[U],T[U]=te}s.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)A(this,M,M+1);return this},s.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)A(this,M,M+3),A(this,M+1,M+2);return this},s.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)A(this,M,M+7),A(this,M+1,M+6),A(this,M+2,M+5),A(this,M+3,M+4);return this},s.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):_.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(T){if(!s.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:s.compare(this,T)===0},s.prototype.inspect=function(){let T="",M=r.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(T,M,U,te,ce){if(_e(T,Uint8Array)&&(T=s.from(T,T.offset,T.byteLength)),!s.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),U===void 0&&(U=T?T.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),M<0||U>T.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&M>=U)return 0;if(te>=ce)return-1;if(M>=U)return 1;if(M>>>=0,U>>>=0,te>>>=0,ce>>>=0,this===T)return 0;let ge=ce-te,ke=U-M,Vt=Math.min(ge,ke),ni=this.slice(te,ce),Vr=T.slice(M,U);for(let Ar=0;Ar<Vt;++Ar)if(ni[Ar]!==Vr[Ar]){ge=ni[Ar],ke=Vr[Ar];break}return ge<ke?-1:ke<ge?1:0};function D(T,M,U,te,ce){if(T.length===0)return-1;if(typeof U=="string"?(te=U,U=0):U>2147483647?U=2147483647:U<-2147483648&&(U=-2147483648),U=+U,at(U)&&(U=ce?0:T.length-1),U<0&&(U=T.length+U),U>=T.length){if(ce)return-1;U=T.length-1}else if(U<0)if(ce)U=0;else return-1;if(typeof M=="string"&&(M=s.from(M,te)),s.isBuffer(M))return M.length===0?-1:N(T,M,U,te,ce);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(T,M,U):Uint8Array.prototype.lastIndexOf.call(T,M,U):N(T,[M],U,te,ce);throw new TypeError("val must be string, number or Buffer")}function N(T,M,U,te,ce){let ge=1,ke=T.length,Vt=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;ge=2,ke/=2,Vt/=2,U/=2}function ni(Ar,gr){return ge===1?Ar[gr]:Ar.readUInt16BE(gr*ge)}let Vr;if(ce){let Ar=-1;for(Vr=U;Vr<ke;Vr++)if(ni(T,Vr)===ni(M,Ar===-1?0:Vr-Ar)){if(Ar===-1&&(Ar=Vr),Vr-Ar+1===Vt)return Ar*ge}else Ar!==-1&&(Vr-=Vr-Ar),Ar=-1}else for(U+Vt>ke&&(U=ke-Vt),Vr=U;Vr>=0;Vr--){let Ar=!0;for(let gr=0;gr<Vt;gr++)if(ni(T,Vr+gr)!==ni(M,gr)){Ar=!1;break}if(Ar)return Vr}return-1}s.prototype.includes=function(T,M,U){return this.indexOf(T,M,U)!==-1},s.prototype.indexOf=function(T,M,U){return D(this,T,M,U,!0)},s.prototype.lastIndexOf=function(T,M,U){return D(this,T,M,U,!1)};function $(T,M,U,te){U=Number(U)||0;let ce=T.length-U;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let ge=M.length;te>ge/2&&(te=ge/2);let ke;for(ke=0;ke<te;++ke){let Vt=parseInt(M.substr(ke*2,2),16);if(at(Vt))return ke;T[U+ke]=Vt}return ke}function z(T,M,U,te){return Bt(Pe(M,T.length-U),T,U,te)}function L(T,M,U,te){return Bt(Ne(M),T,U,te)}function j(T,M,U,te){return Bt(Je(M),T,U,te)}function H(T,M,U,te){return Bt(He(M,T.length-U),T,U,te)}s.prototype.write=function(T,M,U,te){if(M===void 0)te="utf8",U=this.length,M=0;else if(U===void 0&&typeof M=="string")te=M,U=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(U)?(U=U>>>0,te===void 0&&(te="utf8")):(te=U,U=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-M;if((U===void 0||U>ce)&&(U=ce),T.length>0&&(U<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return $(this,T,M,U);case"utf8":case"utf-8":return z(this,T,M,U);case"ascii":case"latin1":case"binary":return L(this,T,M,U);case"base64":return j(this,T,M,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,T,M,U);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Y(T,M,U){return M===0&&U===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,U))}function R(T,M,U){U=Math.min(T.length,U);let te=[],ce=M;for(;ce<U;){let ge=T[ce],ke=null,Vt=ge>239?4:ge>223?3:ge>191?2:1;if(ce+Vt<=U){let ni,Vr,Ar,gr;switch(Vt){case 1:ge<128&&(ke=ge);break;case 2:ni=T[ce+1],(ni&192)===128&&(gr=(ge&31)<<6|ni&63,gr>127&&(ke=gr));break;case 3:ni=T[ce+1],Vr=T[ce+2],(ni&192)===128&&(Vr&192)===128&&(gr=(ge&15)<<12|(ni&63)<<6|Vr&63,gr>2047&&(gr<55296||gr>57343)&&(ke=gr));break;case 4:ni=T[ce+1],Vr=T[ce+2],Ar=T[ce+3],(ni&192)===128&&(Vr&192)===128&&(Ar&192)===128&&(gr=(ge&15)<<18|(ni&63)<<12|(Vr&63)<<6|Ar&63,gr>65535&&gr<1114112&&(ke=gr))}}ke===null?(ke=65533,Vt=1):ke>65535&&(ke-=65536,te.push(ke>>>10&1023|55296),ke=56320|ke&1023),te.push(ke),ce+=Vt}return P(te)}var C=4096;function P(T){let M=T.length;if(M<=C)return String.fromCharCode.apply(String,T);let U="",te=0;for(;te<M;)U+=String.fromCharCode.apply(String,T.slice(te,te+=C));return U}function S(T,M,U){let te="";U=Math.min(T.length,U);for(let ce=M;ce<U;++ce)te+=String.fromCharCode(T[ce]&127);return te}function E(T,M,U){let te="";U=Math.min(T.length,U);for(let ce=M;ce<U;++ce)te+=String.fromCharCode(T[ce]);return te}function k(T,M,U){let te=T.length;(!M||M<0)&&(M=0),(!U||U<0||U>te)&&(U=te);let ce="";for(let ge=M;ge<U;++ge)ce+=It[T[ge]];return ce}function I(T,M,U){let te=T.slice(M,U),ce="";for(let ge=0;ge<te.length-1;ge+=2)ce+=String.fromCharCode(te[ge]+te[ge+1]*256);return ce}s.prototype.slice=function(T,M){let U=this.length;T=~~T,M=M===void 0?U:~~M,T<0?(T+=U,T<0&&(T=0)):T>U&&(T=U),M<0?(M+=U,M<0&&(M=0)):M>U&&(M=U),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,s.prototype),te};function K(T,M,U){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>U)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T],ce=1,ge=0;for(;++ge<M&&(ce*=256);)te+=this[T+ge]*ce;return te},s.prototype.readUintBE=s.prototype.readUIntBE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T+--M],ce=1;for(;M>0&&(ce*=256);)te+=this[T+--M]*ce;return te},s.prototype.readUint8=s.prototype.readUInt8=function(T,M){return T=T>>>0,M||K(T,1,this.length),this[T]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||K(T,2,this.length),this[T]|this[T+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||K(T,2,this.length),this[T]<<8|this[T+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||K(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},s.prototype.readBigUInt64LE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ce=this[++T]+this[++T]*2**8+this[++T]*2**16+U*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),s.prototype.readBigUInt64BE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ce=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+U;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),s.prototype.readIntLE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=this[T],ce=1,ge=0;for(;++ge<M&&(ce*=256);)te+=this[T+ge]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*M)),te},s.prototype.readIntBE=function(T,M,U){T=T>>>0,M=M>>>0,U||K(T,M,this.length);let te=M,ce=1,ge=this[T+--te];for(;te>0&&(ce*=256);)ge+=this[T+--te]*ce;return ce*=128,ge>=ce&&(ge-=Math.pow(2,8*M)),ge},s.prototype.readInt8=function(T,M){return T=T>>>0,M||K(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},s.prototype.readInt16LE=function(T,M){T=T>>>0,M||K(T,2,this.length);let U=this[T]|this[T+1]<<8;return U&32768?U|4294901760:U},s.prototype.readInt16BE=function(T,M){T=T>>>0,M||K(T,2,this.length);let U=this[T+1]|this[T]<<8;return U&32768?U|4294901760:U},s.prototype.readInt32LE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},s.prototype.readInt32BE=function(T,M){return T=T>>>0,M||K(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},s.prototype.readBigInt64LE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(U<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),s.prototype.readBigInt64BE=$t(function(T){T=T>>>0,ue(T,"offset");let M=this[T],U=this[T+7];(M===void 0||U===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+U)}),s.prototype.readFloatLE=function(T,M){return T=T>>>0,M||K(T,4,this.length),t.read(this,T,!0,23,4)},s.prototype.readFloatBE=function(T,M){return T=T>>>0,M||K(T,4,this.length),t.read(this,T,!1,23,4)},s.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||K(T,8,this.length),t.read(this,T,!0,52,8)},s.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||K(T,8,this.length),t.read(this,T,!1,52,8)};function F(T,M,U,te,ce,ge){if(!s.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ce||M<ge)throw new RangeError('"value" argument is out of bounds');if(U+te>T.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(T,M,U,te){if(T=+T,M=M>>>0,U=U>>>0,!te){let ke=Math.pow(2,8*U)-1;F(this,T,M,U,ke,0)}let ce=1,ge=0;for(this[M]=T&255;++ge<U&&(ce*=256);)this[M+ge]=T/ce&255;return M+U},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(T,M,U,te){if(T=+T,M=M>>>0,U=U>>>0,!te){let ke=Math.pow(2,8*U)-1;F(this,T,M,U,ke,0)}let ce=U-1,ge=1;for(this[M+ce]=T&255;--ce>=0&&(ge*=256);)this[M+ce]=T/ge&255;return M+U},s.prototype.writeUint8=s.prototype.writeUInt8=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,1,255,0),this[M]=T&255,M+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function V(T,M,U,te,ce){le(M,te,ce,T,U,7);let ge=Number(M&BigInt(4294967295));T[U++]=ge,ge=ge>>8,T[U++]=ge,ge=ge>>8,T[U++]=ge,ge=ge>>8,T[U++]=ge;let ke=Number(M>>BigInt(32)&BigInt(4294967295));return T[U++]=ke,ke=ke>>8,T[U++]=ke,ke=ke>>8,T[U++]=ke,ke=ke>>8,T[U++]=ke,U}function W(T,M,U,te,ce){le(M,te,ce,T,U,7);let ge=Number(M&BigInt(4294967295));T[U+7]=ge,ge=ge>>8,T[U+6]=ge,ge=ge>>8,T[U+5]=ge,ge=ge>>8,T[U+4]=ge;let ke=Number(M>>BigInt(32)&BigInt(4294967295));return T[U+3]=ke,ke=ke>>8,T[U+2]=ke,ke=ke>>8,T[U+1]=ke,ke=ke>>8,T[U]=ke,U+8}s.prototype.writeBigUInt64LE=$t(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=$t(function(T,M=0){return W(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(T,M,U,te){if(T=+T,M=M>>>0,!te){let Vt=Math.pow(2,8*U-1);F(this,T,M,U,Vt-1,-Vt)}let ce=0,ge=1,ke=0;for(this[M]=T&255;++ce<U&&(ge*=256);)T<0&&ke===0&&this[M+ce-1]!==0&&(ke=1),this[M+ce]=(T/ge>>0)-ke&255;return M+U},s.prototype.writeIntBE=function(T,M,U,te){if(T=+T,M=M>>>0,!te){let Vt=Math.pow(2,8*U-1);F(this,T,M,U,Vt-1,-Vt)}let ce=U-1,ge=1,ke=0;for(this[M+ce]=T&255;--ce>=0&&(ge*=256);)T<0&&ke===0&&this[M+ce+1]!==0&&(ke=1),this[M+ce]=(T/ge>>0)-ke&255;return M+U},s.prototype.writeInt8=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},s.prototype.writeInt16LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},s.prototype.writeInt16BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},s.prototype.writeInt32LE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},s.prototype.writeInt32BE=function(T,M,U){return T=+T,M=M>>>0,U||F(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},s.prototype.writeBigInt64LE=$t(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=$t(function(T,M=0){return W(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(T,M,U,te,ce,ge){if(U+te>T.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("Index out of range")}function Q(T,M,U,te,ce){return M=+M,U=U>>>0,ce||J(T,M,U,4,34028234663852886e22,-34028234663852886e22),t.write(T,M,U,te,23,4),U+4}s.prototype.writeFloatLE=function(T,M,U){return Q(this,T,M,!0,U)},s.prototype.writeFloatBE=function(T,M,U){return Q(this,T,M,!1,U)};function q(T,M,U,te,ce){return M=+M,U=U>>>0,ce||J(T,M,U,8,17976931348623157e292,-17976931348623157e292),t.write(T,M,U,te,52,8),U+8}s.prototype.writeDoubleLE=function(T,M,U){return q(this,T,M,!0,U)},s.prototype.writeDoubleBE=function(T,M,U){return q(this,T,M,!1,U)},s.prototype.copy=function(T,M,U,te){if(!s.isBuffer(T))throw new TypeError("argument should be a Buffer");if(U||(U=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<U&&(te=U),te===U||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-U&&(te=T.length-M+U);let ce=te-U;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,U,te):Uint8Array.prototype.set.call(T,this.subarray(U,te),M),ce},s.prototype.fill=function(T,M,U,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,U=this.length):typeof U=="string"&&(te=U,U=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!s.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let ge=T.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(T=ge)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<U)throw new RangeError("Out of range index");if(U<=M)return this;M=M>>>0,U=U===void 0?this.length:U>>>0,T||(T=0);let ce;if(typeof T=="number")for(ce=M;ce<U;++ce)this[ce]=T;else{let ge=s.isBuffer(T)?T:s.from(T,te),ke=ge.length;if(ke===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ce=0;ce<U-M;++ce)this[ce+M]=ge[ce%ke]}return this};var ee={};function se(T,M,U){ee[T]=class extends U{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,U){let te=`The value of "${T}" is out of range.`,ce=U;return Number.isInteger(U)&&Math.abs(U)>2**32?ce=ne(String(U)):typeof U=="bigint"&&(ce=String(U),(U>BigInt(2)**BigInt(32)||U<-(BigInt(2)**BigInt(32)))&&(ce=ne(ce)),ce+="n"),te+=` It must be ${M}. Received ${ce}`,te},RangeError);function ne(T){let M="",U=T.length,te=T[0]==="-"?1:0;for(;U>=te+4;U-=3)M=`_${T.slice(U-3,U)}${M}`;return`${T.slice(0,U)}${M}`}function X(T,M,U){ue(M,"offset"),(T[M]===void 0||T[M+U]===void 0)&&pe(M,T.length-(U+1))}function le(T,M,U,te,ce,ge){if(T>U||T<M){let ke=typeof M=="bigint"?"n":"",Vt;throw ge>3?M===0||M===BigInt(0)?Vt=`>= 0${ke} and < 2${ke} ** ${(ge+1)*8}${ke}`:Vt=`>= -(2${ke} ** ${(ge+1)*8-1}${ke}) and < 2 ** ${(ge+1)*8-1}${ke}`:Vt=`>= ${M}${ke} and <= ${U}${ke}`,new ee.ERR_OUT_OF_RANGE("value",Vt,T)}X(te,ce,ge)}function ue(T,M){if(typeof T!="number")throw new ee.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,U){throw Math.floor(T)!==T?(ue(T,U),new ee.ERR_OUT_OF_RANGE(U||"offset","an integer",T)):M<0?new ee.ERR_BUFFER_OUT_OF_BOUNDS:new ee.ERR_OUT_OF_RANGE(U||"offset",`>= ${U?1:0} and <= ${M}`,T)}var xe=/[^+/0-9A-Za-z-_]/g;function de(T){if(T=T.split("=")[0],T=T.trim().replace(xe,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Pe(T,M){M=M||1/0;let U,te=T.length,ce=null,ge=[];for(let ke=0;ke<te;++ke){if(U=T.charCodeAt(ke),U>55295&&U<57344){if(!ce){if(U>56319){(M-=3)>-1&&ge.push(239,191,189);continue}else if(ke+1===te){(M-=3)>-1&&ge.push(239,191,189);continue}ce=U;continue}if(U<56320){(M-=3)>-1&&ge.push(239,191,189),ce=U;continue}U=(ce-55296<<10|U-56320)+65536}else ce&&(M-=3)>-1&&ge.push(239,191,189);if(ce=null,U<128){if((M-=1)<0)break;ge.push(U)}else if(U<2048){if((M-=2)<0)break;ge.push(U>>6|192,U&63|128)}else if(U<65536){if((M-=3)<0)break;ge.push(U>>12|224,U>>6&63|128,U&63|128)}else if(U<1114112){if((M-=4)<0)break;ge.push(U>>18|240,U>>12&63|128,U>>6&63|128,U&63|128)}else throw new Error("Invalid code point")}return ge}function Ne(T){let M=[];for(let U=0;U<T.length;++U)M.push(T.charCodeAt(U)&255);return M}function He(T,M){let U,te,ce,ge=[];for(let ke=0;ke<T.length&&!((M-=2)<0);++ke)U=T.charCodeAt(ke),te=U>>8,ce=U%256,ge.push(ce),ge.push(te);return ge}function Je(T){return e.toByteArray(de(T))}function Bt(T,M,U,te){let ce;for(ce=0;ce<te&&!(ce+U>=M.length||ce>=T.length);++ce)M[ce+U]=T[ce];return ce}function _e(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function at(T){return T!==T}var It=function(){let T="0123456789abcdef",M=new Array(256);for(let U=0;U<16;++U){let te=U*16;for(let ce=0;ce<16;++ce)M[te+ce]=T[U]+T[ce]}return M}();function $t(T){return typeof BigInt>"u"?Ht:T}function Ht(){throw new Error("BigInt not supported")}}),r7=er((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),n7=er(r=>{"use strict";var e=Od(),t=new Set(["buffer","view","utf8"]),n=class{constructor(i){if(this.encode=i.encode||this.encode,this.decode=i.decode||this.decode,this.name=i.name||this.name,this.format=i.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!t.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");i.createViewTranscoder&&(this.createViewTranscoder=i.createViewTranscoder),i.createBufferTranscoder&&(this.createBufferTranscoder=i.createBufferTranscoder),i.createUTF8Transcoder&&(this.createUTF8Transcoder=i.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};r.Encoding=n}),i7=er(r=>{"use strict";var{Buffer:e}=xC()||{},{Encoding:t}=n7(),n=r7(),i=class extends t{constructor(s){super({...s,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:s=>this.decode(e.from(s.buffer,s.byteOffset,s.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends t{constructor(s){super({...s,format:"view"})}createBufferTranscoder(){return new i({encode:s=>{let c=this.encode(s);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends t{constructor(s){super({...s,format:"utf8"})}createBufferTranscoder(){return new i({encode:s=>e.from(this.encode(s),"utf8"),decode:s=>this.decode(s.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:s,textDecoder:c}=n();return new a({encode:l=>s.encode(this.encode(l)),decode:l=>this.decode(c.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=a,r.UTF8Format=o}),wde=er(r=>{"use strict";var{Buffer:e}=xC()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=r7()(),{BufferFormat:i,ViewFormat:a,UTF8Format:o}=i7(),s=c=>c;r.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:s,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:s,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),r.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:s,name:"view",createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:s,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),r.base64=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),vde=er(r=>{"use strict";var e=Od(),t=wde(),{Encoding:n}=n7(),{BufferFormat:i,ViewFormat:a,UTF8Format:o}=i7(),s=Symbol("formats"),c=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(v=>l.has(v)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[s]=new Set(y);for(let v in t)try{this.encoding(v)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let v=this[c].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=h[y],!v)throw new e(`Encoding '${y}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof y!="object"||y===null)throw new TypeError("First argument 'encoding' must be a string or object");v=u(y)}let{name:w,format:x}=v;if(!this[s].has(x))if(this[s].has("view"))v=v.createViewTranscoder();else if(this[s].has("buffer"))v=v.createBufferTranscoder();else if(this[s].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,v.name,v.commonName])this[c].set(_,v)}return v}};r.Transcoder=d;function u(y){if(y instanceof n)return y;let v="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||v||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new o({...y,name:w});case"buffer":return new i({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var p={binary:t.buffer,"utf-8":t.utf8},h={...t,...p},m=0}),bde=er((r,e)=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function o(l,d,u,f,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new a(u,f||l,p),m=n?n+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],h]:l._events[m].push(h):(l._events[m]=h,l._eventsCount++),l}function s(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)t.call(d,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},c.prototype.listeners=function(l){var d=n?n+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,p=u.length,h=new Array(p);f<p;f++)h[f]=u[f].fn;return h},c.prototype.listenerCount=function(l){var d=n?n+l:l,u=this._events[d];return u?u.fn?1:u.length:0},c.prototype.emit=function(l,d,u,f,p,h){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,x;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,u),!0;case 4:return y.fn.call(y.context,d,u,f),!0;case 5:return y.fn.call(y.context,d,u,f,p),!0;case 6:return y.fn.call(y.context,d,u,f,p,h),!0}for(x=1,w=new Array(v-1);x<v;x++)w[x-1]=arguments[x];y.fn.apply(y.context,w)}else{var _=y.length,A;for(x=0;x<_;x++)switch(y[x].once&&this.removeListener(l,y[x].fn,void 0,!0),v){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,d);break;case 3:y[x].fn.call(y[x].context,d,u);break;case 4:y[x].fn.call(y[x].context,d,u,f);break;default:if(!w)for(A=1,w=new Array(v-1);A<v;A++)w[A-1]=arguments[A];y[x].fn.apply(y[x].context,w)}}return!0},c.prototype.on=function(l,d,u){return o(this,l,d,u,!1)},c.prototype.once=function(l,d,u){return o(this,l,d,u,!0)},c.prototype.removeListener=function(l,d,u,f){var p=n?n+l:l;if(!this._events[p])return this;if(!d)return s(this,p),this;var h=this._events[p];if(h.fn)h.fn===d&&(!f||h.once)&&(!u||h.context===u)&&s(this,p);else{for(var m=0,y=[],v=h.length;m<v;m++)(h[m].fn!==d||f&&!h[m].once||u&&h[m].context!==u)&&y.push(h[m]);y.length?this._events[p]=y.length===1?y[0]:y:s(this,p)}return this},c.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&s(this,d)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),Pde=er((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),eE=er(r=>{"use strict";var e=Pde();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(a,o){t=function(s,c){s?o(s):a(c)}});t[n!==void 0?n:"promise"]=i}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t},r.fromPromise=function(t,n){if(n===void 0)return t;t.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),EC=er(r=>{"use strict";r.getCallback=function(e,t){return typeof e=="function"?e:t},r.getOptions=function(e,t){return typeof e=="object"&&e!==null?e:t!==void 0?t:{}}}),ah=er(r=>{"use strict";var{fromCallback:e}=eE(),t=Od(),{getOptions:n,getCallback:i}=EC(),a=Symbol("promise"),o=Symbol("callback"),s=Symbol("working"),c=Symbol("handleOne"),l=Symbol("handleMany"),d=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),p=Symbol("closing"),h=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),x=Symbol("abortOnClose"),_=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),z=Object.freeze({}),L=()=>{},j=!1,H=class{constructor(S,E,k){if(typeof S!="object"||S===null){let I=S===null?"null":typeof S;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof E!="object"||E===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[s]=!1,this[p]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[l]=this[l].bind(this),this[h]=this[h].bind(this),this[v]=E[v],this[w]=E[w],this[_]=k,this[N]=Number.isInteger(E.limit)&&E.limit>=0?E.limit:1/0,this[$]=0,this[x]=!!E.abortOnClose,this.db=S,this.db.attachResource(this),this.nextTick=S.nextTick}get count(){return this[$]}get limit(){return this[N]}next(S){let E;if(S===void 0)E=new Promise((k,I)=>{S=(K,F,V)=>{K?I(K):this[_]?F===void 0&&V===void 0?k():k([F,V]):k(F)}});else if(typeof S!="function")throw new TypeError("Callback must be a function");return this[p]?this.nextTick(S,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(S,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[s]=!0,this[o]=S,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),E}_next(S){this.nextTick(S)}nextv(S,E,k){return k=i(E,k),k=e(k,a),E=n(E,z),Number.isInteger(S)?(this[p]?this.nextTick(k,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(k,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(S<1&&(S=1),this[N]<1/0&&(S=Math.min(S,this[N]-this[$])),this[s]=!0,this[o]=k,S<=0?this.nextTick(this[l],null,[]):this._nextv(S,E,this[l])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(S,E,k){let I=[],K=(F,V,W)=>{if(F)return k(F);if(this[_]?V===void 0&&W===void 0:V===void 0)return k(null,I);I.push(this[_]?[V,W]:V),I.length===S?k(null,I):this._next(K)};this._next(K)}all(S,E){return E=i(S,E),E=e(E,a),S=n(S,z),this[p]?this.nextTick(E,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[s]?this.nextTick(E,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[s]=!0,this[o]=E,this[d]=!0,this[$]>=this[N]?this.nextTick(this[l],null,[]):this._all(S,this[l])),E[a]}_all(S,E){let k=this[$],I=[],K=()=>{let V=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;V<=0?this.nextTick(E,null,I):this._nextv(V,z,F)},F=(V,W)=>{V?E(V):W.length===0?E(null,I):(I.push.apply(I,W),k+=W.length,K())};K()}[u](){let S=this[o];return this[x]&&S===null?L:(this[s]=!1,this[o]=null,this[p]&&this._close(this[h]),S)}[f](S,E,k){this[d]?this.close(S.bind(null,E,k)):S(E,k)}seek(S,E){if(E=n(E,z),!this[p]){if(this[s])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(E.keyEncoding||this[v]),I=k.format;E.keyEncoding!==I&&(E={...E,keyEncoding:I});let K=this.db.prefixKey(k.encode(S),I);this._seek(K,E)}}}_seek(S,E){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(S){return S=e(S,a),this[m]?this.nextTick(S):this[p]?this[y].push(S):(this[p]=!0,this[y].push(S),this[s]?this[x]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[h])),S[a]}_close(S){this.nextTick(S)}[h](){this[m]=!0,this.db.detachResource(this);let S=this[y];this[y]=[];for(let E of S)E()}async*[Symbol.asyncIterator](){try{let S;for(;(S=await this.next())!==void 0;)yield S}finally{this[m]||await this.close()}}},Y=class extends H{constructor(S,E){super(S,E,!0),this[A]=E.keys!==!1,this[D]=E.values!==!1}[c](S,E,k){let I=this[u]();if(S)return I(S);try{E=this[A]&&E!==void 0?this[v].decode(E):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(K){return I(new P("entry",K))}E===void 0&&k===void 0||this[$]++,I(null,E,k)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I of E){let K=I[0],F=I[1];I[0]=this[A]&&K!==void 0?this[v].decode(K):void 0,I[1]=this[D]&&F!==void 0?this[w].decode(F):void 0}}catch(I){return this[f](k,new P("entries",I))}this[$]+=E.length,this[f](k,null,E)}end(S){return!j&&typeof console<"u"&&(j=!0,console.warn(new t("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(S)}},R=class extends H{constructor(S,E){super(S,E,!1)}[c](S,E){let k=this[u]();if(S)return k(S);try{E=E!==void 0?this[v].decode(E):void 0}catch(I){return k(new P("key",I))}E!==void 0&&this[$]++,k(null,E)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I=0;I<E.length;I++){let K=E[I];E[I]=K!==void 0?this[v].decode(K):void 0}}catch(I){return this[f](k,new P("keys",I))}this[$]+=E.length,this[f](k,null,E)}},C=class extends H{constructor(S,E){super(S,E,!1)}[c](S,E){let k=this[u]();if(S)return k(S);try{E=E!==void 0?this[w].decode(E):void 0}catch(I){return k(new P("value",I))}E!==void 0&&this[$]++,k(null,E)}[l](S,E){let k=this[u]();if(S)return this[f](k,S);try{for(let I=0;I<E.length;I++){let K=E[I];E[I]=K!==void 0?this[w].decode(K):void 0}}catch(I){return this[f](k,new P("values",I))}this[$]+=E.length,this[f](k,null,E)}},P=class extends t{constructor(S,E){super(`Iterator could not decode ${S}`,{code:"LEVEL_DECODE_ERROR",cause:E})}};for(let S of["_ended property","_nexting property","_end method"])Object.defineProperty(Y.prototype,S.split(" ")[0],{get(){throw new t(`The ${S} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${S} has been removed`,{code:"LEVEL_LEGACY"})}});Y.keyEncoding=v,Y.valueEncoding=w,r.AbstractIterator=Y,r.AbstractKeyIterator=R,r.AbstractValueIterator=C}),xde=er(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=ah(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),s=class extends e{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends t{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let l of[s,c]){let d=l===s,u=d?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,p,h){let m=this[i];f?m(f):m(null,d?p:h)},l.prototype._nextv=function(f,p,h){this[i]=h,this[n].nextv(f,p,this[o])},l.prototype._all=function(f,p){this[i]=p,this[n].all(f,this[o])},l.prototype[o]=function(f,p){let h=this[i];f?h(f):h(null,p.map(u))},l.prototype._seek=function(f,p){this[n].seek(f,p)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=s,r.DefaultValueIterator=c}),Ede=er(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=ah(),i=Od(),a=Symbol("nut"),o=Symbol("undefer"),s=Symbol("factory"),c=class extends e{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.iterator(f),this.db.defer(()=>this[o]())}},l=class extends t{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(u,f){super(u,f),this[a]=null,this[s]=()=>u.values(f),this.db.defer(()=>this[o]())}};for(let u of[c,l,d])u.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[s]())},u.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new i("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._nextv=function(f,p,h){this[a]!==null?this[a].nextv(f,p,h):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,p,h)):this.nextTick(h,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,p){this[a]!==null?this[a].all(p):this.db.status==="opening"?this.db.defer(()=>this._all(f,p)):this.nextTick(p,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,p){this[a]!==null?this[a]._seek(f,p):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,p))},u.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=c,r.DeferredKeyIterator=l,r.DeferredValueIterator=d}),s7=er(r=>{"use strict";var{fromCallback:e}=eE(),t=Od(),{getCallback:n,getOptions:i}=EC(),a=Symbol("promise"),o=Symbol("status"),s=Symbol("operations"),c=Symbol("finishClose"),l=Symbol("closeCallbacks"),d=class{constructor(u){if(typeof u!="object"||u===null){let f=u===null?"null":typeof u;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[s]=[],this[l]=[],this[o]="open",this[c]=this[c].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[s].length}put(u,f,p){if(this[o]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u)||this.db._checkValue(f);if(h)throw h;let m=p&&p.sublevel!=null?p.sublevel:this.db,y=p,v=m.keyEncoding(p&&p.keyEncoding),w=m.valueEncoding(p&&p.valueEncoding),x=v.format;p={...p,keyEncoding:x,valueEncoding:w.format},m!==this.db&&(p.sublevel=null);let _=m.prefixKey(v.encode(u),x),A=w.encode(f);return this._put(_,A,p),this[s].push({...y,type:"put",key:u,value:f}),this}_put(u,f,p){}del(u,f){if(this[o]!=="open")throw new t("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u);if(p)throw p;let h=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=h.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},h!==this.db&&(f.sublevel=null),this._del(h.prefixKey(y.encode(u),v),f),this[s].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[o]!=="open")throw new t("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[s]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,a),u=i(u),this[o]!=="open"?this.nextTick(f,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(f):(this[o]="writing",this._write(u,p=>{this[o]="closing",this[l].push(()=>f(p)),p||this.db.emit("batch",this[s]),this._close(this[c])})),f[a]}_write(u,f){}close(u){return u=e(u,a),this[o]==="closing"?this[l].push(u):this[o]==="closed"?this.nextTick(u):(this[l].push(u),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),u[a]}_close(u){this.nextTick(u)}[c](){this[o]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=d}),Sde=er(r=>{"use strict";var{AbstractChainedBatch:e}=s7(),t=Od(),n=Symbol("encoded"),i=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,s){this[n].push({...s,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};r.DefaultChainedBatch=i}),kde=er((r,e)=>{"use strict";var t=Od(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let s={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new t(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(c)?s[c]=o.encode(a[c]):s[c]=a[c]}return s.reverse=!!s.reverse,s.limit=Number.isInteger(s.limit)&&s.limit>=0?s.limit:-1,s}}),o7=er((r,e)=>{var t;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(t||(t=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),_de=er((r,e)=>{"use strict";var t=o7();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),Ade=er(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=ah(),i=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),s=Symbol("handleMany"),c=Symbol("callback"),l=class extends e{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[o]=this[o].bind(this),this[s]=this[s].bind(this),this[c]=null}[o](f,p,h){let m=this[c];if(f)return m(f);p!==void 0&&(p=this[i](p)),m(f,p,h)}[s](f,p){let h=this[c];if(f)return h(f);for(let m of p){let y=m[0];y!==void 0&&(m[0]=this[i](y))}h(f,p)}},d=class extends t{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[o]=this[o].bind(this),this[s]=this[s].bind(this),this[c]=null}[o](f,p){let h=this[c];if(f)return h(f);p!==void 0&&(p=this[i](p)),h(f,p)}[s](f,p){let h=this[c];if(f)return h(f);for(let m=0;m<p.length;m++){let y=p[m];y!==void 0&&(p[m]=this[i](y))}h(f,p)}},u=class extends n{constructor(f,p,h){super(f,p),this[a]=h}};for(let f of[l,d])f.prototype._next=function(p){this[c]=p,this[a].next(this[o])},f.prototype._nextv=function(p,h,m){this[c]=m,this[a].nextv(p,h,this[s])},f.prototype._all=function(p,h){this[c]=h,this[a].all(p,this[s])};for(let f of[u])f.prototype._next=function(p){this[a].next(p)},f.prototype._nextv=function(p,h,m){this[a].nextv(p,h,m)},f.prototype._all=function(p,h){this[a].all(p,h)};for(let f of[l,d,u])f.prototype._seek=function(p,h){this[a].seek(p,h)},f.prototype._close=function(p){this[a].close(p)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=d,r.AbstractSublevelValueIterator=u}),Tde=er((r,e)=>{"use strict";var t=Od(),{Buffer:n}=xC()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Ade(),s=Symbol("prefix"),c=Symbol("upperBound"),l=Symbol("prefixRange"),d=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,p={separator:"!"};e.exports=function({AbstractLevel:x}){class _ extends x{static defaults(D){if(typeof D=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?p:D.separator?D:{...D,separator:"!"}}constructor(D,N,$){let{separator:z,manifest:L,...j}=_.defaults($);N=w(N,z);let H=z.charCodeAt(0)+1,Y=D[d]||D;if(!f.encode(N).every(P=>P>H&&P<127))throw new t(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(h(Y,L),j);let R=(D.prefix||"")+z+N+z,C=R.slice(0,-1)+String.fromCharCode(H);this[d]=Y,this[s]=new y(R),this[c]=new y(C),this[u]=new v,this.nextTick=Y.nextTick}prefixKey(D,N){if(N==="utf8")return this[s].utf8+D;if(D.byteLength===0)return this[s][N];if(N==="view"){let $=this[s].view,z=new Uint8Array($.byteLength+D.byteLength);return z.set($,0),z.set(D,$.byteLength),z}else{let $=this[s].buffer;return n.concat([$,D],$.byteLength+D.byteLength)}}[l](D,N){D.gte!==void 0?D.gte=this.prefixKey(D.gte,N):D.gt!==void 0?D.gt=this.prefixKey(D.gt,N):D.gte=this[s][N],D.lte!==void 0?D.lte=this.prefixKey(D.lte,N):D.lt!==void 0?D.lt=this.prefixKey(D.lt,N):D.lte=this[c][N]}get prefix(){return this[s].utf8}get db(){return this[d]}_open(D,N){this[d].open({passive:!0},N)}_put(D,N,$,z){this[d].put(D,N,$,z)}_get(D,N,$){this[d].get(D,N,$)}_getMany(D,N,$){this[d].getMany(D,N,$)}_del(D,N,$){this[d].del(D,N,$)}_batch(D,N,$){this[d].batch(D,N,$)}_clear(D,N){this[l](D,D.keyEncoding),this[d].clear(D,N)}_iterator(D){this[l](D,D.keyEncoding);let N=this[d].iterator(D),$=this[u].get(this[s].utf8.length,D.keyEncoding);return new i(this,D,N,$)}_keys(D){this[l](D,D.keyEncoding);let N=this[d].keys(D),$=this[u].get(this[s].utf8.length,D.keyEncoding);return new a(this,D,N,$)}_values(D){this[l](D,D.keyEncoding);let N=this[d].values(D);return new o(this,D,N)}}return{AbstractSublevel:_}};var h=function(x,_){return{...x.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(x,"utf8"),buffer:m(x,"buffer"),view:m(x,"view")}}},m=function(x,_){return x.supports.encodings[_]?x.keyEncoding(_).name===_:!1},y=class{constructor(x){this.utf8=x,this.view=f.encode(x),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(x,_){let A=this.cache.get(_);return A===void 0&&(_==="view"?A=(function(D,N){return N.subarray(D)}).bind(null,x):A=(function(D,N){return N.slice(D)}).bind(null,x),this.cache.set(_,A)),A}},w=function(x,_){let A=0,D=x.length;for(;A<D&&x[A]===_;)A++;for(;D>A&&x[D-1]===_;)D--;return x.slice(A,D)}}),N9=er(r=>{"use strict";var{supports:e}=mde(),{Transcoder:t}=vde(),{EventEmitter:n}=bde(),{fromCallback:i}=eE(),a=Od(),{AbstractIterator:o}=ah(),{DefaultKeyIterator:s,DefaultValueIterator:c}=xde(),{DeferredIterator:l,DeferredKeyIterator:d,DeferredValueIterator:u}=Ede(),{DefaultChainedBatch:f}=Sde(),{getCallback:p,getOptions:h}=EC(),m=kde(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),x=Symbol("closeResources"),_=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),j=Symbol("keyEncoding"),H=Symbol("valueEncoding"),Y=()=>{},R=class extends n{constructor(E,k){if(super(),typeof E!="object"||E===null)throw new TypeError("The first argument 'manifest' must be an object");k=h(k);let{keyEncoding:I,valueEncoding:K,passive:F,...V}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[N]=V,this[$]="opening",this.supports=e(E,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:E.snapshots!==!1,permanence:E.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:E.encodings||{},events:Object.assign({},E.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(S(this)),this[j]=this[L].encoding(I||"utf8"),this[H]=this[L].encoding(K||"utf8");for(let W of this[L].encodings())this.supports.encodings[W.commonName]||(this.supports.encodings[W.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[j].commonName,valueEncoding:this[H].commonName}),key:Object.freeze({keyEncoding:this[j].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},Y)})}get status(){return this[$]}keyEncoding(E){return this[L].encoding(E??this[j])}valueEncoding(E){return this[L].encoding(E??this[H])}open(E,k){k=p(E,k),k=i(k,y),E={...this[N],...h(E)},E.createIfMissing=E.createIfMissing!==!1,E.errorIfExists=!!E.errorIfExists;let I=K=>{this[$]==="closing"||this[$]==="opening"?this.once(v,K?()=>I(K):I):this[$]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:K})):k()};return E.passive?this[$]==="opening"?this.once(v,I):this.nextTick(I):this[$]==="closed"||this[D]?(this[D]=!1,this[$]="opening",this.emit("opening"),this._open(E,K=>{if(K){this[$]="closed",this[x](()=>{this.emit(v),I(K)}),this[A]();return}this[$]="open",this[A](),this.emit(v),this[$]==="open"&&this.emit("open"),this[$]==="open"&&this.emit("ready"),I()})):this[$]==="open"?this.nextTick(I):this.once(v,()=>this.open(E,k)),k[y]}_open(E,k){this.nextTick(k)}close(E){E=i(E,y);let k=I=>{this[$]==="opening"||this[$]==="closing"?this.once(v,I?k(I):k):this[$]!=="closed"?E(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):E()};if(this[$]==="open"){this[$]="closing",this.emit("closing");let I=K=>{this[$]="open",this[A](),this.emit(v),k(K)};this[x](()=>{this._close(K=>{if(K)return I(K);this[$]="closed",this[A](),this.emit(v),this[$]==="closed"&&this.emit("closed"),k()})})}else this[$]==="closed"?this.nextTick(k):this.once(v,()=>this.close(E));return E[y]}[x](E){if(this[w].size===0)return this.nextTick(E);let k=this[w].size,I=!0,K=()=>{--k===0&&(I?this.nextTick(E):E())};for(let F of this[w])F.close(K);I=!1,this[w].clear()}_close(E){this.nextTick(E)}get(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[$]==="opening")return this.defer(()=>this.get(E,k,I)),I[y];if(P(this,I))return I[y];let K=this._checkKey(E);if(K)return this.nextTick(I,K),I[y];let F=this.keyEncoding(k.keyEncoding),V=this.valueEncoding(k.valueEncoding),W=F.format,J=V.format;return(k.keyEncoding!==W||k.valueEncoding!==J)&&(k=Object.assign({},k,{keyEncoding:W,valueEncoding:J})),this._get(this.prefixKey(F.encode(E),W),k,(Q,q)=>{if(Q)return(Q.code==="LEVEL_NOT_FOUND"||Q.notFound||/NotFound/i.test(Q))&&(Q.code||(Q.code="LEVEL_NOT_FOUND"),Q.notFound||(Q.notFound=!0),Q.status||(Q.status=404)),I(Q);try{q=V.decode(q)}catch(ee){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:ee}))}I(null,q)}),I[y]}_get(E,k,I){this.nextTick(I,new Error("NotFound"))}getMany(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[$]==="opening")return this.defer(()=>this.getMany(E,k,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(E))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(E.length===0)return this.nextTick(I,null,[]),I[y];let K=this.keyEncoding(k.keyEncoding),F=this.valueEncoding(k.valueEncoding),V=K.format,W=F.format;(k.keyEncoding!==V||k.valueEncoding!==W)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:W}));let J=new Array(E.length);for(let Q=0;Q<E.length;Q++){let q=E[Q],ee=this._checkKey(q);if(ee)return this.nextTick(I,ee),I[y];J[Q]=this.prefixKey(K.encode(q),V)}return this._getMany(J,k,(Q,q)=>{if(Q)return I(Q);try{for(let ee=0;ee<q.length;ee++)q[ee]!==void 0&&(q[ee]=F.decode(q[ee]))}catch(ee){return I(new a(`Could not decode one or more of ${q.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:ee}))}I(null,q)}),I[y]}_getMany(E,k,I){this.nextTick(I,null,new Array(E.length).fill(void 0))}put(E,k,I,K){if(K=p(I,K),K=i(K,y),I=h(I,this[z].entry),this[$]==="opening")return this.defer(()=>this.put(E,k,I,K)),K[y];if(P(this,K))return K[y];let F=this._checkKey(E)||this._checkValue(k);if(F)return this.nextTick(K,F),K[y];let V=this.keyEncoding(I.keyEncoding),W=this.valueEncoding(I.valueEncoding),J=V.format,Q=W.format;(I.keyEncoding!==J||I.valueEncoding!==Q)&&(I=Object.assign({},I,{keyEncoding:J,valueEncoding:Q}));let q=this.prefixKey(V.encode(E),J),ee=W.encode(k);return this._put(q,ee,I,se=>{if(se)return K(se);this.emit("put",E,k),K()}),K[y]}_put(E,k,I,K){this.nextTick(K)}del(E,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].key),this[$]==="opening")return this.defer(()=>this.del(E,k,I)),I[y];if(P(this,I))return I[y];let K=this._checkKey(E);if(K)return this.nextTick(I,K),I[y];let F=this.keyEncoding(k.keyEncoding),V=F.format;return k.keyEncoding!==V&&(k=Object.assign({},k,{keyEncoding:V})),this._del(this.prefixKey(F.encode(E),V),k,W=>{if(W)return I(W);this.emit("del",E),I()}),I[y]}_del(E,k,I){this.nextTick(I)}batch(E,k,I){if(!arguments.length){if(this[$]==="opening")return new f(this);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof E=="function"?I=E:I=p(k,I),I=i(I,y),k=h(k,this[z].empty),this[$]==="opening")return this.defer(()=>this.batch(E,k,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(E))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(E.length===0)return this.nextTick(I),I[y];let K=new Array(E.length),{keyEncoding:F,valueEncoding:V,...W}=k;for(let J=0;J<E.length;J++){if(typeof E[J]!="object"||E[J]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Q=Object.assign({},E[J]);if(Q.type!=="put"&&Q.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let q=this._checkKey(Q.key);if(q)return this.nextTick(I,q),I[y];let ee=Q.sublevel!=null?Q.sublevel:this,se=ee.keyEncoding(Q.keyEncoding||F),ne=se.format;if(Q.key=ee.prefixKey(se.encode(Q.key),ne),Q.keyEncoding=ne,Q.type==="put"){let X=this._checkValue(Q.value);if(X)return this.nextTick(I,X),I[y];let le=ee.valueEncoding(Q.valueEncoding||V);Q.value=le.encode(Q.value),Q.valueEncoding=le.format}ee!==this&&(Q.sublevel=null),K[J]=Q}return this._batch(K,W,J=>{if(J)return I(J);this.emit("batch",E),I()}),I[y]}_batch(E,k,I){this.nextTick(I)}sublevel(E,k){return this._sublevel(E,C.defaults(k))}_sublevel(E,k){return new C(this,E,k)}prefixKey(E,k){return E}clear(E,k){if(k=p(E,k),k=i(k,y),E=h(E,this[z].empty),this[$]==="opening")return this.defer(()=>this.clear(E,k)),k[y];if(P(this,k))return k[y];let I=E,K=this.keyEncoding(E.keyEncoding);return E=m(E,K),E.keyEncoding=K.format,E.limit===0?this.nextTick(k):this._clear(E,F=>{if(F)return k(F);this.emit("clear",I),k()}),k[y]}_clear(E,k){this.nextTick(k)}iterator(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E.keys=E.keys!==!1,E.values=E.values!==!1,E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new l(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(E)}_iterator(E){return new o(this,E)}keys(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new d(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(E)}_keys(E){return new s(this,E)}values(E){let k=this.keyEncoding(E&&E.keyEncoding),I=this.valueEncoding(E&&E.valueEncoding);if(E=m(E,k),E[o.keyEncoding]=k,E[o.valueEncoding]=I,E.keyEncoding=k.format,E.valueEncoding=I.format,this[$]==="opening")return new u(this,E);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(E)}_values(E){return new c(this,E)}defer(E){if(typeof E!="function")throw new TypeError("The first argument must be a function");this[_].push(E)}[A](){if(this[_].length===0)return;let E=this[_];this[_]=[];for(let k of E)k()}attachResource(E){if(typeof E!="object"||E===null||typeof E.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(E)}detachResource(E){this[w].delete(E)}_chainedBatch(){return new f(this)}_checkKey(E){if(E==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(E){if(E==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=_de();var{AbstractSublevel:C}=Tde()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=C;var P=function(E,k){return E[$]!=="open"?(E.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},S=function(E){return Object.keys(E.supports.encodings).filter(k=>!!E.supports.encodings[k])}}),a7=er(r=>{"use strict";r.AbstractLevel=N9().AbstractLevel,r.AbstractSublevel=N9().AbstractSublevel,r.AbstractIterator=ah().AbstractIterator,r.AbstractKeyIterator=ah().AbstractKeyIterator,r.AbstractValueIterator=ah().AbstractValueIterator,r.AbstractChainedBatch=s7().AbstractChainedBatch}),Ide=er((r,e)=>{e.exports=n;var t=o7();function n(i,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let s,c,l,d,u,f=!0,p;Array.isArray(i)?(s=[],l=c=i.length):(d=Object.keys(i),s={},l=c=d.length);function h(y){function v(){o&&o(y,s),o=null}f?t(v):v()}function m(y,v,w){if(s[y]=w,v&&(u=!0),--l===0||v)h(v);else if(!u&&p<c){let x;d?(x=d[p],p+=1,i[x](function(_,A){m(x,_,A)})):(x=p,p+=1,i[x](function(_,A){m(x,_,A)}))}}p=a,l?d?d.some(function(y,v){return i[y](function(w,x){m(y,w,x)}),v===a-1}):i.some(function(y,v){return y(function(w,x){m(v,w,x)}),v===a-1}):h(null),f=!1}}),c7=er((r,e)=>{"use strict";e.exports=function(t){let n=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,i=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,a=t.gte===void 0,o=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):i!==void 0?IDBKeyRange.upperBound(i,o):null}}),d7=er((r,e)=>{"use strict";var t=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):t.encode(n)}}),Dde=er(r=>{"use strict";var{AbstractIterator:e}=a7(),t=c7(),n=d7(),i=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),s=Symbol("currentOptions"),c=Symbol("position"),l=Symbol("location"),d=Symbol("first"),u={},f=class extends e{constructor(h,m,y){super(h,y),this[i]=[],this[a]=this.limit===0,this[o]=y,this[s]={...y},this[c]=void 0,this[l]=m,this[d]=!0}_nextv(h,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return h=Math.min(h,this[i].length),this.nextTick(y,null,this[i].splice(0,h));this[c]!==void 0&&(this[o].reverse?(this[s].lt=this[c],this[s].lte=void 0):(this[s].gt=this[c],this[s].gte=void 0));let v;try{v=t(this[s])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),x=w.objectStore(this[l]),_=[];if(this[o].reverse){let A=!this[o].values&&x.openKeyCursor?"openKeyCursor":"openCursor";x[A](v,"prev").onsuccess=D=>{let N=D.target.result;if(N){let{key:$,value:z}=N;this[c]=$,_.push([this[o].keys&&$!==void 0?n($):void 0,this[o].values&&z!==void 0?n(z):void 0]),_.length<h?N.continue():p(w)}else this[a]=!0}}else{let A,D,N=()=>{if(A===void 0||D===void 0)return;let $=Math.max(A.length,D.length);$===0||h===1/0?this[a]=!0:this[c]=A[$-1],_.length=$;for(let z=0;z<$;z++){let L=A[z],j=D[z];_[z]=[this[o].keys&&L!==void 0?n(L):void 0,this[o].values&&j!==void 0?n(j):void 0]}p(w)};this[o].keys||h<1/0?x.getAllKeys(v,h<1/0?h:void 0).onsuccess=$=>{A=$.target.result,N()}:(A=[],this.nextTick(N)),this[o].values?x.getAll(v,h<1/0?h:void 0).onsuccess=$=>{D=$.target.result,N()}:(D=[],this.nextTick(N))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(h){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(h,null,m,y)}else if(this[a])this.nextTick(h);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return h(y);this[i]=v,this._next(h)})}}_all(h,m){this[d]=!1;let y=this[i].splice(0,this[i].length),v=this.limit-this.count-y.length;if(v<=0)return this.nextTick(m,null,y);this._nextv(v,u,(w,x)=>{if(w)return m(w);y.length>0&&(x=y.concat(x)),m(null,x)})}_seek(h,m){this[d]=!0,this[i]=[],this[a]=!1,this[c]=void 0,this[s]={...this[o]};let y;try{y=t(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(h)?this[a]=!0:this[o].reverse?this[s].lte=h:this[s].gte=h}};r.Iterator=f;function p(h){typeof h.commit=="function"&&h.commit()}}),Rde=er((r,e)=>{"use strict";e.exports=function(t,n,i,a,o){if(a.limit===0)return t.nextTick(o);let s=t.db.transaction([n],"readwrite"),c=s.objectStore(n),l=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";c[d](i,u).onsuccess=function(f){let p=f.target.result;p&&(c.delete(p.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&p.continue()})}}}),Cde=er(r=>{"use strict";var{AbstractLevel:e}=a7(),t=Od(),n=Ide(),{fromCallback:i}=eE(),{Iterator:a}=Dde(),o=d7(),s=Rde(),c=c7(),l="level-js-",d=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),p=Symbol("version"),h=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,x,_){if(typeof x=="function"||typeof _=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...N}=x||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=A??l,this[p]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[p]}get db(){return this[d]}get type(){return"browser-level"}_open(w,x){let _=indexedDB.open(this[u]+this[f],this[p]);_.onerror=function(){x(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,x()},_.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[h](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,x){let _=w.transaction;_.onabort=function(){x(_.error||new Error("aborted by user"))},_.oncomplete=function(){x(null,w.result)}}_get(w,x,_){let A=this[h]("readonly"),D;try{D=A.get(w)}catch(N){return this.nextTick(_,N)}this[m](D,function(N,$){if(N)return _(N);if($===void 0)return _(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(w,x,_){let A=this[h]("readonly"),D=w.map(N=>$=>{let z;try{z=A.get(N)}catch(L){return $(L)}z.onsuccess=()=>{let L=z.result;$(null,L===void 0?L:o(L))},z.onerror=L=>{L.stopPropagation(),$(z.error)}});n(D,16,_)}_del(w,x,_){let A=this[h]("readwrite"),D;try{D=A.delete(w)}catch(N){return this.nextTick(_,N)}this[m](D,_)}_put(w,x,_,A){let D=this[h]("readwrite"),N;try{N=D.put(x,w)}catch($){return this.nextTick(A,$)}this[m](N,A)}_iterator(w){return new a(this,this[f],w)}_batch(w,x,_){let A=this[h]("readwrite"),D=A.transaction,N=0,$;D.onabort=function(){_($||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function z(){let L=w[N++],j=L.key,H;try{H=L.type==="del"?A.delete(j):A.put(L.value,j)}catch(Y){$=Y,D.abort();return}N<w.length?H.onsuccess=z:typeof D.commit=="function"&&D.commit()}z()}_clear(w,x){let _,A;try{_=c(w)}catch{return this.nextTick(x)}if(w.limit>=0)return s(this,this[f],_,w,x);try{let D=this[h]("readwrite");A=_?D.delete(_):D.clear()}catch(D){return this.nextTick(x,D)}this[m](A,x)}_close(w){this[d].close(),this.nextTick(w)}};v.destroy=function(w,x,_){typeof x=="function"&&(_=x,x=l),_=i(_,y);let A=indexedDB.deleteDatabase(x+w);return A.onsuccess=function(){_()},A.onerror=function(D){_(D)},_[y]},r.BrowserLevel=v}),l7=er(r=>{r.Level=Cde().BrowserLevel}),$de=er((r,e)=>{(function(t,n){typeof r=="object"&&typeof e<"u"?n(r):typeof define=="function"&&define.amd?define(["exports"],n):n(t.URI=t.URI||{})})(r,function(t){"use strict";function n(){for(var Z=arguments.length,oe=Array(Z),ae=0;ae<Z;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var be=oe.length-1,Ee=1;Ee<be;++Ee)oe[Ee]=oe[Ee].slice(1,-1);return oe[be]=oe[be].slice(1),oe.join("")}else return oe[0]}function i(Z){return"(?:"+Z+")"}function a(Z){return Z===void 0?"undefined":Z===null?"null":Object.prototype.toString.call(Z).split(" ").pop().split("]").shift().toLowerCase()}function o(Z){return Z.toUpperCase()}function s(Z){return Z!=null?Z instanceof Array?Z:typeof Z.length!="number"||Z.split||Z.setInterval||Z.call?[Z]:Array.prototype.slice.call(Z):[]}function c(Z,oe){var ae=Z;if(oe)for(var be in oe)ae[be]=oe[be];return ae}function l(Z){var oe="[A-Za-z]",ae="[\\x0D]",be="[0-9]",Ee="[\\x22]",We=n(be,"[A-Fa-f]"),Nt="[\\x0A]",Pr="[\\x20]",Qr=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),en="[\\:\\/\\?\\#\\[\\]\\@]",pr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",An=n(en,pr),Qn=Z?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",wn=Z?"[\\uE000-\\uF8FF]":"[]",Cr=n(oe,be,"[\\-\\.\\_\\~]",Qn),Tr=i(oe+n(oe,be,"[\\+\\-\\.]")+"*"),cs=i(i(Qr+"|"+n(Cr,pr,"[\\:]"))+"*"),Ig=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),Qs=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),Ga=i(Qs+"\\."+Qs+"\\."+Qs+"\\."+Qs),$r=i(We+"{1,4}"),Eo=i(i($r+"\\:"+$r)+"|"+Ga),ia=i(i($r+"\\:")+"{6}"+Eo),Kd=i("\\:\\:"+i($r+"\\:")+"{5}"+Eo),Mf=i(i($r)+"?\\:\\:"+i($r+"\\:")+"{4}"+Eo),Cc=i(i(i($r+"\\:")+"{0,1}"+$r)+"?\\:\\:"+i($r+"\\:")+"{3}"+Eo),Rb=i(i(i($r+"\\:")+"{0,2}"+$r)+"?\\:\\:"+i($r+"\\:")+"{2}"+Eo),Cb=i(i(i($r+"\\:")+"{0,3}"+$r)+"?\\:\\:"+$r+"\\:"+Eo),Nh=i(i(i($r+"\\:")+"{0,4}"+$r)+"?\\:\\:"+Eo),Uh=i(i(i($r+"\\:")+"{0,5}"+$r)+"?\\:\\:"+$r),Lh=i(i(i($r+"\\:")+"{0,6}"+$r)+"?\\:\\:"),Kf=i([ia,Kd,Mf,Cc,Rb,Cb,Nh,Uh,Lh].join("|")),qh=i(i(Cr+"|"+Qr)+"+"),zh=i(Kf+"\\%25"+qh),sV=i(Kf+i("\\%25|\\%(?!"+We+"{2})")+qh),oV=i("[vV]"+We+"+\\."+n(Cr,pr,"[\\:]")+"+"),aV=i("\\["+i(sV+"|"+Kf+"|"+oV)+"\\]"),i5=i(i(Qr+"|"+n(Cr,pr))+"*"),Dg=i(aV+"|"+Ga+"(?!"+i5+")|"+i5),Rg=i(be+"*"),s5=i(i(cs+"@")+"?"+Dg+i("\\:"+Rg)+"?"),Cg=i(Qr+"|"+n(Cr,pr,"[\\:\\@]")),cV=i(Cg+"*"),o5=i(Cg+"+"),dV=i(i(Qr+"|"+n(Cr,pr,"[\\@]"))+"+"),Nd=i(i("\\/"+cV)+"*"),Fh=i("\\/"+i(o5+Nd)+"?"),pS=i(dV+Nd),$b=i(o5+Nd),Gh="(?!"+Cg+")",iwe=i(Nd+"|"+Fh+"|"+pS+"|"+$b+"|"+Gh),Hh=i(i(Cg+"|"+n("[\\/\\?]",wn))+"*"),$g=i(i(Cg+"|[\\/\\?]")+"*"),a5=i(i("\\/\\/"+s5+Nd)+"|"+Fh+"|"+$b+"|"+Gh),lV=i(Tr+"\\:"+a5+i("\\?"+Hh)+"?"+i("\\#"+$g)+"?"),uV=i(i("\\/\\/"+s5+Nd)+"|"+Fh+"|"+pS+"|"+Gh),fV=i(uV+i("\\?"+Hh)+"?"+i("\\#"+$g)+"?"),swe=i(lV+"|"+fV),owe=i(Tr+"\\:"+a5+i("\\?"+Hh)+"?"),awe="^("+Tr+")\\:"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+$b+"|"+Gh+")")+i("\\?("+Hh+")")+"?"+i("\\#("+$g+")")+"?$",cwe="^(){0}"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+pS+"|"+Gh+")")+i("\\?("+Hh+")")+"?"+i("\\#("+$g+")")+"?$",dwe="^("+Tr+")\\:"+i(i("\\/\\/("+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?)")+"?("+Nd+"|"+Fh+"|"+$b+"|"+Gh+")")+i("\\?("+Hh+")")+"?$",lwe="^"+i("\\#("+$g+")")+"?$",uwe="^"+i("("+cs+")@")+"?("+Dg+")"+i("\\:("+Rg+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Cr,pr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Cr,pr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Cr,pr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Cr,pr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Cr,pr,"[\\:\\@\\/\\?]",wn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Cr,pr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Cr,pr),"g"),UNRESERVED:new RegExp(Cr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Cr,An),"g"),PCT_ENCODED:new RegExp(Qr,"g"),IPV4ADDRESS:new RegExp("^("+Ga+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Kf+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+qh+")")+"?\\]?$")}}var d=l(!1),u=l(!0),f=function(){function Z(oe,ae){var be=[],Ee=!0,We=!1,Nt=void 0;try{for(var Pr=oe[Symbol.iterator](),Qr;!(Ee=(Qr=Pr.next()).done)&&(be.push(Qr.value),!(ae&&be.length===ae));Ee=!0);}catch(en){We=!0,Nt=en}finally{try{!Ee&&Pr.return&&Pr.return()}finally{if(We)throw Nt}}return be}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Z(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),p=function(Z){if(Array.isArray(Z)){for(var oe=0,ae=Array(Z.length);oe<Z.length;oe++)ae[oe]=Z[oe];return ae}else return Array.from(Z)},h=2147483647,m=36,y=1,v=26,w=38,x=700,_=72,A=128,D="-",N=/^xn--/,$=/[^\0-\x7E]/,z=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=m-y,H=Math.floor,Y=String.fromCharCode;function R(Z){throw new RangeError(L[Z])}function C(Z,oe){for(var ae=[],be=Z.length;be--;)ae[be]=oe(Z[be]);return ae}function P(Z,oe){var ae=Z.split("@"),be="";ae.length>1&&(be=ae[0]+"@",Z=ae[1]),Z=Z.replace(z,".");var Ee=Z.split("."),We=C(Ee,oe).join(".");return be+We}function S(Z){for(var oe=[],ae=0,be=Z.length;ae<be;){var Ee=Z.charCodeAt(ae++);if(Ee>=55296&&Ee<=56319&&ae<be){var We=Z.charCodeAt(ae++);(We&64512)==56320?oe.push(((Ee&1023)<<10)+(We&1023)+65536):(oe.push(Ee),ae--)}else oe.push(Ee)}return oe}var E=function(Z){return String.fromCodePoint.apply(String,p(Z))},k=function(Z){return Z-48<10?Z-22:Z-65<26?Z-65:Z-97<26?Z-97:m},I=function(Z,oe){return Z+22+75*(Z<26)-((oe!=0)<<5)},K=function(Z,oe,ae){var be=0;for(Z=ae?H(Z/x):Z>>1,Z+=H(Z/oe);Z>j*v>>1;be+=m)Z=H(Z/j);return H(be+(j+1)*Z/(Z+w))},F=function(Z){var oe=[],ae=Z.length,be=0,Ee=A,We=_,Nt=Z.lastIndexOf(D);Nt<0&&(Nt=0);for(var Pr=0;Pr<Nt;++Pr)Z.charCodeAt(Pr)>=128&&R("not-basic"),oe.push(Z.charCodeAt(Pr));for(var Qr=Nt>0?Nt+1:0;Qr<ae;){for(var en=be,pr=1,An=m;;An+=m){Qr>=ae&&R("invalid-input");var Qn=k(Z.charCodeAt(Qr++));(Qn>=m||Qn>H((h-be)/pr))&&R("overflow"),be+=Qn*pr;var wn=An<=We?y:An>=We+v?v:An-We;if(Qn<wn)break;var Cr=m-wn;pr>H(h/Cr)&&R("overflow"),pr*=Cr}var Tr=oe.length+1;We=K(be-en,Tr,en==0),H(be/Tr)>h-Ee&&R("overflow"),Ee+=H(be/Tr),be%=Tr,oe.splice(be++,0,Ee)}return String.fromCodePoint.apply(String,oe)},V=function(Z){var oe=[];Z=S(Z);var ae=Z.length,be=A,Ee=0,We=_,Nt=!0,Pr=!1,Qr=void 0;try{for(var en=Z[Symbol.iterator](),pr;!(Nt=(pr=en.next()).done);Nt=!0){var An=pr.value;An<128&&oe.push(Y(An))}}catch(zh){Pr=!0,Qr=zh}finally{try{!Nt&&en.return&&en.return()}finally{if(Pr)throw Qr}}var Qn=oe.length,wn=Qn;for(Qn&&oe.push(D);wn<ae;){var Cr=h,Tr=!0,cs=!1,Ig=void 0;try{for(var Qs=Z[Symbol.iterator](),Ga;!(Tr=(Ga=Qs.next()).done);Tr=!0){var $r=Ga.value;$r>=be&&$r<Cr&&(Cr=$r)}}catch(zh){cs=!0,Ig=zh}finally{try{!Tr&&Qs.return&&Qs.return()}finally{if(cs)throw Ig}}var Eo=wn+1;Cr-be>H((h-Ee)/Eo)&&R("overflow"),Ee+=(Cr-be)*Eo,be=Cr;var ia=!0,Kd=!1,Mf=void 0;try{for(var Cc=Z[Symbol.iterator](),Rb;!(ia=(Rb=Cc.next()).done);ia=!0){var Cb=Rb.value;if(Cb<be&&++Ee>h&&R("overflow"),Cb==be){for(var Nh=Ee,Uh=m;;Uh+=m){var Lh=Uh<=We?y:Uh>=We+v?v:Uh-We;if(Nh<Lh)break;var Kf=Nh-Lh,qh=m-Lh;oe.push(Y(I(Lh+Kf%qh,0))),Nh=H(Kf/qh)}oe.push(Y(I(Nh,0))),We=K(Ee,Eo,wn==Qn),Ee=0,++wn}}}catch(zh){Kd=!0,Mf=zh}finally{try{!ia&&Cc.return&&Cc.return()}finally{if(Kd)throw Mf}}++Ee,++be}return oe.join("")},W=function(Z){return P(Z,function(oe){return N.test(oe)?F(oe.slice(4).toLowerCase()):oe})},J=function(Z){return P(Z,function(oe){return $.test(oe)?"xn--"+V(oe):oe})},Q={version:"2.1.0",ucs2:{decode:S,encode:E},decode:F,encode:V,toASCII:J,toUnicode:W},q={};function ee(Z){var oe=Z.charCodeAt(0),ae=void 0;return oe<16?ae="%0"+oe.toString(16).toUpperCase():oe<128?ae="%"+oe.toString(16).toUpperCase():oe<2048?ae="%"+(oe>>6|192).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase():ae="%"+(oe>>12|224).toString(16).toUpperCase()+"%"+(oe>>6&63|128).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase(),ae}function se(Z){for(var oe="",ae=0,be=Z.length;ae<be;){var Ee=parseInt(Z.substr(ae+1,2),16);if(Ee<128)oe+=String.fromCharCode(Ee),ae+=3;else if(Ee>=194&&Ee<224){if(be-ae>=6){var We=parseInt(Z.substr(ae+4,2),16);oe+=String.fromCharCode((Ee&31)<<6|We&63)}else oe+=Z.substr(ae,6);ae+=6}else if(Ee>=224){if(be-ae>=9){var Nt=parseInt(Z.substr(ae+4,2),16),Pr=parseInt(Z.substr(ae+7,2),16);oe+=String.fromCharCode((Ee&15)<<12|(Nt&63)<<6|Pr&63)}else oe+=Z.substr(ae,9);ae+=9}else oe+=Z.substr(ae,3),ae+=3}return oe}function ne(Z,oe){function ae(be){var Ee=se(be);return Ee.match(oe.UNRESERVED)?Ee:be}return Z.scheme&&(Z.scheme=String(Z.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Z.userinfo!==void 0&&(Z.userinfo=String(Z.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,ee).replace(oe.PCT_ENCODED,o)),Z.host!==void 0&&(Z.host=String(Z.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,ee).replace(oe.PCT_ENCODED,o)),Z.path!==void 0&&(Z.path=String(Z.path).replace(oe.PCT_ENCODED,ae).replace(Z.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,ee).replace(oe.PCT_ENCODED,o)),Z.query!==void 0&&(Z.query=String(Z.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,ee).replace(oe.PCT_ENCODED,o)),Z.fragment!==void 0&&(Z.fragment=String(Z.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,ee).replace(oe.PCT_ENCODED,o)),Z}function X(Z){return Z.replace(/^0*(.*)/,"$1")||"0"}function le(Z,oe){var ae=Z.match(oe.IPV4ADDRESS)||[],be=f(ae,2),Ee=be[1];return Ee?Ee.split(".").map(X).join("."):Z}function ue(Z,oe){var ae=Z.match(oe.IPV6ADDRESS)||[],be=f(ae,3),Ee=be[1],We=be[2];if(Ee){for(var Nt=Ee.toLowerCase().split("::").reverse(),Pr=f(Nt,2),Qr=Pr[0],en=Pr[1],pr=en?en.split(":").map(X):[],An=Qr.split(":").map(X),Qn=oe.IPV4ADDRESS.test(An[An.length-1]),wn=Qn?7:8,Cr=An.length-wn,Tr=Array(wn),cs=0;cs<wn;++cs)Tr[cs]=pr[cs]||An[Cr+cs]||"";Qn&&(Tr[wn-1]=le(Tr[wn-1],oe));var Ig=Tr.reduce(function(ia,Kd,Mf){if(!Kd||Kd==="0"){var Cc=ia[ia.length-1];Cc&&Cc.index+Cc.length===Mf?Cc.length++:ia.push({index:Mf,length:1})}return ia},[]),Qs=Ig.sort(function(ia,Kd){return Kd.length-ia.length})[0],Ga=void 0;if(Qs&&Qs.length>1){var $r=Tr.slice(0,Qs.index),Eo=Tr.slice(Qs.index+Qs.length);Ga=$r.join(":")+"::"+Eo.join(":")}else Ga=Tr.join(":");return We&&(Ga+="%"+We),Ga}else return Z}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,xe="".match(/(){0}/)[1]===void 0;function de(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},be=oe.iri!==!1?u:d;oe.reference==="suffix"&&(Z=(oe.scheme?oe.scheme+":":"")+"//"+Z);var Ee=Z.match(pe);if(Ee){xe?(ae.scheme=Ee[1],ae.userinfo=Ee[3],ae.host=Ee[4],ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Ee[7],ae.fragment=Ee[8],isNaN(ae.port)&&(ae.port=Ee[5])):(ae.scheme=Ee[1]||void 0,ae.userinfo=Z.indexOf("@")!==-1?Ee[3]:void 0,ae.host=Z.indexOf("//")!==-1?Ee[4]:void 0,ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Z.indexOf("?")!==-1?Ee[7]:void 0,ae.fragment=Z.indexOf("#")!==-1?Ee[8]:void 0,isNaN(ae.port)&&(ae.port=Z.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Ee[4]:void 0)),ae.host&&(ae.host=ue(le(ae.host,be),be)),ae.scheme===void 0&&ae.userinfo===void 0&&ae.host===void 0&&ae.port===void 0&&!ae.path&&ae.query===void 0?ae.reference="same-document":ae.scheme===void 0?ae.reference="relative":ae.fragment===void 0?ae.reference="absolute":ae.reference="uri",oe.reference&&oe.reference!=="suffix"&&oe.reference!==ae.reference&&(ae.error=ae.error||"URI is not a "+oe.reference+" reference.");var We=q[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!We||!We.unicodeSupport)){if(ae.host&&(oe.domainHost||We&&We.domainHost))try{ae.host=Q.toASCII(ae.host.replace(be.PCT_ENCODED,se).toLowerCase())}catch(Nt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Nt}ne(ae,d)}else ne(ae,be);We&&We.parse&&We.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Pe(Z,oe){var ae=oe.iri!==!1?u:d,be=[];return Z.userinfo!==void 0&&(be.push(Z.userinfo),be.push("@")),Z.host!==void 0&&be.push(ue(le(String(Z.host),ae),ae).replace(ae.IPV6ADDRESS,function(Ee,We,Nt){return"["+We+(Nt?"%25"+Nt:"")+"]"})),(typeof Z.port=="number"||typeof Z.port=="string")&&(be.push(":"),be.push(String(Z.port))),be.length?be.join(""):void 0}var Ne=/^\.\.?\//,He=/^\/\.(\/|$)/,Je=/^\/\.\.(\/|$)/,Bt=/^\/?(?:.|\n)*?(?=\/|$)/;function _e(Z){for(var oe=[];Z.length;)if(Z.match(Ne))Z=Z.replace(Ne,"");else if(Z.match(He))Z=Z.replace(He,"/");else if(Z.match(Je))Z=Z.replace(Je,"/"),oe.pop();else if(Z==="."||Z==="..")Z="";else{var ae=Z.match(Bt);if(ae){var be=ae[0];Z=Z.slice(be.length),oe.push(be)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function at(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:d,be=[],Ee=q[(oe.scheme||Z.scheme||"").toLowerCase()];if(Ee&&Ee.serialize&&Ee.serialize(Z,oe),Z.host&&!ae.IPV6ADDRESS.test(Z.host)&&(oe.domainHost||Ee&&Ee.domainHost))try{Z.host=oe.iri?Q.toUnicode(Z.host):Q.toASCII(Z.host.replace(ae.PCT_ENCODED,se).toLowerCase())}catch(Pr){Z.error=Z.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+Pr}ne(Z,ae),oe.reference!=="suffix"&&Z.scheme&&(be.push(Z.scheme),be.push(":"));var We=Pe(Z,oe);if(We!==void 0&&(oe.reference!=="suffix"&&be.push("//"),be.push(We),Z.path&&Z.path.charAt(0)!=="/"&&be.push("/")),Z.path!==void 0){var Nt=Z.path;!oe.absolutePath&&(!Ee||!Ee.absolutePath)&&(Nt=_e(Nt)),We===void 0&&(Nt=Nt.replace(/^\/\//,"/%2F")),be.push(Nt)}return Z.query!==void 0&&(be.push("?"),be.push(Z.query)),Z.fragment!==void 0&&(be.push("#"),be.push(Z.fragment)),be.join("")}function It(Z,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Ee={};return be||(Z=de(at(Z,ae),ae),oe=de(at(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Ee.scheme=oe.scheme,Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=_e(oe.path||""),Ee.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=_e(oe.path||""),Ee.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Ee.path=_e(oe.path):((Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)&&!Z.path?Ee.path="/"+oe.path:Z.path?Ee.path=Z.path.slice(0,Z.path.lastIndexOf("/")+1)+oe.path:Ee.path=oe.path,Ee.path=_e(Ee.path)),Ee.query=oe.query):(Ee.path=Z.path,oe.query!==void 0?Ee.query=oe.query:Ee.query=Z.query),Ee.userinfo=Z.userinfo,Ee.host=Z.host,Ee.port=Z.port),Ee.scheme=Z.scheme),Ee.fragment=oe.fragment,Ee}function $t(Z,oe,ae){var be=c({scheme:"null"},ae);return at(It(de(Z,be),de(oe,be),be,!0),be)}function Ht(Z,oe){return typeof Z=="string"?Z=at(de(Z,oe),oe):a(Z)==="object"&&(Z=de(at(Z,oe),oe)),Z}function T(Z,oe,ae){return typeof Z=="string"?Z=at(de(Z,ae),ae):a(Z)==="object"&&(Z=at(Z,ae)),typeof oe=="string"?oe=at(de(oe,ae),ae):a(oe)==="object"&&(oe=at(oe,ae)),Z===oe}function M(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?d.ESCAPE:u.ESCAPE,ee)}function U(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?d.PCT_ENCODED:u.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(Z,oe){return Z.host||(Z.error=Z.error||"HTTP URIs must have a host."),Z},serialize:function(Z,oe){var ae=String(Z.scheme).toLowerCase()==="https";return(Z.port===(ae?443:80)||Z.port==="")&&(Z.port=void 0),Z.path||(Z.path="/"),Z}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(Z){return typeof Z.secure=="boolean"?Z.secure:String(Z.scheme).toLowerCase()==="wss"}var ke={scheme:"ws",domainHost:!0,parse:function(Z,oe){var ae=Z;return ae.secure=ge(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Z,oe){if((Z.port===(ge(Z)?443:80)||Z.port==="")&&(Z.port=void 0),typeof Z.secure=="boolean"&&(Z.scheme=Z.secure?"wss":"ws",Z.secure=void 0),Z.resourceName){var ae=Z.resourceName.split("?"),be=f(ae,2),Ee=be[0],We=be[1];Z.path=Ee&&Ee!=="/"?Ee:void 0,Z.query=We,Z.resourceName=void 0}return Z.fragment=void 0,Z}},Vt={scheme:"wss",domainHost:ke.domainHost,parse:ke.parse,serialize:ke.serialize},ni={},Vr=!0,Ar="[A-Za-z0-9\\-\\.\\_\\~"+(Vr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",gr="[0-9A-Fa-f]",JH=i(i("%[EFef]"+gr+"%"+gr+gr+"%"+gr+gr)+"|"+i("%[89A-Fa-f]"+gr+"%"+gr+gr)+"|"+i("%"+gr+gr)),ZH="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",YH="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",XH=n(YH,'[\\"\\\\]'),QH="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",eV=new RegExp(Ar,"g"),Kh=new RegExp(JH,"g"),tV=new RegExp(n("[^]",ZH,"[\\.]",'[\\"]',XH),"g"),e5=new RegExp(n("[^]",Ar,QH),"g"),rV=e5;function fS(Z){var oe=se(Z);return oe.match(eV)?oe:Z}var t5={scheme:"mailto",parse:function(Z,oe){var ae=Z,be=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Ee=!1,We={},Nt=ae.query.split("&"),Pr=0,Qr=Nt.length;Pr<Qr;++Pr){var en=Nt[Pr].split("=");switch(en[0]){case"to":for(var pr=en[1].split(","),An=0,Qn=pr.length;An<Qn;++An)be.push(pr[An]);break;case"subject":ae.subject=U(en[1],oe);break;case"body":ae.body=U(en[1],oe);break;default:Ee=!0,We[U(en[0],oe)]=U(en[1],oe);break}}Ee&&(ae.headers=We)}ae.query=void 0;for(var wn=0,Cr=be.length;wn<Cr;++wn){var Tr=be[wn].split("@");if(Tr[0]=U(Tr[0]),oe.unicodeSupport)Tr[1]=U(Tr[1],oe).toLowerCase();else try{Tr[1]=Q.toASCII(U(Tr[1],oe).toLowerCase())}catch(cs){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+cs}be[wn]=Tr.join("@")}return ae},serialize:function(Z,oe){var ae=Z,be=s(Z.to);if(be){for(var Ee=0,We=be.length;Ee<We;++Ee){var Nt=String(be[Ee]),Pr=Nt.lastIndexOf("@"),Qr=Nt.slice(0,Pr).replace(Kh,fS).replace(Kh,o).replace(tV,ee),en=Nt.slice(Pr+1);try{en=oe.iri?Q.toUnicode(en):Q.toASCII(U(en,oe).toLowerCase())}catch(wn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+wn}be[Ee]=Qr+"@"+en}ae.path=be.join(",")}var pr=Z.headers=Z.headers||{};Z.subject&&(pr.subject=Z.subject),Z.body&&(pr.body=Z.body);var An=[];for(var Qn in pr)pr[Qn]!==ni[Qn]&&An.push(Qn.replace(Kh,fS).replace(Kh,o).replace(e5,ee)+"="+pr[Qn].replace(Kh,fS).replace(Kh,o).replace(rV,ee));return An.length&&(ae.query=An.join("&")),ae}},nV=/^([^\:]+)\:(.*)/,r5={scheme:"urn",parse:function(Z,oe){var ae=Z.path&&Z.path.match(nV),be=Z;if(ae){var Ee=oe.scheme||be.scheme||"urn",We=ae[1].toLowerCase(),Nt=ae[2],Pr=Ee+":"+(oe.nid||We),Qr=q[Pr];be.nid=We,be.nss=Nt,be.path=void 0,Qr&&(be=Qr.parse(be,oe))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(Z,oe){var ae=oe.scheme||Z.scheme||"urn",be=Z.nid,Ee=ae+":"+(oe.nid||be),We=q[Ee];We&&(Z=We.serialize(Z,oe));var Nt=Z,Pr=Z.nss;return Nt.path=(be||oe.nid)+":"+Pr,Nt}},iV=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,n5={scheme:"urn:uuid",parse:function(Z,oe){var ae=Z;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(iV))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Z,oe){var ae=Z;return ae.nss=(Z.uuid||"").toLowerCase(),ae}};q[te.scheme]=te,q[ce.scheme]=ce,q[ke.scheme]=ke,q[Vt.scheme]=Vt,q[t5.scheme]=t5,q[r5.scheme]=r5,q[n5.scheme]=n5,t.SCHEMES=q,t.pctEncChar=ee,t.pctDecChars=se,t.parse=de,t.removeDotSegments=_e,t.serialize=at,t.resolveComponents=It,t.resolve=$t,t.normalize=Ht,t.equal=T,t.escapeComponent=M,t.unescapeComponent=U,Object.defineProperty(t,"__esModule",{value:!0})})}),Bde=er((r,e)=>{"use strict";e.exports=function t(n){if(typeof n=="number"&&isNaN(n))throw new Error("NaN is not allowed");if(typeof n=="number"&&!isFinite(n))throw new Error("Infinity is not allowed");return n===null||typeof n!="object"?JSON.stringify(n):n.toJSON instanceof Function?t(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,o)=>`${i}${o===0?"":","}${t(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return i;let o=i.length===0?"":",";return`${i}${o}${t(a)}:${t(n[a])}`},"")}}`}}),u7=er((r,e)=>{var t=1e3,n=t*60,i=n*60,a=i*24,o=a*7,s=a*365.25;e.exports=function(f,p){p=p||{};var h=typeof f;if(h==="string"&&f.length>0)return c(f);if(h==="number"&&isFinite(f))return p.long?d(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(p){var h=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return h*s;case"weeks":case"week":case"w":return h*o;case"days":case"day":case"d":return h*a;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function l(f){var p=Math.abs(f);return p>=a?Math.round(f/a)+"d":p>=i?Math.round(f/i)+"h":p>=n?Math.round(f/n)+"m":p>=t?Math.round(f/t)+"s":f+"ms"}function d(f){var p=Math.abs(f);return p>=a?u(f,p,a,"day"):p>=i?u(f,p,i,"hour"):p>=n?u(f,p,n,"minute"):p>=t?u(f,p,t,"second"):f+" ms"}function u(f,p,h,m){var y=p>=h*1.5;return Math.round(f/h)+" "+m+(y?"s":"")}}),tE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(tE||{}),Di={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},ts=class f7{constructor({method:e,id:t,path:n,query:i,fragment:a,params:o}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let t=f7.DID_URI_PATTERN.exec(e);if(!t||!t.groups)return null;let{method:n,id:i,path:a,query:o,fragment:s}=t.groups,c={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(c.path=a),o&&(c.query=o.slice(1)),s&&(c.fragment=s.slice(1)),o){let l={},d=o.slice(1).split("&");for(let u of d){let[f,p]=u.split("=");l[f]=p}c.params=l}return c}};ts.METHOD_PATTERN="([a-z0-9]+)",ts.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",ts.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${ts.PCT_ENCODED_PATTERN})`,ts.METHOD_ID_PATTERN=`((?:${ts.ID_CHAR_PATTERN}*:)*(${ts.ID_CHAR_PATTERN}+))`,ts.PATH_PATTERN="(/[^#?]*)?",ts.QUERY_PATTERN="([?][^#]*)?",ts.FRAGMENT_PATTERN="(#.*)?",ts.DID_URI_PATTERN=new RegExp("^did:(?<method>"+ts.METHOD_PATTERN+"):(?<id>"+ts.METHOD_ID_PATTERN+")(?<path>"+ts.PATH_PATTERN+")(?<query>"+ts.QUERY_PATTERN+")(?<fragment>"+ts.FRAGMENT_PATTERN+")$");Jn=ts,nt=class p7 extends Error{constructor(e,t){super(`${e}: ${t}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,p7)}},Ode=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidPreviousDidProof="invalidPreviousDidProof",r.InvalidPublicKey="invalidPublicKey",r.InvalidPublicKeyLength="invalidPublicKeyLength",r.InvalidPublicKeyType="invalidPublicKeyType",r.InvalidSignature="invalidSignature",r.NotFound="notFound",r.RepresentationNotSupported="representationNotSupported",r.UnsupportedPublicKeyType="unsupportedPublicKeyType",r))(Ode||{}),Ka=class h7 extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,h7)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(wo||(wo={}));jde=hh(hde(),1);Kde=Mde,Nde=Kde,Ude=Nde,KNe=new Uint8Array(0),Lde=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},SC=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},qde=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},zde=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return m7(this,r)}},Fde=class{constructor(r){this.decoders=r}or(r){return m7(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},m7=(r,e)=>new Fde({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Gde=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new qde(r,e,t),this.decoder=new zde(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},y7=({name:r,prefix:e,encode:t,decode:n})=>new Gde(r,e,t,n),g7=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=Ude(t,e);return y7({prefix:r,name:e,encode:n,decode:a=>SC(i(a))})},Hde=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let o=new Uint8Array(a*t/8|0),s=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,s+=t,s>=8&&(s-=8,o[l++]=255&c>>s)}if(s>=t||255&c<<8-s)throw new SyntaxError("Unexpected end of data");return o},Vde=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",o=0,s=0;for(let c=0;c<r.length;++c)for(s=s<<8|r[c],o+=8;o>t;)o-=t,a+=e[i&s>>o];if(o&&(a+=e[i&s<<t-o]),n)for(;a.length*t&7;)a+="=";return a},Qo=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>y7({prefix:e,name:r,encode(i){return Vde(i,n,t)},decode(i){return Hde(i,n,t,r)}}),x2=Qo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),NNe=Qo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),UNe=Qo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LNe=Qo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qNe=Qo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zNe=Qo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),FNe=Qo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GNe=Qo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),U9=Qo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ja=g7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HNe=g7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),VNe=Qo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),WNe=Qo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$l=Qo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JNe=Qo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});P0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},L9=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(o){return new Promise(function(s,c){o=r[a](o),i(s,c,o.done,o.value)})}}function i(a,o,s,c){Promise.resolve(c).then(function(l){a({value:l,done:s})},o)}},h2=new TextEncoder,eh=new TextDecoder,st=class yo{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new yo(e,"ArrayBuffer")}static asyncIterable(e){if(!Jde(e))throw new TypeError("Input must be of type AsyncIterable.");return new yo(e,"AsyncIterable")}static base32Z(e){return new yo(e,"Base32Z")}static base58Btc(e){return new yo(e,"Base58Btc")}static base64Url(e){return new yo(e,"Base64Url")}static bufferSource(e){return new yo(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new yo(e,"Hex")}static multibase(e){return new yo(e,"Multibase")}static object(e){return new yo(e,"Object")}static string(e){return new yo(e,"String")}static uint8Array(e){return new yo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return ja.baseDecode(this.data).buffer;case"Base64Url":return $l.baseDecode(this.data).buffer;case"BufferSource":{if(QR(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Wde(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return U9.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return ja.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return ja.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return $l.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return $l.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=h2.encode(e);return $l.baseEncode(t)}case"String":{let e=h2.encode(this.data);return $l.baseEncode(e)}case"Uint8Array":return $l.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return P0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=L9(this.data),s;s=yield o.next(),e=s.done,!e;a=!0){i=s.value,a=!1;let l=i;c.push(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let t=this.toUint8Array();return yo.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return yo.uint8Array(t).toHex()}case"Uint8Array":{let t="";for(let n=0;n<this.data.length;n++)t+=e[this.data[n]];return t}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=$l.baseDecode(this.data),t=eh.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=eh.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return eh.decode(this.data);case"Base64Url":{let e=$l.baseDecode(this.data);return eh.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return eh.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return P0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=L9(this.data),s;s=yield o.next(),e=s.done,!e;a=!0){i=s.value,a=!1;let l=i;typeof l=="string"?c+=l:c+=eh.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return c+=eh.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return U9.baseDecode(this.data);case"Base58Btc":return ja.baseDecode(this.data);case"Base64Url":return $l.baseDecode(this.data);case"BufferSource":{let e=QR(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let t=0;t<this.data.length;t+=2){let n=parseInt(this.data.substring(t,t+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[t/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return h2.encode(e)}case"String":return h2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return P0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};(function(r){r.Debug="debug",r.Silent="silent"})(z0||(z0={}));Zde=class{constructor(){this.logLevel=z0.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==z0.Silent&&console.info(r)}error(r){this.logLevel!==z0.Silent&&console.error(r)}},Yde=new Zde;typeof window<"u"&&(window.enboxLogger=Yde);T0={};PC(T0,{decode:()=>z2,encodeTo:()=>G0,encodingLength:()=>H0});Xde=w7,q9=128,Qde=127,ele=~Qde,tle=Math.pow(2,31);rle=eC,nle=128,z9=127;ile=Math.pow(2,7),sle=Math.pow(2,14),ole=Math.pow(2,21),ale=Math.pow(2,28),cle=Math.pow(2,35),dle=Math.pow(2,42),lle=Math.pow(2,49),ule=Math.pow(2,56),fle=Math.pow(2,63),ple=function(r){return r<ile?1:r<sle?2:r<ole?3:r<ale?4:r<cle?5:r<dle?6:r<lle?7:r<ule?8:r<fle?9:10},hle={encode:Xde,decode:rle,encodingLength:ple},mle=hle,q2=mle,z2=(r,e=0)=>[q2.decode(r,e),q2.decode.bytes],G0=(r,e,t=0)=>(q2.encode(r,e,t),e),H0=r=>q2.encodingLength(r),yle=(r,e)=>{let t=e.byteLength,n=H0(r),i=n+H0(t),a=new Uint8Array(i+t);return G0(r,a,0),G0(t,a,n),a.set(e,i),new kC(r,t,e,a)},gle=r=>{let e=SC(r),[t,n]=z2(e),[i,a]=z2(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==i)throw new Error("Incorrect length");return new kC(t,i,o,e)},wle=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Lde(r.bytes,t.bytes)}},kC=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},F9=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return ble(t,tC(r),e||ja.encoder);default:return Ple(t,tC(r),e||x2.encoder)}},G9=new WeakMap,tC=r=>{let e=G9.get(r);if(e==null){let t=new Map;return G9.set(r,t),t}return e},ZNe=class Ps{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:e,multihash:t}=this;if(e!==x0)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ps.createV0(t)}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:e,digest:t}=this.multihash,n=yle(e,t);return Ps.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return Ps.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&wle(e.multihash,n.multihash)}toString(e){return F9(this,e)}toJSON(){return{"/":F9(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof Ps)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:a,bytes:o}=t;return new Ps(n,i,a,o||H9(n,i,a.bytes))}else if(t[Ele]===!0){let{version:n,multihash:i,code:a}=t,o=gle(i);return Ps.create(n,a,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==x0)throw new Error(`Version 0 CID must use dag-pb (code: ${x0}) block encoding`);return new Ps(e,t,n,n.bytes)}case 1:{let i=H9(e,t,n.bytes);return new Ps(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return Ps.create(0,x0,e)}static createV1(e,t){return Ps.create(1,e,t)}static decode(e){let[t,n]=Ps.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=Ps.inspectBytes(e),n=t.size-t.multihashSize,i=SC(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let a=i.subarray(t.multihashSize-t.digestSize),o=new kC(t.multihashCode,t.digestSize,a,i);return[t.version===0?Ps.createV0(o):Ps.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=z2(e.subarray(t));return t+=f,u},i=n(),a=x0;if(i===18?(i=0,t=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,s=n(),c=n(),l=t+c,d=l-o;return{version:i,codec:a,multihashCode:s,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,i]=vle(e,t),a=Ps.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tC(a).set(n,e),a}},vle=(r,e)=>{switch(r[0]){case"Q":{let t=e||ja;return[ja.prefix,t.decode(`${ja.prefix}${r}`)]}case ja.prefix:{let t=e||ja;return[ja.prefix,t.decode(r)]}case x2.prefix:{let t=e||x2;return[x2.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},ble=(r,e,t)=>{let{prefix:n}=t;if(n!==ja.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let a=t.encode(r).slice(1);return e.set(n,a),a}else return i},Ple=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let a=t.encode(r);return e.set(n,a),a}else return i},x0=112,xle=18,H9=(r,e,t)=>{let n=H0(r),i=n+H0(e),a=new Uint8Array(i+t.byteLength);return G0(r,a,0),G0(e,a,n),a.set(t,i),a},Ele=Symbol.for("@ipld/js-cid/CID"),Ua=class yf{static addPrefix(e){var t;let{code:n,data:i,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=yf.codeToName.has(n)?n:yf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let o=T0.encodingLength(n),s=new Uint8Array(o+i.byteLength);return s.set(i,o),T0.encodeTo(n,s),s}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=T0.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=yf.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=yf.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){yf.codeToName.set(e.code,e.name),yf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=T0.decode(t),a=yf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:a}}};Ua.codeToName=new Map;Ua.nameToCode=new Map;Ua.registerCodec({code:237,name:"ed25519-pub"});Ua.registerCodec({code:4864,name:"ed25519-priv"});Ua.registerCodec({code:236,name:"x25519-pub"});Ua.registerCodec({code:4866,name:"x25519-priv"});Ua.registerCodec({code:231,name:"secp256k1-pub"});Ua.registerCodec({code:4865,name:"secp256k1-priv"});YNe=hh(l7(),1),of=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Sle=class{constructor(){this.store=new Map}clear(){return of(this,void 0,void 0,function*(){this.store.clear()})}open(){return of(this,void 0,void 0,function*(){})}close(){return of(this,void 0,void 0,function*(){})}delete(r){return of(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return of(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return of(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return of(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return of(this,void 0,void 0,function*(){this.store.set(r,e)})}},rE=class{},b7={};PC(b7,{bitGet:()=>Rle,bitLen:()=>Dle,bitMask:()=>AC,bitSet:()=>Cle,bytesToHex:()=>uh,bytesToNumberBE:()=>ch,bytesToNumberLE:()=>Pf,concatBytes:()=>fh,createHmacDrbg:()=>E7,ensureBytes:()=>Wn,equalBytes:()=>Tle,hexToBytes:()=>Hy,hexToNumber:()=>_C,isBytes:()=>$d,numberToBytesBE:()=>Bd,numberToBytesLE:()=>Vy,numberToHexUnpadded:()=>x7,numberToVarBytesBE:()=>Ale,utf8ToBytes:()=>Ile,validateObject:()=>mh});P7=BigInt(0),nE=BigInt(1),kle=BigInt(2);_le=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Bl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};Cle=(r,e,t)=>r|(t?nE:P7)<<BigInt(e),AC=r=>(kle<<BigInt(r-1))-nE,zR=r=>new Uint8Array(r),W9=r=>Uint8Array.from(r);$le={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||$d(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};FR=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;GR=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),kd=(r,e)=>r<<32-e|r>>>e,Mle=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Mle)throw new Error("Non little-endian hardware is not supported");T7=class{clone(){return this._cloneInto()}},XNe={}.toString;D7=class extends T7{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=GR(this.buffer)}update(r){F2(this);let{view:e,buffer:t,blockLen:n}=this;r=TC(r);let i=r.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let s=GR(r);for(;n<=i-a;a+=n)this.process(s,a);continue}t.set(r.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){F2(this),jle(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;Kle(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=GR(r),s=this.outputLen;if(s%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},Nle=(r,e,t)=>r&e^~r&t,Ule=(r,e,t)=>r&e^r&t^e&t,Lle=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),af=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cf=new Uint32Array(64),qle=class extends D7{constructor(){super(64,32,8,!1),this.A=af[0]|0,this.B=af[1]|0,this.C=af[2]|0,this.D=af[3]|0,this.E=af[4]|0,this.F=af[5]|0,this.G=af[6]|0,this.H=af[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:o,H:s}=this;return[r,e,t,n,i,a,o,s]}set(r,e,t,n,i,a,o,s){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(r,e){for(let d=0;d<16;d++,e+=4)cf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=cf[d-15],f=cf[d-2],p=kd(u,7)^kd(u,18)^u>>>3,h=kd(f,17)^kd(f,19)^f>>>10;cf[d]=h+cf[d-7]+p+cf[d-16]|0}let{A:t,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let d=0;d<64;d++){let u=kd(o,6)^kd(o,11)^kd(o,25),f=l+u+Nle(o,s,c)+Lle[d]+cf[d]|0,p=(kd(t,2)^kd(t,13)^kd(t,22))+Ule(t,n,i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,o,s,c,l)}roundClean(){cf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},R7=I7(()=>new qle),yi=BigInt(0),gn=BigInt(1),nh=BigInt(2),zle=BigInt(3),rC=BigInt(4),Z9=BigInt(5),Y9=BigInt(8),QNe=BigInt(9),Fle=BigInt(16);Vle=(r,e)=>(Xr(r,e)&gn)===gn,Wle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];eue=BigInt(0),HR=BigInt(1);({bytesToNumberBE:rue,hexToBytes:nue}=b7),oh={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=oh;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:rue(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=oh,t=typeof r=="string"?nue(r):r;if(!$d(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=oh._parseInt(t.subarray(2)),{d:o,l:s}=oh._parseInt(a);if(s.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),i=e(t(r.r)),a=n.length/2,o=i.length/2,s=t(a),c=t(o);return`30${t(o+a+4)}02${c}${i}02${s}${n}`}},Ul=BigInt(0),Oa=BigInt(1),eUe=BigInt(2),X9=BigInt(3),tUe=BigInt(4);M7=class extends T7{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,Ole(r);let t=TC(e);if(this.iHash=r.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(t.length>n?r.create().update(t).digest():t);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=r.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(r){return F2(this),this.iHash.update(r),this}digestInto(r){F2(this),S7(r,this.outputLen),this.finished=!0,this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||(r=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:t,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=a,r.outputLen=o,r.oHash=e._cloneInto(r.oHash),r.iHash=t._cloneInto(r.iHash),r}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},K7=(r,e,t)=>new M7(r,e).update(t).digest();K7.create=(r,e)=>new M7(r,e);U7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Q9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cue=BigInt(1),iC=BigInt(2),eq=(r,e)=>(r+e/iC)/e;sC=DC(U7,void 0,void 0,{sqrt:due}),Jo=N7({a:BigInt(0),b:BigInt(7),Fp:sC,n:Q9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Q9,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cue*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=t,o=BigInt("0x100000000000000000000000000000000"),s=eq(a*r,e),c=eq(-n*r,e),l=Xr(r-s*t-c*i,e),d=Xr(-s*n-c*a,e),u=l>o,f=d>o;if(u&&(l=e-l),f&&(d=e-d),l>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},R7),rUe=BigInt(0),nUe=Jo.ProjectivePoint;E2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,VR=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),_d=(r,e)=>r<<32-e|r>>>e,iUe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;pue=class{clone(){return this._cloneInto()}},sUe={}.toString;gue=(r,e,t)=>r&e^~r&t,wue=(r,e,t)=>r&e^r&t^e&t,vue=class extends pue{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=VR(this.buffer)}update(r){tq(this);let{view:e,buffer:t,blockLen:n}=this;r=q7(r);let i=r.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let s=VR(r);for(;n<=i-a;a+=n)this.process(s,a);continue}t.set(r.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){tq(this),uue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;yue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=VR(r),s=this.outputLen;if(s%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},bue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),df=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lf=new Uint32Array(64),Pue=class extends vue{constructor(){super(64,32,8,!1),this.A=df[0]|0,this.B=df[1]|0,this.C=df[2]|0,this.D=df[3]|0,this.E=df[4]|0,this.F=df[5]|0,this.G=df[6]|0,this.H=df[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:o,H:s}=this;return[r,e,t,n,i,a,o,s]}set(r,e,t,n,i,a,o,s){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(r,e){for(let d=0;d<16;d++,e+=4)lf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=lf[d-15],f=lf[d-2],p=_d(u,7)^_d(u,18)^u>>>3,h=_d(f,17)^_d(f,19)^f>>>10;lf[d]=h+lf[d-7]+p+lf[d-16]|0}let{A:t,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let d=0;d<64;d++){let u=_d(o,6)^_d(o,11)^_d(o,25),f=l+u+gue(o,s,c)+bue[d]+lf[d]|0,p=(_d(t,2)^_d(t,13)^_d(t,22))+wue(t,n,i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,o,s,c,l)}roundClean(){lf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},V0=hue(()=>new Pue);Eue=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},z7=class{static digest(r){return Eue(this,arguments,void 0,function*({data:e}){return V0(e)})}},Sue=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},rq="urn:jwk:";Qi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},_ue=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},ns=class Td{static adjustSignatureToLowS(e){return Qi(this,arguments,void 0,function*({signature:t}){let n=Jo.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Qi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Td.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Td.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static compressPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){return Jo.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Qi(this,arguments,void 0,function*({key:t}){let n=yield Td.privateKeyToBytes({privateKey:t}),i=yield Td.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:st.uint8Array(i.x).toBase64Url(),y:st.uint8Array(i.y).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertDerToCompactSignature(e){return Qi(this,arguments,void 0,function*({derSignature:t}){return Jo.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){return Jo.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Qi(this,void 0,void 0,function*(){let e=Jo.utils.randomPrivateKey(),t=yield Td.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return Qi(this,arguments,void 0,function*({key:t}){var n;if(!(dh(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,a=_ue(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return Qi(this,arguments,void 0,function*({privateKey:t}){if(!dh(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Qi(this,arguments,void 0,function*({publicKey:t}){if(!(CC(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=st.base64Url(t.x).toUint8Array(),a=st.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Qi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Td.privateKeyToBytes({privateKey:t}),a=yield Td.publicKeyToBytes({publicKey:n});return Jo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Qi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Td.privateKeyToBytes({privateKey:n}),a=V0(t);return Jo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Qi(this,arguments,void 0,function*({privateKeyBytes:t}){return Jo.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Qi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Jo.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Qi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Td.publicKeyToBytes({publicKey:t}),o=V0(i);return Jo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Qi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Jo.getPublicKey(t));let n=Jo.ProjectivePoint.fromHex(t),i=Bd(n.x,32),a=Bd(n.y,32);return{x:i,y:a}})}},F7=DC(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Aue=F7.create(BigInt("-3")),Tue=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Iue=N7({a:Aue,b:Tue,Fp:F7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},R7),Da=Iue,es=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Due=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},xs=class Id{static adjustSignatureToLowS(e){return es(this,arguments,void 0,function*({signature:t}){let n=Da.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return es(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Id.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Id.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:st.uint8Array(n.x).toBase64Url(),y:st.uint8Array(n.y).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static compressPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){return Da.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return es(this,arguments,void 0,function*({key:t}){let n=yield Id.privateKeyToBytes({privateKey:t}),i=yield Id.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:st.uint8Array(i.x).toBase64Url(),y:st.uint8Array(i.y).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertDerToCompactSignature(e){return es(this,arguments,void 0,function*({derSignature:t}){return Da.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){return Da.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return es(this,void 0,void 0,function*(){let e=Da.utils.randomPrivateKey(),t=yield Id.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return es(this,arguments,void 0,function*({key:t}){var n;if(!(dh(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,a=Due(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return es(this,arguments,void 0,function*({privateKey:t}){if(!dh(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return es(this,arguments,void 0,function*({publicKey:t}){if(!(CC(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=st.base64Url(t.x).toUint8Array(),a=st.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return es(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Id.privateKeyToBytes({privateKey:t}),a=yield Id.publicKeyToBytes({publicKey:n});return Da.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return es(this,arguments,void 0,function*({data:t,key:n}){let i=yield Id.privateKeyToBytes({privateKey:n}),a=V0(t);return Da.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return es(this,arguments,void 0,function*({privateKeyBytes:t}){return Da.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:t}){try{Da.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return es(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Id.publicKeyToBytes({publicKey:t}),o=V0(i);return Da.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return es(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Da.getPublicKey(t));let n=Da.ProjectivePoint.fromHex(t),i=Bd(n.x,32),a=Bd(n.y,32);return{x:i,y:a}})}},Ol=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nq=class extends rE{bytesToPrivateKey(r){return Ol(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ns.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield xs.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Ol(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ns.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield xs.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Ol(this,arguments,void 0,function*({key:e}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ns.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield xs.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Ol(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield ns.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield xs.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return Ol(this,arguments,void 0,function*({key:e}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ns.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield xs.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Ol(this,arguments,void 0,function*({key:e,data:t}){if(!dh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield ns.sign({key:e,data:t});case"P-256":return yield xs.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Ol(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!CC(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield ns.verify({key:e,signature:t,data:n});case"P-256":return yield xs.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Ol(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield ns.privateKeyToBytes({privateKey:e});case"P-256":return yield xs.privateKeyToBytes({privateKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Ol(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield ns.publicKeyToBytes({publicKey:e});case"P-256":return yield xs.publicKeyToBytes({publicKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m2=BigInt(4294967295),oC=BigInt(32);Cue=(r,e)=>BigInt(r>>>0)<<oC|BigInt(e>>>0),$ue=(r,e,t)=>r>>>t,Bue=(r,e,t)=>r<<32-t|e>>>t,Oue=(r,e,t)=>r>>>t|e<<32-t,jue=(r,e,t)=>r<<32-t|e>>>t,Mue=(r,e,t)=>r<<64-t|e>>>t-32,Kue=(r,e,t)=>r>>>t-32|e<<64-t,Nue=(r,e)=>e,Uue=(r,e)=>r,Lue=(r,e,t)=>r<<t|e>>>32-t,que=(r,e,t)=>e<<t|r>>>32-t,zue=(r,e,t)=>e<<t-32|r>>>64-t,Fue=(r,e,t)=>r<<t-32|e>>>64-t;Hue=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Vue=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Wue=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Jue=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Zue=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Yue=(r,e,t,n,i,a)=>e+t+n+i+a+(r/2**32|0)|0,Xue={fromBig:G7,split:Rue,toBig:Cue,shrSH:$ue,shrSL:Bue,rotrSH:Oue,rotrSL:jue,rotrBH:Mue,rotrBL:Kue,rotr32H:Nue,rotr32L:Uue,rotlSH:Lue,rotlSL:que,rotlBH:zue,rotlBL:Fue,add:Gue,add3L:Hue,add3H:Vue,add4L:Wue,add4H:Jue,add5H:Yue,add5L:Zue},Lt=Xue,[Que,efe]=Lt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),uf=new Uint32Array(80),ff=new Uint32Array(80),tfe=class extends D7{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:r,Al:e,Bh:t,Bl:n,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:d,Fl:u,Gh:f,Gl:p,Hh:h,Hl:m}=this;return[r,e,t,n,i,a,o,s,c,l,d,u,f,p,h,m]}set(r,e,t,n,i,a,o,s,c,l,d,u,f,p,h,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=p|0,this.Hh=h|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)uf[w]=r.getUint32(e),ff[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let x=uf[w-15]|0,_=ff[w-15]|0,A=Lt.rotrSH(x,_,1)^Lt.rotrSH(x,_,8)^Lt.shrSH(x,_,7),D=Lt.rotrSL(x,_,1)^Lt.rotrSL(x,_,8)^Lt.shrSL(x,_,7),N=uf[w-2]|0,$=ff[w-2]|0,z=Lt.rotrSH(N,$,19)^Lt.rotrBH(N,$,61)^Lt.shrSH(N,$,6),L=Lt.rotrSL(N,$,19)^Lt.rotrBL(N,$,61)^Lt.shrSL(N,$,6),j=Lt.add4L(D,L,ff[w-7],ff[w-16]),H=Lt.add4H(j,A,z,uf[w-7],uf[w-16]);uf[w]=H|0,ff[w]=j|0}let{Ah:t,Al:n,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:d,El:u,Fh:f,Fl:p,Gh:h,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let x=Lt.rotrSH(d,u,14)^Lt.rotrSH(d,u,18)^Lt.rotrBH(d,u,41),_=Lt.rotrSL(d,u,14)^Lt.rotrSL(d,u,18)^Lt.rotrBL(d,u,41),A=d&f^~d&h,D=u&p^~u&m,N=Lt.add5L(v,_,D,efe[w],ff[w]),$=Lt.add5H(N,y,x,A,Que[w],uf[w]),z=N|0,L=Lt.rotrSH(t,n,28)^Lt.rotrBH(t,n,34)^Lt.rotrBH(t,n,39),j=Lt.rotrSL(t,n,28)^Lt.rotrBL(t,n,34)^Lt.rotrBL(t,n,39),H=t&i^t&o^i&o,Y=n&a^n&s^a&s;y=h|0,v=m|0,h=f|0,m=p|0,f=d|0,p=u|0,{h:d,l:u}=Lt.add(c|0,l|0,$|0,z|0),c=o|0,l=s|0,o=i|0,s=a|0,i=t|0,a=n|0;let R=Lt.add3L(z,j,Y);t=Lt.add3H(R,$,L,H),n=R|0}({h:t,l:n}=Lt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:a}=Lt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Lt.add(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Lt.add(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:u}=Lt.add(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:p}=Lt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h,l:m}=Lt.add(this.Gh|0,this.Gl|0,h|0,m|0),{h:y,l:v}=Lt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,a,o,s,c,l,d,u,f,p,h,m,y,v)}roundClean(){uf.fill(0),ff.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},H7=I7(()=>new tfe),_c=BigInt(0),Vo=BigInt(1),y2=BigInt(2),rfe=BigInt(8),nfe={zip215:!0};E0=BigInt(0),WR=BigInt(1);W0=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),iq=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),oUe=BigInt(0),afe=BigInt(1),aC=BigInt(2),cfe=BigInt(5),sq=BigInt(10),dfe=BigInt(20),lfe=BigInt(40),oq=BigInt(80);Na=DC(W0,void 0,!0),J0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:H7,randomBytes:IC,adjustScalarBytes:W7,uvRatio:ufe},th=BC(J0);aUe=BC({...J0,domain:J7}),cUe=BC({...J0,domain:J7,prehash:H7}),I0=ofe({P:W0,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=W0,{pow_p_5_8:t,b2:n}=V7(r);return Xr(Sn(t,BigInt(3),e)*n,e)},adjustScalarBytes:W7,randomBytes:IC});hfe=(Na.ORDER+BigInt(3))/BigInt(8),dUe=Na.pow(aC,hfe),lUe=Na.sqrt(Na.neg(Na.ONE)),uUe=(Na.ORDER-BigInt(5))/BigInt(8),fUe=BigInt(486662),pUe=Xle(Na,Na.neg(BigInt(486664))),hUe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),mUe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),yUe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),gUe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),wUe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ra=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},mfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},is=class gf{static bytesToPrivateKey(e){return Ra(this,arguments,void 0,function*({privateKeyBytes:t}){let n=th.getPublicKey(t),i={crv:"Ed25519",d:st.uint8Array(t).toBase64Url(),kty:"OKP",x:st.uint8Array(n).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return Ra(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:st.uint8Array(t).toBase64Url()};return n.kid=yield _r({jwk:n}),n})}static computePublicKey(e){return Ra(this,arguments,void 0,function*({key:t}){let n=yield gf.privateKeyToBytes({privateKey:t}),i=th.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Ra(this,arguments,void 0,function*({privateKey:t}){let n=yield gf.privateKeyToBytes({privateKey:t}),i=pfe(n),a=I0.getPublicKey(i),o={kty:"OKP",crv:"X25519",d:st.uint8Array(i).toBase64Url(),x:st.uint8Array(a).toBase64Url()};return o.kid=yield _r({jwk:o}),o})}static convertPublicKeyToX25519(e){return Ra(this,arguments,void 0,function*({publicKey:t}){let n=yield gf.publicKeyToBytes({publicKey:t});if(!(yield gf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=ffe(n),a={kty:"OKP",crv:"X25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static generateKey(){return Ra(this,void 0,void 0,function*(){let e=th.utils.randomPrivateKey(),t=yield gf.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return Ra(this,arguments,void 0,function*({key:t}){var n;if(!(zl(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,a=mfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return Ra(this,arguments,void 0,function*({privateKey:t}){if(!zl(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ra(this,arguments,void 0,function*({publicKey:t}){if(!$C(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return st.base64Url(t.x).toUint8Array()})}static sign(e){return Ra(this,arguments,void 0,function*({key:t,data:n}){let i=yield gf.privateKeyToBytes({privateKey:t});return th.sign(n,i)})}static validatePublicKey(e){return Ra(this,arguments,void 0,function*({publicKeyBytes:t}){try{th.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ra(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield gf.publicKeyToBytes({publicKey:t});return th.verify(n,i,a)})}},jl=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},yfe=class extends rE{bytesToPrivateKey(r){return jl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield is.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return jl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield is.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return jl(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield is.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return jl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield is.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return jl(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield is.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return jl(this,arguments,void 0,function*({key:e,data:t}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield is.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return jl(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!$C(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield is.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return jl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield is.privateKeyToBytes({privateKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return jl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield is.publicKeyToBytes({publicKey:e});default:throw new Ka(wo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},gfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wfe=class extends rE{digest(r){return gfe(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield z7.digest({data:t})}})}},pf=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},vfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},Oy=class D0{static bytesToPrivateKey(e){return pf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=I0.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:st.uint8Array(t).toBase64Url(),x:st.uint8Array(n).toBase64Url()};return i.kid=yield _r({jwk:i}),i})}static bytesToPublicKey(e){return pf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:st.uint8Array(t).toBase64Url()};return n.kid=yield _r({jwk:n}),n})}static computePublicKey(e){return pf(this,arguments,void 0,function*({key:t}){let n=yield D0.privateKeyToBytes({privateKey:t}),i=I0.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:st.uint8Array(i).toBase64Url()};return a.kid=yield _r({jwk:a}),a})}static generateKey(){return pf(this,void 0,void 0,function*(){let e=I0.utils.randomPrivateKey(),t=yield D0.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield _r({jwk:t}),t})}static getPublicKey(e){return pf(this,arguments,void 0,function*({key:t}){var n;if(!(zl(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,a=vfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield _r({jwk:a})),a})}static privateKeyToBytes(e){return pf(this,arguments,void 0,function*({privateKey:t}){if(!zl(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return st.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return pf(this,arguments,void 0,function*({publicKey:t}){if(!$C(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return st.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return pf(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield D0.privateKeyToBytes({privateKey:t}),a=yield D0.publicKeyToBytes({publicKey:n});return I0.getSharedSecret(i,a)})}},S0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},bfe=class extends rE{bytesToPrivateKey(r){return S0(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Oy.bytesToPrivateKey({privateKeyBytes:t});default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return S0(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Oy.computePublicKey({key:e});default:throw new Ka(wo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return S0(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Oy.generateKey();default:throw new Ka(wo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return S0(this,arguments,void 0,function*({key:e}){if(!zl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Oy.getPublicKey({key:e});default:throw new Ka(wo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return S0(this,arguments,void 0,function*({privateKey:e}){return Oy.privateKeyToBytes({privateKey:e})})}},Ml=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},JR={Ed25519:{implementation:yfe,names:["Ed25519"]},secp256k1:{implementation:nq,names:["ES256K","secp256k1"]},secp256r1:{implementation:nq,names:["ES256","secp256r1"]},"SHA-256":{implementation:wfe,names:["SHA-256"]},X25519:{implementation:bfe,names:["X25519"]}},Ic=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new Sle}digest(r){return Ml(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e}){let t=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(t?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${rq}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return Ml(this,arguments,void 0,function*({key:e}){let t=yield _r({jwk:e});return`${rq}${t}`})}getPublicKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){let t=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}importKey(r){return Ml(this,arguments,void 0,function*({key:e}){var t;if(!kue(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(t=n.kid)!==null&&t!==void 0||(n.kid=yield _r({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return Ml(this,arguments,void 0,function*({keyUri:e,data:t}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:t,key:n})})}verify(r){return Ml(this,arguments,void 0,function*({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})})}getAlgorithm({algorithm:r}){var e;let t=(e=JR[r])===null||e===void 0?void 0:e.implementation;if(!t)throw new Error(`Algorithm not supported: ${r}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({key:r}){let e=r.alg,t=r.crv;for(let n in JR){let i=JR[n];if(e&&i.names.includes(e)||t&&i.names.includes(t))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${t}`)}getPrivateKey(r){return Ml(this,arguments,void 0,function*({keyUri:e}){let t=yield this._keyStore.get(e);if(!t)throw new Error(`Key not found: ${e}`);return t})}},Pfe=class cC{static getJoseSignatureAlgorithmFromPublicKey(e){let t={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(t).includes(e.alg))return e.alg;if(e.crv&&Object.keys(t).includes(e.crv))return t[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(t).join(", ")}. Supported 'crv' values: ${Object.keys(t).join(", ")}.`)}static randomBytes(e){return mue(e)}static randomUuid(){return E2.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let t=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let a=cC.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%i}while(n>t)}else{let i=Math.pow(10,10);do{let a=cC.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%i}while(n>t)}return n.toString().padStart(e,"0")}},xfe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];Se=class{constructor(r,e,t){this.major=r,this.majorEncoded=r<<5,this.name=e,this.terminal=t}toString(){return`Type[${this.major}].${this.name}`}compare(r){return this.major<r.major?-1:this.major>r.major?1:0}static equals(r,e){return r===e||r.major===e.major&&r.name===e.name}};Se.uint=new Se(0,"uint",!0);Se.negint=new Se(1,"negint",!0);Se.bytes=new Se(2,"bytes",!0);Se.string=new Se(3,"string",!0);Se.array=new Se(4,"array",!1);Se.map=new Se(5,"map",!1);Se.tag=new Se(6,"tag",!1);Se.float=new Se(7,"float",!0);Se.false=new Se(7,"false",!0);Se.true=new Se(7,"true",!0);Se.null=new Se(7,"null",!0);Se.undefined=new Se(7,"undefined",!0);Se.break=new Se(7,"break",!0);tt=class{constructor(r,e,t){this.type=r,this.value=e,this.encodedLength=t,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},tb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",kfe=new TextEncoder;_fe=24,Afe=200,Tfe=tb?r=>r.length>=_fe?globalThis.Buffer.from(r):aq(r):r=>r.length>=Afe?kfe.encode(r):aq(r),Kl=r=>Uint8Array.from(r),Ife=tb?(r,e,t)=>G2(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Dfe=tb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Z7(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Rfe=tb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);Cfe=256,X7=class{constructor(r=Cfe){this.chunkSize=r,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(r){let e=this.chunks[this.chunks.length-1];if(this.cursor+r.length<=this.maxCursor+1){let t=e.length-(this.maxCursor-this.cursor)-1;e.set(r,t)}else{if(e){let t=e.length-(this.maxCursor-this.cursor)-1;t<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,t),this.maxCursor=this.cursor-1)}r.length<64&&r.length<this.chunkSize?(e=Rfe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(r,0)):(this.chunks.push(r),this.maxCursor+=r.length)}this.cursor+=r.length}toBytes(r=!1){let e;if(this.chunks.length===1){let t=this.chunks[0];r&&this.cursor>t.length/2?(e=this.cursor===t.length?t:t.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=Ife(t,0,this.cursor)}else e=Dfe(this.chunks,this.cursor);return r&&this.reset(),e}},$fe=class{constructor(r){this.dest=r,this.cursor=0,this.chunks=[r]}reset(){this.cursor=0}push(r){if(this.cursor+r.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(r,this.cursor),this.cursor+=r.length}toBytes(r=!1){let e=this.dest.subarray(0,this.cursor);return r&&this.reset(),e}},kn="CBOR decode error:",Q7="CBOR encode error:",rb=[];rb[23]=1;rb[24]=2;rb[25]=3;rb[26]=5;rb[27]=9;ss=[24,256,65536,4294967296,BigInt("18446744073709551616")];bh.encodedSize=function(r){return La.encodedSize(r.value)};La.encodedSize=function(r){return r<ss[0]?1:r<ss[1]?2:r<ss[2]?3:r<ss[3]?5:9};bh.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};OC=BigInt(-1),ez=BigInt(1);jC.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*OC-ez:e*-1-1;return t<ss[0]?1:t<ss[1]?2:t<ss[2]?3:t<ss[3]?5:9};jC.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};iE.encodedSize=function(r){let e=H2(r);return La.encodedSize(e.length)+e.length};iE.compareTokens=function(r,e){return Vfe(H2(r),H2(e))};cq=new TextDecoder,Wfe=32;tpe=iE;MC.compareTokens=bh.compareTokens;MC.encodedSize=function(r){return La.encodedSize(r.value)};KC.compareTokens=bh.compareTokens;KC.encodedSize=function(r){return La.encodedSize(r.value)};NC.compareTokens=bh.compareTokens;NC.encodedSize=function(r){return La.encodedSize(r.value)};tz=20,rz=21,nz=22,iz=23;LC.encodedSize=function(r,e){let t=r.value;if(t===!1||t===!0||t===null||t===void 0)return 1;if(!e||e.float64!==!0){oz(t);let n=qC(Ac,1);if(t===n||Number.isNaN(t))return 3;if(az(t),n=zC(Ac,1),t===n)return 5}return 9};sz=new ArrayBuffer(9),$a=new DataView(sz,1),Ac=new Uint8Array(sz,0);LC.compareTokens=bh.compareTokens;je=[];for(let r=0;r<=23;r++)je[r]=yr;je[24]=Bfe;je[25]=Ofe;je[26]=jfe;je[27]=Mfe;je[28]=yr;je[29]=yr;je[30]=yr;je[31]=yr;for(let r=32;r<=55;r++)je[r]=yr;je[56]=Kfe;je[57]=Nfe;je[58]=Ufe;je[59]=Lfe;je[60]=yr;je[61]=yr;je[62]=yr;je[63]=yr;for(let r=64;r<=87;r++)je[r]=qfe;je[88]=zfe;je[89]=Ffe;je[90]=Gfe;je[91]=Hfe;je[92]=yr;je[93]=yr;je[94]=yr;je[95]=sE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)je[r]=Zfe;je[120]=Yfe;je[121]=Xfe;je[122]=Qfe;je[123]=epe;je[124]=yr;je[125]=yr;je[126]=yr;je[127]=sE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)je[r]=rpe;je[152]=npe;je[153]=ipe;je[154]=spe;je[155]=ope;je[156]=yr;je[157]=yr;je[158]=yr;je[159]=ape;for(let r=160;r<=183;r++)je[r]=cpe;je[184]=dpe;je[185]=lpe;je[186]=upe;je[187]=fpe;je[188]=yr;je[189]=yr;je[190]=yr;je[191]=ppe;for(let r=192;r<=215;r++)je[r]=hpe;je[216]=mpe;je[217]=ype;je[218]=gpe;je[219]=wpe;je[220]=yr;je[221]=yr;je[222]=yr;je[223]=yr;for(let r=224;r<=243;r++)je[r]=sE("simple values are not supported");je[244]=yr;je[245]=yr;je[246]=yr;je[247]=vpe;je[248]=sE("simple values are not supported");je[249]=Ppe;je[250]=xpe;je[251]=Epe;je[252]=yr;je[253]=yr;je[254]=yr;je[255]=bpe;Gl=[];for(let r=0;r<24;r++)Gl[r]=new tt(Se.uint,r,1);for(let r=-1;r>=-24;r--)Gl[31-r]=new tt(Se.negint,r,1);Gl[64]=new tt(Se.bytes,new Uint8Array(0),1);Gl[96]=new tt(Se.string,"",1);Gl[128]=new tt(Se.array,0,1);Gl[160]=new tt(Se.map,0,1);Gl[244]=new tt(Se.false,!1,1);Gl[245]=new tt(Se.true,!0,1);Gl[246]=new tt(Se.null,null,1);_pe=Object.freeze({float64:!0,mapSorter:Rpe,quickEncodeToken:kpe});Tpe=Ape(),Ipe=new X7,dq=class dz{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Q7} object contains circular references`);return new dz(t,e)}},hf={null:new tt(Se.null,null),undefined:new tt(Se.undefined,void 0),true:new tt(Se.true,!0),false:new tt(Se.false,!1),emptyArray:new tt(Se.array,0),emptyMap:new tt(Se.map,0)},Ef={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new tt(Se.float,r):r>=0?new tt(Se.uint,r):new tt(Se.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new tt(Se.uint,r):new tt(Se.negint,r)},Uint8Array(r,e,t,n){return new tt(Se.bytes,r)},string(r,e,t,n){return new tt(Se.string,r)},boolean(r,e,t,n){return r?hf.true:hf.false},null(r,e,t,n){return hf.null},undefined(r,e,t,n){return hf.undefined},ArrayBuffer(r,e,t,n){return new tt(Se.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new tt(Se.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[hf.emptyArray,new tt(Se.break)]:hf.emptyArray;n=dq.createCheck(n,r);let i=[],a=0;for(let o of r)i[a++]=S2(o,t,n);return t.addBreakTokens?[new tt(Se.array,r.length),i,new tt(Se.break)]:[new tt(Se.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",a=i?r.keys():Object.keys(r),o=i?r.size:a.length,s;if(o){s=new Array(o),n=dq.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,l=0;for(let d of a){let u=i?r.get(d):r[d];c&&u===void 0||(s[l++]=[S2(d,t,n),S2(u,t,n)])}l<o&&(s.length=l)}return s?.length?(Dpe(s,t),t.addBreakTokens?[new tt(Se.map,s.length),s,new tt(Se.break)]:[new tt(Se.map,s.length),s]):t.addBreakTokens===!0?[hf.emptyMap,new tt(Se.break)]:hf.emptyMap}};Ef.Map=Ef.Object;Ef.Buffer=Ef.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ef[`${r}Array`]=Ef.DataView;vUe=Se.uint.majorEncoded,bUe=Se.negint.majorEncoded,PUe=Se.bytes.majorEncoded,xUe=Se.string.majorEncoded,EUe=Se.array.majorEncoded,SUe=Se.float.majorEncoded|tz,kUe=Se.float.majorEncoded|rz,_Ue=Se.float.majorEncoded|nz,AUe=Se.float.majorEncoded|iz,TUe=BigInt(-1),IUe=BigInt(1);DUe=Symbol.for("DONE"),RUe=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(uq||(uq={}));(function(r){r[r.P256=1]="P256",r[r.P384=2]="P384",r[r.P521=3]="P521",r[r.X25519=4]="X25519",r[r.X448=5]="X448",r[r.Ed25519=6]="Ed25519",r[r.Ed448=7]="Ed448",r[r.Secp256k1=8]="Secp256k1"})(Es||(Es={}));(function(r){r[r.EdDSA=-8]="EdDSA",r[r.ES256=-7]="ES256",r[r.ES384=-35]="ES384",r[r.ES512=-36]="ES512",r[r.ES256K=-47]="ES256K"})(Ma||(Ma={}));(function(r){r[r.Kty=1]="Kty",r[r.Kid=2]="Kid",r[r.Alg=3]="Alg",r[r.KeyOps=4]="KeyOps",r[r.BaseIv=5]="BaseIv"})(fq||(fq={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(pq||(pq={}));CUe={"P-256":Es.P256,"P-384":Es.P384,"P-521":Es.P521,X25519:Es.X25519,Ed25519:Es.Ed25519,Ed448:Es.Ed448,secp256k1:Es.Secp256k1},$Ue={[Es.P256]:"P-256",[Es.P384]:"P-384",[Es.P521]:"P-521",[Es.X25519]:"X25519",[Es.Ed25519]:"Ed25519",[Es.Ed448]:"Ed448",[Es.Secp256k1]:"secp256k1"},BUe={EdDSA:Ma.EdDSA,ES256:Ma.ES256,ES384:Ma.ES384,ES512:Ma.ES512,ES256K:Ma.ES256K},OUe={[Ma.EdDSA]:"EdDSA",[Ma.ES256]:"ES256",[Ma.ES384]:"ES384",[Ma.ES512]:"ES512",[Ma.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(hq||(hq={}));(function(r){r[r.Iss=1]="Iss",r[r.Sub=2]="Sub",r[r.Aud=3]="Aud",r[r.Exp=4]="Exp",r[r.Nbf=5]="Nbf",r[r.Iat=6]="Iat",r[r.Cti=7]="Cti",r[r.Nonce=10]="Nonce",r[r.Ueid=256]="Ueid",r[r.Sueids=257]="Sueids",r[r.Oemid=258]="Oemid",r[r.Hwmodel=259]="Hwmodel",r[r.Hwversion=260]="Hwversion",r[r.Secboot=262]="Secboot",r[r.Dbgstat=263]="Dbgstat",r[r.Location=264]="Location",r[r.Profile=265]="Profile",r[r.Submods=266]="Submods",r[r.Measres=272]="Measres",r[r.Intuse=268]="Intuse"})(mq||(mq={}));(function(r){r[r.Enabled=0]="Enabled",r[r.Disabled=1]="Disabled",r[r.DisabledSinceBoot=2]="DisabledSinceBoot",r[r.DisabledPermanently=3]="DisabledPermanently",r[r.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(yq||(yq={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(gq||(gq={}));FC={};PC(FC,{extractDidFragment:()=>Zs,getServices:()=>$pe,getVerificationMethodByKey:()=>Bpe,getVerificationMethodTypes:()=>uz,getVerificationMethods:()=>oE,getVerificationRelationshipsById:()=>fz,isDidService:()=>pz,isDidVerificationMethod:()=>V2,isDwnDidService:()=>Ope,isPortableDid:()=>Ph,keyBytesToMultibaseId:()=>hz,multibaseIdToKeyBytes:()=>mz});Ss=class yz{constructor({uri:e,document:t,metadata:n,keyManager:i}){this.uri=e,this.document=t,this.metadata=n,this.keyManager=i}async export(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let t=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:i});t.push({...a})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(o=>Zs(o.id)===(Zs(e?.methodId)??Zs(this.document.assertionMethod?.[0])));if(!(t&&t.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:t.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:Pfe.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:s}){return await a.verify({data:o,key:i,signature:s})}}}static async import({portableDid:e,keyManager:t=new Ic}){let n=oE({didDocument:e.document});if(n.length===0)throw new nt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await t.importKey({key:i})}for(let i of n){if(!i.publicKeyJwk)throw new Error(`Verification method '${i.id}' does not contain a public key in JWK format`);let a=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:a})}return new yz({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},sb=class{static async getSigningMethod(r){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(r,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},gz=(r=>(r[r.Discoverable=0]="Discoverable",r[r.Organization=1]="Organization",r[r.Government=2]="Government",r[r.Corporation=3]="Corporation",r[r.LocalBusiness=4]="LocalBusiness",r[r.SoftwarePackage=5]="SoftwarePackage",r[r.WebApp=6]="WebApp",r[r.FinancialInstitution=7]="FinancialInstitution",r))(gz||{}),GC=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(GC||{}),wz=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(wz||{}),wq="0123456789abcdef",vz=[],vq=[];for(let r=0;r<256;r++)vz[r]=wq[r>>4&15]+wq[r&15],r<16&&(r<10?vq[48+r]=r:vq[87+r]=r);jpe=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=vz[r[n++]];return t},Mpe=(r,e=0)=>{let t=r.length||0;if(!e){let o=t;for(;o--;)e+=r[o].length}let n=new Uint8Array(e),i=e,a=t;for(;a--;)i-=r[a].length,n.set(r[a],i);return n},bq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Kpe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(k0=0;k0<bq.length;k0++)Kpe[bq.charCodeAt(k0)]=k0;Npe=new TextDecoder,bz=(r,e)=>e?new TextDecoder(e).decode(r):Npe.decode(r),Upe=new TextEncoder,Fl=r=>Upe.encode(r),Pq=typeof window<"u"?window:self,xq=Pq.crypto||Pq.msCrypto||{},jUe=xq.subtle||xq.webkitSubtle;br.bytes=-1;br._floatConversionDetected=!1;br._encode=function(r,e){if(e!=null)switch(Pz(e)){case"object":br.dict(r,e);break;case"map":br.dictMap(r,e);break;case"array":br.list(r,e);break;case"set":br.listSet(r,e);break;case"string":br.string(r,e);break;case"number":br.number(r,e);break;case"boolean":br.number(r,e);break;case"arraybufferview":br.buffer(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":br.buffer(r,new Uint8Array(e));break}};aE=new Uint8Array([101]),xz=new Uint8Array([100]),Ez=new Uint8Array([108]);br.buffer=function(r,e){r.push(Fl(e.length+":"),e)};br.string=function(r,e){r.push(Fl(Fl(e).byteLength+":"+e))};br.number=function(r,e){if(Number.isInteger(e))return r.push(Fl("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,a=n*t+i;r.push(Fl("i"+a+"e")),a!==e&&!br._floatConversionDetected&&(br._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};br.dict=function(r,e){r.push(xz);let t=0,n,i=Object.keys(e).sort(),a=i.length;for(;t<a;t++)n=i[t],e[n]!=null&&(br.string(r,n),br._encode(r,e[n]));r.push(aE)};br.dictMap=function(r,e){r.push(xz);let t=Array.from(e.keys()).sort();for(let n of t)e.get(n)!=null&&(ArrayBuffer.isView(n)?br._encode(r,n):br.string(r,String(n)),br._encode(r,e.get(n)));r.push(aE)};br.list=function(r,e){let t=0,n=e.length;for(r.push(Ez);t<n;t++)e[t]!=null&&br._encode(r,e[t]);r.push(aE)};br.listSet=function(r,e){r.push(Ez);for(let t of e)t!=null&&br._encode(r,t);r.push(aE)};Lpe=br,qpe=105,zpe=58,Fpe=100,Gpe=108,HC=101;bt.bytes=0;bt.position=0;bt.data=null;bt.encoding=null;bt.next=function(){switch(bt.data[bt.position]){case Fpe:return bt.dictionary();case Gpe:return bt.list();case qpe:return bt.integer();default:return bt.buffer()}};bt.find=function(r){let e=bt.position,t=bt.data.length,n=bt.data;for(;e<t;){if(n[e]===r)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(r)+'" [0x'+r.toString(16)+"]")};bt.dictionary=function(){bt.position++;let r={};for(;bt.data[bt.position]!==HC;){let e=bt.buffer(),t=bz(e);t.includes("\uFFFD")&&(t=jpe(e)),r[t]=bt.next()}return bt.position++,r};bt.list=function(){bt.position++;let r=[];for(;bt.data[bt.position]!==HC;)r.push(bt.next());return bt.position++,r};bt.integer=function(){let r=bt.find(HC),e=Sz(bt.data,bt.position+1,r);return bt.position+=r+1-bt.position,e};bt.buffer=function(){let r=bt.find(zpe),e=Sz(bt.data,bt.position,r),t=++r+e;return bt.position=t,bt.encoding?bz(bt.data.slice(r,t)):bt.data.slice(r,t)};Hpe=bt;kz=cE,Xpe=kz,_z={encode:Lpe,decode:Hpe,byteLength:kz,encodingLength:Xpe},Qpe=/^(\d{1,3}\.){3,3}\d{1,3}$/,ehe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Cd={name:"v4",size:4,isFormat:r=>Qpe.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let a=0;a<n;){let o=r.charCodeAt(a++);o===46?(e[t++]=i,i=0):i=i*10+(o-48)}return e[t]=i,e},decode(r,e){return e=~~e,`${r[e++]}.${r[e++]}.${r[e++]}.${r[e]}`}},xf={name:"v6",size:16,isFormat:r=>r.length>0&&ehe.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,a=0,o=0,s=!0,c=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let d=r.charCodeAt(l);d===58?(s?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(c===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2),a=0,o=0),s=!0,c=!1):d===46?(t<n&&(e[t]=o),t++,o=0,a=0,s=!1,c=!0):(s=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(s===!1)c===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2);else if(i===0)t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2;else if(i!==-1){t+=2;for(let l=Math.min(t-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=t}if(i!==t&&i!==-1)for(t>n-2&&(t=n-2);n>i;)e[--n]=t<n&&t>i?e[--t]:0;else for(;t<n;)e[t++]=0;return e},decode(r,e){e=~~e;let t="";for(let n=0;n<16;n+=2)n!==0&&(t+=":"),t+=(r[e+n]<<8|r[e+n+1]).toString(16);return t.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};Y0.bytes=0;ab.bytes=0;ph=r=>r instanceof Uint8Array;R0={},Rz=new Array(255);for(let r=0;r<=15;r+=1){let e=r.toString(16),t=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),o=r<<4|n,s=`${e}${i}`;Rz[o]=s,R0[s]=o,R0[`${t}${i}`]=o,R0[`${e}${a}`]=o,R0[`${t}${a}`]=o}}dhe=Math.pow(2,24),lhe=Math.pow(2,16),uhe=Math.pow(2,8),Ll=(r,e)=>r[e]*dhe+r[e+1]*lhe+r[e+2]*uhe+r[e+3],qt=(r,e)=>r[e]<<8|r[e+1],ql=(r,e,t)=>(e=+e,r[t+3]=e,e=e>>>8,r[t+2]=e,e=e>>>8,r[t+1]=e,e=e>>>8,r[t]=e,t+4),ot=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);phe=0,kq=32768,dC=32768,hhe=~dC,Cz=32768,mhe=~Cz;Ze=Hr({encode(r,e,t){e||(e=new Uint8Array(Ze.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let o=0;o<a.length;o++){let s=WC(e,a[o],t+1);e[t]=s,t+=s+1}}return e[t++]=0,Ze.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,a=0,o=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let s=r[e++];if(a+=o?0:1,s===0)break;if(s&192)if((s&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let c=qt(r,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+s>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=s+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(ab(r,e,e+s)),e+=s,a+=o?0:s}}return Ze.decode.bytes=a,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:Sf(r.replace(/^\.|\.$/gm,""))+2}}),mi=Hr({encode(r,e,t){e||(e=new Uint8Array(mi.encodingLength(r))),t||(t=0);let n=WC(e,r,t+1);return e[t]=n,mi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=ab(r,e+1,e+1+t);return mi.decode.bytes=t+1,n},encodingLength(r){return Sf(r)+1}}),jy=Hr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(jy.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?kq:phe;return ot(e,r.id||0,t),ot(e,n|i,t+2),ot(e,r.questions.length,t+4),ot(e,r.answers.length,t+6),ot(e,r.authorities.length,t+8),ot(e,r.additionals.length,t+10),e},decode(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=qt(r,e+2);return{id:qt(r,e),type:t&kq?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:she(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:ihe(t&15),questions:new Array(qt(r,e+4)),answers:new Array(qt(r,e+6)),authorities:new Array(qt(r,e+8)),additionals:new Array(qt(r,e+10))}},encodingLength(){return 12}}),k2=Hr({encode(r,e,t){e||(e=new Uint8Array(k2.encodingLength(r))),t||(t=0);let n=r.length;return ot(e,n,t),Xo(r,e,t+2,0,n),k2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n=r.slice(e+2,e+2+t);return k2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),_2=Hr({encode(r,e,t){return e||(e=new Uint8Array(_2.encodingLength(r))),t||(t=0),Ze.encode(r,e,t+2),ot(e,Ze.encode.bytes,t),_2.encode.bytes=Ze.encode.bytes+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n=Ze.decode(r,e+2);return _2.decode.bytes=t+2,n},encodingLength(r){return Ze.encodingLength(r)+2}}),A2=Hr({encode(r,e,t){e||(e=new Uint8Array(A2.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.mname,e,t),t+=Ze.encode.bytes,Ze.encode(r.rname,e,t),t+=Ze.encode.bytes,ql(e,r.serial||0,t),t+=4,ql(e,r.refresh||0,t),t+=4,ql(e,r.retry||0,t),t+=4,ql(e,r.expire||0,t),t+=4,ql(e,r.minimum||0,t),t+=4,ot(e,t-n-2,n),A2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=Ze.decode(r,e),e+=Ze.decode.bytes,n.rname=Ze.decode(r,e),e+=Ze.decode.bytes,n.serial=Ll(r,e),e+=4,n.refresh=Ll(r,e),e+=4,n.retry=Ll(r,e),e+=4,n.expire=Ll(r,e),e+=4,n.minimum=Ll(r,e),e+=4,A2.decode.bytes=e-t,n},encodingLength(r){return 22+Ze.encodingLength(r.mname)+Ze.encodingLength(r.rname)}}),T2=Hr({encode(r,e,t){Array.isArray(r)||(r=[r]);for(let i=0;i<r.length;i++)if(typeof r[i]=="string"&&(r[i]=VC(r[i])),!ph(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(T2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,Xo(i,e,t,0,i.length),t+=i.length}),ot(e,t-n-2,n),T2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=qt(r,e);e+=2;let i=[];for(;n>0;){let a=r[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(r.slice(e,e+a)),e+=a,n-=a}return T2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Sf(t)+1:e+=t.length+1}),e}}),I2=Hr({encode(r,e,t){e||(e=new Uint8Array(I2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=VC(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return Xo(r,e,t,0,i),t+=i,ot(e,t-n-2,n),I2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=qt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,I2.decode.bytes=e-t,i},encodingLength(r){return r?(ph(r)?r.length:Sf(r))+2:2}}),D2=Hr({encode(r,e,t){e||(e=new Uint8Array(D2.encodingLength(r))),t||(t=0);let n=t;return t+=2,mi.encode(r.cpu,e,t),t+=mi.encode.bytes,mi.encode(r.os,e,t),t+=mi.encode.bytes,ot(e,t-n-2,n),D2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=mi.decode(r,e),e+=mi.decode.bytes,n.os=mi.decode(r,e),e+=mi.decode.bytes,D2.decode.bytes=e-t,n},encodingLength(r){return mi.encodingLength(r.cpu)+mi.encodingLength(r.os)+2}}),zy=Hr({encode(r,e,t){return e||(e=new Uint8Array(zy.encodingLength(r))),t||(t=0),Ze.encode(r,e,t+2),ot(e,Ze.encode.bytes,t),zy.encode.bytes=Ze.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Ze.decode(r,e+2);return zy.decode.bytes=Ze.decode.bytes+2,t},encodingLength(r){return Ze.encodingLength(r)+2}}),R2=Hr({encode(r,e,t){e||(e=new Uint8Array(R2.encodingLength(r))),t||(t=0),ot(e,r.priority||0,t+2),ot(e,r.weight||0,t+4),ot(e,r.port||0,t+6),Ze.encode(r.target,e,t+8);let n=Ze.encode.bytes+6;return ot(e,n,t),R2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=qt(r,e),n={};return n.priority=qt(r,e+2),n.weight=qt(r,e+4),n.port=qt(r,e+6),n.target=Ze.decode(r,e+8),R2.decode.bytes=t+2,n},encodingLength(r){return 8+Ze.encodingLength(r.target)}}),vf=Hr({encode(r,e,t){let n=vf.encodingLength(r);return e||(e=new Uint8Array(vf.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=vf.ISSUER_CRITICAL),ot(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,mi.encode(r.tag,e,t),t+=mi.encode.bytes,WC(e,r.value,t),t+=Sf(r.value),vf.encode.bytes=n,e},decode(r,e){e||(e=0);let t=qt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=mi.decode(r,e),e+=mi.decode.bytes,i.value=ab(r,e,n+t),i.issuerCritical=!!(i.flags&vf.ISSUER_CRITICAL),vf.decode.bytes=t+2,i},encodingLength(r){return mi.encodingLength(r.tag)+mi.encodingLength(r.value)+2}});vf.ISSUER_CRITICAL=128;C2=Hr({encode(r,e,t){e||(e=new Uint8Array(C2.encodingLength(r))),t||(t=0);let n=t;return t+=2,ot(e,r.preference||0,t),t+=2,Ze.encode(r.exchange,e,t),t+=Ze.encode.bytes,ot(e,t-n-2,n),C2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=qt(r,e),e+=2,n.exchange=Ze.decode(r,e),e+=Ze.decode.bytes,C2.decode.bytes=e-t,n},encodingLength(r){return 4+Ze.encodingLength(r.exchange)}}),$z=Hr({encode(r,e,t){return e||(e=new Uint8Array($z.encodingLength(r))),t||(t=0),ot(e,4,t),t+=2,Cd.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,Cd.decode(r,e)},bytes:6}),$2=Hr({encode(r,e,t){return e||(e=new Uint8Array($2.encodingLength(r))),t||(t=0),ot(e,16,t),t+=2,xf.encode(r,e,t),$2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=xf.decode(r,e);return $2.decode.bytes=18,t},bytes:18}),_q=r=>new Uint8Array(r),Nl=Hr({encode(r,e,t){e||(e=new Uint8Array(Nl.encodingLength(r))),t||(t=0);let n=t,i=Eq(r.code);if(ot(e,i,t),t+=2,r.data)ot(e,r.data.length,t),t+=2,Xo(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let a=r.sourcePrefixLength||0,o=r.family||the(r.ip,_q),s=rhe(r.ip,_q),c=Math.ceil(a/8);ot(e,c+4,t),t+=2,ot(e,o,t),t+=2,e[t++]=a,e[t++]=r.scopePrefixLength||0,Xo(s,e,t,0,c),t+=c}break;case 11:r.timeout?(ot(e,2,t),t+=2,ot(e,r.timeout,t),t+=2):(ot(e,0,t),t+=2);break;case 12:{let a=r.length||0;ot(e,a,t),t+=2,e.fill(0,t,t+a),t+=a}break;case 14:{let a=r.tags.length*2;ot(e,a,t),t+=2;for(let o of r.tags)ot(e,o,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return Nl.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=qt(r,e),t.type=ohe(t.code),e+=2;let n=qt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=qt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);Xo(r,i,0,e,e+n-4),t.ip=nhe(i)}break;case 11:n>0&&(t.timeout=qt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(qt(r,e)),e+=2}return Nl.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(Eq(r.code)){case 8:{let e=r.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)}}),bf=Hr({encode(r,e,t){e||(e=new Uint8Array(bf.encodingLength(r))),t||(t=0);let n=t,i=Ly(r,Nl);return ot(e,i,t),t=M0(r,Nl,e,t+2),bf.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=qt(r,e);e+=2;let a=0;for(;i>0;)n[a++]=Nl.decode(r,e),e+=Nl.decode.bytes,i-=Nl.decode.bytes;return bf.decode.bytes=e-t,n},encodingLength(r){return 2+Ly(r||[],Nl)}}),Rd=Hr({encode(r,e,t){e||(e=new Uint8Array(Rd.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!ph(i))throw new Error("Key must be a Buffer");return t+=2,ot(e,r.flags,t),t+=2,e[t]=Rd.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,Xo(i,e,t,0,i.length),t+=i.length,Rd.encode.bytes=t-n,ot(e,Rd.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);if(e+=2,n.flags=qt(r,e),e+=2,r[e]!==Rd.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=r[e],e+=1,n.key=r.slice(e,t+i+2),e+=n.key.length,Rd.decode.bytes=e-t,n},encodingLength(r){return 6+Sf(r.key)}});Rd.PROTOCOL_DNSSEC=3;Rd.ZONE_KEY=128;Rd.SECURE_ENTRYPOINT=32768;C0=Hr({encode(r,e,t){e||(e=new Uint8Array(C0.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!ph(i))throw new Error("Signature must be a Buffer");return t+=2,ot(e,Z0(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,ql(e,r.originalTTL,t),t+=4,ql(e,r.expiration,t),t+=4,ql(e,r.inception,t),t+=4,ot(e,r.keyTag,t),t+=2,Ze.encode(r.signersName,e,t),t+=Ze.encode.bytes,Xo(i,e,t,0,i.length),t+=i.length,C0.encode.bytes=t-n,ot(e,C0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.typeCovered=dE(qt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=Ll(r,e),e+=4,n.expiration=Ll(r,e),e+=4,n.inception=Ll(r,e),e+=4,n.keyTag=qt(r,e),e+=2,n.signersName=Ze.decode(r,e),e+=Ze.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,C0.decode.bytes=e-t,n},encodingLength(r){return 20+Ze.encodingLength(r.signersName)+Sf(r.signature)}}),$0=Hr({encode(r,e,t){e||(e=new Uint8Array($0.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.mbox||".",e,t),t+=Ze.encode.bytes,Ze.encode(r.txt||".",e,t),t+=Ze.encode.bytes,$0.encode.bytes=t-n,ot(e,$0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=Ze.decode(r,e)||".",e+=Ze.decode.bytes,n.txt=Ze.decode(r,e)||".",e+=Ze.decode.bytes,$0.decode.bytes=e-t,n},encodingLength(r){return 2+Ze.encodingLength(r.mbox||".")+Ze.encodingLength(r.txt||".")}}),Yo=Hr({encode(r,e,t){e||(e=new Uint8Array(Yo.encodingLength(r))),t||(t=0);let n=t,i=[];for(let a=0;a<r.length;a++){let o=Z0(r[a]);i[o>>8]===void 0&&(i[o>>8]=[]),i[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<i.length;a++)if(i[a]!==void 0){let o=VC(i[a]);e[t]=a,t+=1,e[t]=o.length,t+=1,Xo(o,e,t,0,o.length),t+=o.length}return Yo.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let a=r[e];e+=1;let o=r[e];e+=1;for(let s=0;s<o;s++){let c=r[e+s];for(let l=0;l<8;l++)if(c&1<<7-l){let d=dE(a<<8|s<<3|l);i.push(d)}}e+=o}return Yo.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=Z0(r[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let t=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(t+=2+Math.ceil((e[n]+1)/8));return t}}),B0=Hr({encode(r,e,t){e||(e=new Uint8Array(B0.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ze.encode(r.nextDomain,e,t),t+=Ze.encode.bytes,Yo.encode(r.rrtypes,e,t),t+=Yo.encode.bytes,B0.encode.bytes=t-n,ot(e,B0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.nextDomain=Ze.decode(r,e),e+=Ze.decode.bytes,n.rrtypes=Yo.decode(r,e,i-(e-t)),e+=Yo.decode.bytes,B0.decode.bytes=e-t,n},encodingLength(r){return 2+Ze.encodingLength(r.nextDomain)+Yo.encodingLength(r.rrtypes)}}),O0=Hr({encode(r,e,t){e||(e=new Uint8Array(O0.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!ph(i))throw new Error("salt must be a Buffer");let a=r.nextDomain;if(!ph(a))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,ot(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,Xo(i,e,t,0,i.length),t+=i.length,e[t]=a.length,t+=1,Xo(a,e,t,0,a.length),t+=a.length,Yo.encode(r.rrtypes,e,t),t+=Yo.encode.bytes,O0.encode.bytes=t-n,ot(e,O0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=qt(r,e),e+=2;let a=r[e];e+=1,n.salt=r.slice(e,e+a),e+=a;let o=r[e];return e+=1,n.nextDomain=r.slice(e,e+o),e+=o,n.rrtypes=Yo.decode(r,e,i-(e-t)),e+=Yo.decode.bytes,O0.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+Yo.encodingLength(r.rrtypes)}}),j0=Hr({encode(r,e,t){e||(e=new Uint8Array(j0.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!ph(i))throw new Error("Digest must be a Buffer");return t+=2,ot(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,Xo(i,e,t,0,i.length),t+=i.length,j0.encode.bytes=t-n,ot(e,j0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=qt(r,e);return e+=2,n.keyTag=qt(r,e),e+=2,n.algorithm=r[e],e+=1,n.digestType=r[e],e+=1,n.digest=r.slice(e,t+i+2),e+=n.digest.length,j0.decode.bytes=e-t,n},encodingLength(r){return 6+Sf(r.digest)}}),Uy=Hr({encode(r,e,t){e||(e=new Uint8Array(Uy.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=Sq(r.fingerprint),a=lC(r.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${a}`);return che(e,r.fingerprint,t,t+=i),Uy.encode.bytes=t-n,ot(e,Uy.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};e+=2,n.algorithm=r[e],e+=1,n.hash=r[e],e+=1;let i=lC(n.hash);return n.fingerprint=ahe(r,e,e+i),e+=i,Uy.decode.bytes=e-t,n},encodingLength(r){return 4+Sq(r.fingerprint)}});Uy.getFingerprintLengthForHashType=lC;Ba=Hr({encode(r,e,t){e||(e=new Uint8Array(Ba.encodingLength(r))),t||(t=0);let n=t;if(Ze.encode(r.name,e,t),t+=Ze.encode.bytes,ot(e,Z0(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");ot(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,ot(e,r.flags||0,t+6),t+=8,bf.encode(r.options||[],e,t),t+=bf.encode.bytes}else{let i=Iz(r.class===void 0?"IN":r.class);r.flush&&(i|=dC),ot(e,i,t+2),ql(e,r.ttl||0,t+4),t+=8;let a=ZR(r.type);a.encode(r.data,e,t),t+=a.encode.bytes}return Ba.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=Ze.decode(r,e),e+=Ze.decode.bytes,t.type=dE(qt(r,e)),t.type==="OPT")t.udpPayloadSize=qt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=qt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=bf.decode(r,e+8),e+=8+bf.decode.bytes;else{let i=qt(r,e+2);t.ttl=Ll(r,e+4),t.class=Tz(i&hhe),t.flush=!!(i&dC);let a=ZR(t.type);t.data=a.decode(r,e+8),e+=8+a.decode.bytes}return Ba.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return Ze.encodingLength(r.name)+8+ZR(r.type).encodingLength(e)}}),Fy=Hr({encode(r,e,t){e||(e=new Uint8Array(Fy.encodingLength(r))),t||(t=0);let n=t;return Ze.encode(r.name,e,t),t+=Ze.encode.bytes,ot(e,Z0(r.type),t),t+=2,ot(e,Iz(r.class===void 0?"IN":r.class),t),t+=2,Fy.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=Ze.decode(r,e),e+=Ze.decode.bytes,n.type=dE(qt(r,e)),e+=2,n.class=Tz(qt(r,e)),e+=2,n.class&Cz&&(n.class&=mhe),Fy.decode.bytes=e-t,n},encodingLength(r){return Ze.encodingLength(r.name)+4}}),yhe=1024,os={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(ghe(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),jy.encode(r,e,t),t+=jy.encode.bytes,t=M0(r.questions,Fy,e,t),t=M0(r.answers,Ba,e,t),t=M0(r.authorities,Ba,e,t),t=M0(r.additionals,Ba,e,t),os.encode.bytes=t-i,n&&Y2.bytes!==e.length?e.slice(0,Y2.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=jy.decode(r,e);return e+=jy.decode.bytes,e=g2(n.questions,Fy,r,e),e=g2(n.answers,Ba,r,e),e=g2(n.authorities,Ba,r,e),e=g2(n.additionals,Ba,r,e),os.decode.bytes=e-t,n},encodingLength:function(r){return jy.encodingLength(r)+Ly(r.questions||[],Fy)+Ly(r.answers||[],Ba)+Ly(r.authorities||[],Ba)+Ly(r.additionals||[],Ba)}};os.encode.bytes=0;os.decode.bytes=0;J2={encode:function(r,e,t){return e=os.encode(W2(r,"query"),e,t),J2.encode.bytes=os.encode.bytes,e},decode:function(r,e){let t=os.decode(r,e);return J2.decode.bytes=os.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return os.encodingLength(W2(r,"query"))}};J2.encode.bytes=0;J2.decode.bytes=0;Z2={encode:function(r,e,t){return e=os.encode(W2(r,"response"),e,t),Z2.encode.bytes=os.encode.bytes,e},decode:function(r,e){let t=os.decode(r,e);return Z2.decode.bytes=os.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return os.encodingLength(W2(r,"response"))}};Z2.encode.bytes=0;Z2.decode.bytes=0;Y2=os.encode,uC=os.decode,ghe=os.encodingLength;Bz.bytes=0;Oz.bytes=0;Mz="dht";Ehe=0,mf=7200,B2=";",Js=",",Uz={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},Lz={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};Tq=O.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",zz=class fC extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.verificationMethods?.some(d=>!(d.algorithm in Uz)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:i}),o=await qy.identityKeyToIdentifier({identityKey:a}),s={id:o,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},c=[...t.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let u=d.id&&d.id.split("#").pop()==="0"?i:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:u}),p=d.id??f.kid??await _r({jwk:f});p=`${o}#${Zs(p)}`,s.verificationMethod??=[],s.verificationMethod.push({id:p,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let h of d.purposes??[])s[h]??=[],s[h].push(p)}t.services?.forEach(d=>{s.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,s.service.push(d)});let l=new Ss({uri:o,document:s,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let d=await fC.publish({did:l,gatewayUri:t.gatewayUri});l.metadata=d.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==fC.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new nt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Zs(a.id)===(Zs(t)??Zs(e.assertionMethod?.[0])));if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t=Tq}){return await Iq.put({did:e,gatewayUri:t})}static async resolve(e,t={}){let n=t?.gatewayUri??Tq;try{await qy.identifierToIdentityKey({didUri:e});let{didDocument:i,didDocumentMetadata:a}=await Iq.get({didUri:e,gatewayUri:n});return{...Di,didDocument:i,didDocumentMetadata:a}}catch(i){if(!(i instanceof nt))throw new Error(i);return{...Di,didResolutionMetadata:{error:i.code,...i.message&&{errorMessage:i.message}}}}}};zz.methodName="dht";vo=zz,Iq=class N0{static async get({didUri:e,gatewayUri:t}){let n=qy.identifierToIdentityKeyBytes({didUri:e}),i=await N0.pkarrGet({gatewayUri:t,publicKeyBytes:n}),a=await qy.parseBep44GetMessage({bep44Message:i}),o=await N0.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=i.seq.toString(),o}static async put({did:e,gatewayUri:t}){let n=await N0.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),i=await qy.createBep44PutMessage({dnsPacket:n,publicKeyBytes:qy.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await N0.pkarrPut({gatewayUri:t,bep44Message:i});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:i.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return whe(e)}static async pkarrPut(e){return vhe(e)}static async fromDnsPacket(e){return She(e)}static async toDnsPacket(e){return khe(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},qy=class{static async createBep44PutMessage(r){return bhe(r)}static async identifierToIdentityKey(r){return Kz(r)}static identifierToIdentityKeyBytes(r){return JC(r)}static async identityKeyToIdentifier(r){return xhe(r)}static keyConverter(r){return ZC(r)}static async parseBep44GetMessage(r){return Phe(r)}static parseTxtDataToObject(r){return K0(r)}static parseTxtDataToString(r){return X0(r)}static async validatePreviousDidProof(r){return Nz(r)}static chunkDataIfNeeded(r){return qz(r)}},Hn={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"},Vn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},MUe=new Uint8Array(0),_he=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Ahe=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},The=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return Fz(this,r)}},Ihe=class{constructor(r){this.decoders=r}or(r){return Fz(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Fz=(r,e)=>new Ihe({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Dhe=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Ahe(r,e,t),this.decoder=new The(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rhe=({name:r,prefix:e,encode:t,decode:n})=>new Dhe(r,e,t,n),Che=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let o=new Uint8Array(a*t/8|0),s=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,s+=t,s>=8&&(s-=8,o[l++]=255&c>>s)}if(s>=t||255&c<<8-s)throw new SyntaxError("Unexpected end of data");return o},$he=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",o=0,s=0;for(let c=0;c<r.length;++c)for(s=s<<8|r[c],o+=8;o>t;)o-=t,a+=e[i&s>>o];if(o&&(a+=e[i&s<<t-o]),n)for(;a.length*t&7;)a+="=";return a},lE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rhe({prefix:e,name:r,encode(i){return $he(i,n,t)},decode(i){return Che(i,n,t,r)}}),KUe=lE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),NUe=lE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dq=lE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UUe=lE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Wy=class O2{static encode(e){return Dq.baseEncode(e)}static decodeAsBytes(e,t){if(!O2.isBase64UrlString(e))throw new Vn(Hn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return Dq.baseDecode(e)}static decodeAsString(e,t){let n=O2.decodeAsBytes(e,t);return O2.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}},Bhe=hh($de(),1);(function(r){r.Public="public",r.Private="private"})(pC||(pC={}));Dd=pC,Wo=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Dd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Vn(Hn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Vn(Hn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Vn(Hn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Dd.Private&&(r.d===void 0||r.d.length!==43))throw new Vn(Hn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Vn(Hn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!Wy.isBase64UrlString(r))throw new Vn(Hn.IdNotUsingBase64UrlCharacterSet,`Key ID '${r}' is not a Base64URL string.`)}static validatePublicKeyPurposes(r){if(r===void 0)return;let e=new Set;for(let t of r){if(e.has(t))throw new Vn(Hn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},YC=class{};YC.hashAlgorithmInMultihashCode=18;YC.maxCanonicalizedDeltaSizeInBytes=1e3;Tc=YC,Ohe=hh(Bde(),1),Q0=class hC{static canonicalizeAsBytes(e){let t=hC.removeAllUndefinedProperties(e),n=Ohe.default(t);return Wy.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?hC.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},jhe=Gz,Rq=128,Mhe=127,Khe=~Mhe,Nhe=Math.pow(2,31);Uhe=mC,Lhe=128,Cq=127;qhe=Math.pow(2,7),zhe=Math.pow(2,14),Fhe=Math.pow(2,21),Ghe=Math.pow(2,28),Hhe=Math.pow(2,35),Vhe=Math.pow(2,42),Whe=Math.pow(2,49),Jhe=Math.pow(2,56),Zhe=Math.pow(2,63),Yhe=function(r){return r<qhe?1:r<zhe?2:r<Fhe?3:r<Ghe?4:r<Hhe?5:r<Vhe?6:r<Whe?7:r<Jhe?8:r<Zhe?9:10},Xhe={encode:jhe,decode:Uhe,encodingLength:Yhe},Qhe=Xhe,X2=Qhe,$q=(r,e=0)=>[X2.decode(r,e),X2.decode.bytes],Bq=(r,e,t=0)=>(X2.encode(r,e,t),e),Oq=r=>X2.encodingLength(r),jq=(r,e)=>{let t=e.byteLength,n=Oq(r),i=n+Oq(t),a=new Uint8Array(i+t);return Bq(r,a,0),Bq(t,a,n),a.set(e,i),new Hz(r,t,e,a)},eme=r=>{let e=_he(r),[t,n]=$q(e),[i,a]=$q(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==i)throw new Error("Incorrect length");return new Hz(t,i,o,e)},Hz=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},Vz=({name:r,code:e,encode:t})=>new tme(r,e,t),tme=class{constructor(r,e,t){this.name=r,this.code=e,this.encode=t}digest(r){if(r instanceof Uint8Array){let e=this.encode(r);return e instanceof Uint8Array?jq(this.code,e):e.then(t=>jq(this.code,t))}else throw Error("Unknown type, must be binary type")}},Wz=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Mq=Vz({name:"sha2-256",code:18,encode:Wz("SHA-256")}),LUe=Vz({name:"sha2-512",code:19,encode:Wz("SHA-512")}),_0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Zo=class U0{static hash(e,t){return _0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield Mq.digest(e)).bytes;break;default:throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return _0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield Mq.encode(e);break;default:throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=Q0.canonicalizeAsBytes(e);return yield U0.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=Q0.canonicalizeAsBytes(e),i=yield U0.hashAsNonMultihashBytes(n,t);return yield U0.hashThenEncode(i,t)})}static hashThenEncode(e,t){return _0(this,void 0,void 0,function*(){let n=yield U0.hash(e,t);return Wy.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=Wy.decodeAsBytes(e,t);try{n=eme(i)}catch{throw new Vn(Hn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let a=Tc.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Vn(Hn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(yC||(yC={}));w2=yC;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(gC||(gC={}));By=gC,v2=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Jz=class Ca{static createCreateRequest(e){return v2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;Wo.validateEs256kOperationKey(t,Dd.Public),Wo.validateEs256kOperationKey(n,Dd.Public),Ca.validateDidDocumentKeys(i),Ca.validateServices(a);let o=Tc.hashAlgorithmInMultihashCode,s=[{action:By.Replace,document:e.document}],c={updateCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(n,o),patches:s};Ca.validateDeltaSize(c);let l={deltaHash:yield Zo.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(t,o)};return{type:w2.Create,suffixData:l,delta:c}})}static createDeactivateRequest(e){return v2(this,void 0,void 0,function*(){Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.recoveryPublicKey,Dd.Public);let t=Tc.hashAlgorithmInMultihashCode,n=yield Zo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:w2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return v2(this,void 0,void 0,function*(){Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.recoveryPublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextRecoveryPublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextUpdatePublicKey,Dd.Public),Ca.validateDidDocumentKeys(e.document.publicKeys),Ca.validateServices(e.document.services);let t=Tc.hashAlgorithmInMultihashCode,n=yield Zo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:By.Replace,document:e.document}],a=yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),o={patches:i,updateCommitment:a},s=yield Zo.canonicalizeThenHashThenEncode(o,t),c={recoveryCommitment:yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:s},l=yield e.signer.sign({alg:"ES256K"},c);return{type:w2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:l}})}static createUpdateRequest(e){return v2(this,void 0,void 0,function*(){if(Ca.validateDidSuffix(e.didSuffix),Wo.validateEs256kOperationKey(e.updatePublicKey,Dd.Public),Wo.validateEs256kOperationKey(e.nextUpdatePublicKey,Dd.Public),Ca.validateServices(e.servicesToAdd),Ca.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let h of e.idsOfServicesToRemove)Wo.validateId(h);if(e.idsOfPublicKeysToRemove!==void 0)for(let h of e.idsOfPublicKeysToRemove)Wo.validateId(h);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let h={action:By.AddServices,services:n};t.push(h)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let h={action:By.RemoveServices,ids:i};t.push(h)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let h={action:By.AddPublicKeys,publicKeys:a};t.push(h)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let h={action:By.RemovePublicKeys,ids:o};t.push(h)}let s=Tc.hashAlgorithmInMultihashCode,c=yield Zo.canonicalizeThenHashThenEncode(e.updatePublicKey,s),l=yield Zo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,s),d={patches:t,updateCommitment:l},u=yield Zo.canonicalizeThenHashThenEncode(d,s),f={updateKey:e.updatePublicKey,deltaHash:u},p=yield e.signer.sign({alg:"ES256K"},f);return{type:w2.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:p}})}static validateDidSuffix(e){Zo.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let t=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Vn(Hn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Wo.validateId(n.id),t.has(n.id))throw new Vn(Hn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),Wo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Ca.validateService(n),t.has(n.id))throw new Vn(Hn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){Wo.validateId(e.id);let t=30;if(e.type.length>t){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${t}.`;throw new Vn(Hn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Vn(Hn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Bhe.parse(e.serviceEndpoint).error!==void 0)throw new Vn(Hn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=Q0.canonicalizeAsBytes(e);if(t.length>Tc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Tc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Vn(Hn.DeltaExceedsMaximumSize,n)}}},Kq=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},rme=class Zz{static createLongFormDid(e){return Kq(this,void 0,void 0,function*(){let t=yield Jz.createCreateRequest(e),n=yield Zz.computeDidUniqueSuffix(t.suffixData),i;Tc.network===void 0||Tc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Tc.network}:${n}`;let a={suffixData:t.suffixData,delta:t.delta},o=Q0.canonicalizeAsBytes(a),s=Wy.encode(o);return`${i}:${s}`})}static computeDidUniqueSuffix(e){return Kq(this,void 0,void 0,function*(){let t=Q0.canonicalizeAsBytes(e),n=yield Zo.hash(t,Tc.hashAlgorithmInMultihashCode);return Wy.encode(n)})}},rs=2n**255n-19n,j2=2n**252n+27742317777372353535851937790883648493n,wC=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,vC=0x6666666666666666666666666666666666666666666666666666666666666658n,b2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:rs,n:j2,h:8,Gx:wC,Gy:vC},go=(r="")=>{throw new Error(r)},Yz=r=>typeof r=="string",XC=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?go("Uint8Array expected"):r,Jy=r=>new Uint8Array(r),nme=(r,e)=>XC(Yz(r)?e6(r):Jy(r),e),lt=(r,e=rs)=>{let t=r%e;return t>=0n?t:e+t},Nq=r=>r instanceof Zy?r:go("Point expected"),Zy=class My{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new My(e.x,e.y,1n,lt(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=b2;e=nme(e,32);let i=e.slice();i[31]=e[31]&-129;let a=sme(i);a===0n||(t&&!(0n<a&&a<rs)&&go("bad y coord 1"),!t&&!(0n<a&&a<2n**256n)&&go("bad y coord 2"));let o=lt(a*a),s=lt(o-1n),c=lt(n*o+1n),{isValid:l,value:d}=ame(s,c);l||go("bad y coordinate 3");let u=(d&1n)===1n;return(e[31]&128)!==0!==u&&(d=lt(-d)),new My(d,a,1n,lt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:a,ey:o,ez:s}=Nq(e),c=lt(t*s),l=lt(a*i),d=lt(n*s),u=lt(o*i);return c===l&&d===u}is0(){return this.equals(M2)}negate(){return new My(lt(-this.ex),this.ey,this.ez,lt(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=b2,a=lt(e*e),o=lt(t*t),s=lt(2n*lt(n*n)),c=lt(i*a),l=e+t,d=lt(lt(l*l)-a-o),u=c+o,f=u-s,p=c-o,h=lt(d*f),m=lt(u*p),y=lt(d*p),v=lt(f*u);return new My(h,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:a}=this,{ex:o,ey:s,ez:c,et:l}=Nq(e),{a:d,d:u}=b2,f=lt(t*o),p=lt(n*s),h=lt(a*u*l),m=lt(i*c),y=lt((t+n)*(o+s)-f-p),v=lt(m-h),w=lt(m+h),x=lt(p-d*f),_=lt(y*v),A=lt(w*x),D=lt(y*x),N=lt(v*w);return new My(_,A,N,D)}mul(e,t=!0){if(e===0n)return t===!0?go("cannot multiply by 0"):M2;if(typeof e=="bigint"&&0n<e&&e<j2||go("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(Q2))return lme(e).p;let n=M2,i=Q2;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(b2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(j2/2n,!1).double();return j2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:t,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=Qz(n);return lt(n*i)!==1n&&go("invalid inverse"),{x:lt(e*i),y:lt(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=ime(t);return n[31]|=e&1n?128:0,n}toHex(){return QC(this.toRawBytes())}};Zy.BASE=new Zy(wC,vC,1n,lt(wC*vC));Zy.ZERO=new Zy(0n,1n,1n,0n);({BASE:Q2,ZERO:M2}=Zy),Xz=(r,e)=>r.toString(16).padStart(e,"0"),QC=r=>Array.from(r).map(e=>Xz(e,2)).join(""),e6=r=>{let e=r.length;(!Yz(r)||e%2)&&go("hex invalid 1");let t=Jy(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&go("hex invalid 2"),t[n]=o}return t},ime=r=>e6(Xz(r,32*2)).reverse(),sme=r=>BigInt("0x"+QC(Jy(XC(r)).reverse())),Lq=(...r)=>{let e=Jy(r.reduce((n,i)=>n+XC(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},Qz=(r,e=rs)=>{(r===0n||e<=0n)&&go("no inverse n="+r+" mod="+e);let t=lt(r,e),n=e,i=0n,a=1n,o=1n,s=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}return n===1n?lt(i,e):go("no inverse")},Ad=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=rs;return t},ome=r=>{let e=r*r%rs*r%rs,t=Ad(e,2n)*e%rs,n=Ad(t,1n)*r%rs,i=Ad(n,5n)*n%rs,a=Ad(i,10n)*i%rs,o=Ad(a,20n)*a%rs,s=Ad(o,40n)*o%rs,c=Ad(s,80n)*s%rs,l=Ad(c,80n)*s%rs,d=Ad(l,10n)*i%rs;return{pow_p_5_8:Ad(d,2n)*r%rs,b2:e}},qq=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ame=(r,e)=>{let t=lt(e*e*e),n=lt(t*t*e),i=ome(r*n).pow_p_5_8,a=lt(r*t*i),o=lt(e*a*a),s=a,c=lt(a*qq),l=o===r,d=o===lt(-r),u=o===lt(-r*qq);return l&&(a=s),(d||u)&&(a=c),(lt(a)&1n)===1n&&(a=lt(-a)),{isValid:l||d,value:a}},zq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,cme={bytesToHex:QC,hexToBytes:e6,concatBytes:Lq,mod:lt,invert:Qz,randomBytes:r=>{let e=zq();return e||go("crypto.getRandomValues must be defined"),e.getRandomValues(Jy(r))},sha512Async:async(...r)=>{let e=zq();e||go("crypto.subtle or etc.sha512Async must be defined");let t=Lq(...r);return Jy(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(cme,{sha512Sync:{configurable:!1,get(){return YR},set(r){YR||(YR=r)}}});ih=8,dme=()=>{let r=[],e=256/ih+1,t=Q2,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(ih-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},lme=r=>{let e=Uq||(Uq=dme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=M2,i=Q2,a=1+256/ih,o=2**(ih-1),s=BigInt(2**ih-1),c=2**ih,l=BigInt(ih);for(let d=0;d<a;d++){let u=d*o,f=Number(r&s);r>>=l,f>o&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}},t6=2n**256n,lh=t6-0x1000003d1n,r6=t6-0x14551231950b75fc4402da1732fc9bebfn,eF=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,tF=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,rF={p:lh,n:r6,a:0n,b:7n,Gx:eF,Gy:tF},Gy=32,Fq=r=>et(et(r*r)*r+rF.b),Ii=(r="")=>{throw new Error(r)},uE=r=>typeof r=="bigint",nF=r=>typeof r=="string",XR=r=>uE(r)&&0n<r&&r<lh,iF=r=>uE(r)&&0n<r&&r<r6,sF=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ii("Uint8Array expected"):r,eb=r=>new Uint8Array(r),n6=(r,e)=>sF(nF(r)?fE(r):eb(r),e),et=(r,e=lh)=>{let t=r%e;return t>=0n?t:e+t},Gq=r=>r instanceof Yy?r:Ii("Point expected"),Yy=class Ky{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Ky(e.x,e.y,1n)}static fromHex(e){e=n6(e);let t,n=e[0],i=e.subarray(1),a=Vq(i,0,Gy),o=e.length;if(o===33&&[2,3].includes(n)){XR(a)||Ii("Point hex invalid: x not FE");let s=ume(Fq(a)),c=(s&1n)===1n;(n&1)===1!==c&&(s=et(-s)),t=new Ky(a,s,1n)}return o===65&&n===4&&(t=new Ky(a,Vq(i,Gy,2*Gy),1n)),t?t.ok():Ii("Point is not on curve")}static fromPrivateKey(e){return F0.mul(fme(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:a,py:o,pz:s}=Gq(e),c=et(t*s),l=et(a*i),d=et(n*s),u=et(o*i);return c===l&&d===u}negate(){return new Ky(this.px,et(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:a,py:o,pz:s}=Gq(e),{a:c,b:l}=rF,d=0n,u=0n,f=0n,p=et(l*3n),h=et(t*a),m=et(n*o),y=et(i*s),v=et(t+n),w=et(a+o);v=et(v*w),w=et(h+m),v=et(v-w),w=et(t+i);let x=et(a+s);return w=et(w*x),x=et(h+y),w=et(w-x),x=et(n+i),d=et(o+s),x=et(x*d),d=et(m+y),x=et(x-d),f=et(c*w),d=et(p*y),f=et(d+f),d=et(m-f),f=et(m+f),u=et(d*f),m=et(h+h),m=et(m+h),y=et(c*y),w=et(p*w),m=et(m+y),y=et(h-y),y=et(c*y),w=et(w+y),h=et(m*w),u=et(u+h),h=et(x*w),d=et(v*d),d=et(d-h),h=et(v*m),f=et(x*f),f=et(f+h),new Ky(d,u,f)}mul(e,t=!0){if(!t&&e===0n)return K2;if(iF(e)||Ii("invalid scalar"),this.equals(F0))return yme(e).p;let n=K2,i=F0;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}mulAddQUns(e,t,n){return this.mul(t,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:t,pz:n}=this;if(this.equals(K2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=aF(n);return et(n*i)!==1n&&Ii("invalid inverse"),{x:et(e*i),y:et(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!XR(e)||!XR(t))&&Ii("Point invalid: x or y"),et(t*t)===Fq(e)?this:Ii("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:t,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+Wq(t)+(e?"":Wq(n))}toRawBytes(e=!0){return fE(this.toHex(e))}};Yy.BASE=new Yy(eF,tF,1n);Yy.ZERO=new Yy(0n,1n,0n);({BASE:F0,ZERO:K2}=Yy),oF=(r,e)=>r.toString(16).padStart(e,"0"),i6=r=>Array.from(r).map(e=>oF(e,2)).join(""),fE=r=>{let e=r.length;(!nF(r)||e%2)&&Ii("hex invalid 1");let t=eb(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Ii("hex invalid 2"),t[n]=o}return t},pE=r=>BigInt("0x"+(i6(r)||"0")),Vq=(r,e,t)=>pE(r.slice(e,t)),s6=r=>uE(r)&&r>=0n&&r<t6?fE(oF(r,2*Gy)):Ii("bigint expected"),Wq=r=>i6(s6(r)),Jq=(...r)=>{let e=eb(r.reduce((n,i)=>n+sF(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},aF=(r,e=lh)=>{(r===0n||e<=0n)&&Ii("no inverse n="+r+" mod="+e);let t=et(r,e),n=e,i=0n,a=1n,o=1n,s=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-o*c,u=a-s*c;n=t,t=l,i=o,a=s,o=d,s=u}return n===1n?et(i,e):Ii("no inverse")},ume=r=>{let e=1n;for(let t=r,n=(lh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%lh),t=t*t%lh;return et(e*e)===r?e:Ii("sqrt invalid")},fme=r=>(uE(r)||(r=pE(n6(r,Gy))),iF(r)?r:Ii("private key out of range")),Zq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;hme={hexToBytes:fE,bytesToHex:i6,concatBytes:Jq,bytesToNumberBE:pE,numberToBytesBE:s6,mod:et,invert:aF,hmacSha256Async:async(r,...e)=>{let t=Zq();if(!t)return Ii("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return eb(await n.sign("HMAC",i,Jq(...e)))},hmacSha256Sync:N2,hashToPrivateKey:pme,randomBytes:r=>{let e=Zq();return e||Ii("crypto.getRandomValues must be defined"),e.getRandomValues(eb(r))}};Object.defineProperties(hme,{hmacSha256Sync:{configurable:!1,get(){return N2},set(r){N2||(N2=r)}}});sh=8,mme=()=>{let r=[],e=256/sh+1,t=F0,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(sh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},yme=r=>{let e=Hq||(Hq=mme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=K2,i=F0,a=1+256/sh,o=2**(sh-1),s=BigInt(2**sh-1),c=2**sh,l=BigInt(sh);for(let d=0;d<a;d++){let u=d*o,f=Number(r&s);r>>=l,f>o&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(Yq||(Yq={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(Xq||(Xq={}));A0=class rh{static appendPathToUrl({baseUrl:e,path:t}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=t.startsWith("/")?t.substring(1):t,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:t,services:n,verificationMethods:i}){let a=await rh.createIonDocument({services:n,verificationMethods:i}),o=rh.normalizeJwk(e),s=rh.normalizeJwk(t);return await rme.createLongFormDid({document:a,recoveryKey:o,updateKey:s})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await Jz.createCreateRequest({document:e,recoveryKey:rh.normalizeJwk(t),updateKey:rh.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let a of t){let o=a.id??a.publicKeyJwk.kid??await _r({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let s={id:o,publicKeyJwk:rh.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(s)}let i=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:i}}static normalizeJwk(e){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);return n}},gme=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(gme||{}),wme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Qq="https://ion.tbd.engineering",vme=class L0 extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.verificationMethods?.some(h=>!(h.algorithm in wme)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(h=>"id"in h).map(h=>h.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(h=>!h.id||!h.type||!h.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let h of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:h.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:h.id,publicKeyJwk:y,purposes:h.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),s=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:c}),d=await A0.computeLongFormDidUri({recoveryKey:s,updateKey:l,services:t.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await L0.resolve(d,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let p=new Ss({uri:d,document:u,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:s,updateKey:l},keyManager:e});if(t.publish??!0){let h=await L0.publish({did:p,gatewayUri:t.gatewayUri});p.metadata=h.didDocumentMetadata}return p}static async getSigningMethod({didDocument:e,methodId:t}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(t??e.assertionMethod?.[0]));if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==L0.methodName)throw new nt("methodNotSupported","Method not supported");return await Ss.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=Qq}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:fz({didDocument:e.document,methodId:o.id})}))??[],i=await A0.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await A0.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=A0.appendPathToUrl({baseUrl:t,path:"/operations"}),s=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:s.ok},didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:"internalError",errorMessage:`Failed to publish DID document for: ${e.uri}`}}}}static async resolve(e,t={}){let n=Jn.parse(e);if(!n)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L0.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??Qq;try{let a=A0.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new nt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:s,didDocumentMetadata:c}=await o.json();return{...Di,...s&&{didDocument:s},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof nt))throw new Error(a);return{...Di,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};vme.methodName="ion";cF=class q0 extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),o=st.object(a).toBase64Url(),s=`did:${q0.methodName}:${o}`,c=(await q0.resolve(s)).didDocument;return new Ss({uri:s,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Jn.parse(e.id);if(t&&t.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==q0.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new nt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Jn.parse(e),i;try{i=n?st.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==q0.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:i}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],i.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...Di,didDocument:a}}};cF.methodName="jwk";bo=cF,bme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},U2=class Ny{static async jwkToMulticodec({jwk:e}){let t=[];e.crv&&(t.push(e.crv),e.d?t.push("private"):t.push("public"));let n=t.join(":"),i=Ny.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ua.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":xs.compressPublicKey,secp256k1:ns.compressPublicKey}[e];if(!t)throw new nt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:is,"P-256":xs,secp256k1:ns}[e];if(!t)throw new nt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static async multicodecToJwk({code:e,name:t}){if(!(t?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");t=t===void 0?Ua.getNameFromCode({code:e}):t;let n=t,i=Ny.MULTICODEC_TO_JWK[n];if(i===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...i}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in bme))throw new nt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Ny.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Ny.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Ny.jwkToMulticodec({jwk:e});return hz({keyBytes:t,multicodecName:n})}};U2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},U2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},U2.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""}};P2=U2,Pme=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(Pme||{}),e7={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},dF=class wf extends sb{static async create({keyManager:e=new Ic,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),o=await P2.publicKeyToMultibaseId({publicKey:a}),s=`did:${wf.methodName}:${o}`,c=(await wf.resolve(s,t)).didDocument;return new Ss({uri:s,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Jn.parse(e.id);if(t&&t.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!(i&&i.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==wf.methodName)throw new nt("methodNotSupported","Method not supported");let n=await Ss.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new nt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await wf.createDocument({didUri:e,options:t});return{...Di,didDocument:n}}catch(n){if(!(n instanceof nt))throw new Error(n);return{...Di,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:t={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=t,o={id:""},s=Jn.parse(e);if(!s)throw new nt("invalidDid",`Invalid DID URI: ${e}`);let c=s.id;if(s.method!==wf.methodName)throw new nt("methodNotSupported",`Method not supported: ${s.method}`);if(!wf.validateIdentifier(s))throw new nt("invalidDid",`Invalid DID URI: ${e}`);let l=await wf.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}});o.id=s.uri,o.verificationMethod=[l],o.authentication=[l.id],o.assertionMethod=[l.id],o.capabilityInvocation=[l.id],o.capabilityDelegation=[l.id];let d=[n];return uz({didDocument:o}).forEach(u=>{let f=e7[u];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:s,multicodecCode:c,multicodecName:l}=mz({multibaseKeyId:t}),d=s.byteLength,u=P2.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==u)throw new nt("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await ns.validatePublicKey({publicKeyBytes:s});break;case"ed25519-pub":f=await is.validatePublicKey({publicKeyBytes:s});break}if(!f)throw new nt("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${t}`;try{new URL(o.id)}catch{throw new nt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in e7))throw new nt("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new nt("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=t),a==="JsonWebKey2020"){let{crv:p}=await P2.multicodecToJwk({code:c});o.publicKeyJwk=await P2.keyConverter(p).bytesToPublicKey({publicKeyBytes:s})}return o}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&QR(n)==="String"&&n.startsWith("z")}};dF.methodName="key";cb=dF,xme=3e4;lF=class L2 extends sb{static async create({keyManager:e=new Ic,options:t}){if(!t.domain)throw new nt("invalidDid","The 'domain' option is required for did:web creation");if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=t.path?`${t.domain}:${t.path}`:t.domain,i=`did:${L2.methodName}:${n}`;if(!Jn.parse(i))throw new nt("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let s=0;s<a.length;s++){let c=a[s],l=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:l}),u=c.id?.split("#").pop()??`key-${s}`,f=`${i}#${u}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??i,publicKeyJwk:d});for(let p of c.purposes??[])o[p]??=[],o[p].push(f)}return t.services&&(o.service=t.services.map(s=>({...s,id:`${i}#${s.id.split("#").pop()}`}))),new Ss({uri:i,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Jn.parse(e.id);if(n&&n.method!==this.methodName)throw new nt("methodNotSupported",`Method not supported: ${n.method}`);let i=Zs(t)??Zs(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(o=>Zs(o.id)===i):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new nt("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:t=new Ic}){if(Jn.parse(e.uri)?.method!==L2.methodName)throw new nt("methodNotSupported","Method not supported");return await Ss.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Jn.parse(e);if(!n)return{...Di,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L2.methodName)return{...Di,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let a=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let o=new URL(a);if(Eme(o.hostname))return{...Di,didResolutionMetadata:{error:"notFound"}};let s=await fetch(a,{signal:AbortSignal.timeout(xme)});if(!s.ok)throw new Error("HTTP error status code returned");let c=await s.json();return{...Di,didDocument:c}}catch{return{...Di,didResolutionMetadata:{error:"notFound"}}}}};lF.methodName="web";uF=lF,Sme=hh(l7(),1),kme=hh(u7(),1),hE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new Sme.Level(e),this.ttl=(0,kme.default)(t)}open(){return this.cache.open()}async get(r){try{let e=await this.cache.get(r),t=JSON.parse(e);if(Date.now()>=t.ttlMillis){this.cache.nextTick(()=>this.cache.del(r));return}else return t.value}catch(e){if(e.notFound)return;throw e}}set(r,e){let t={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(t);return this.cache.put(r,n)}delete(r){return this.cache.del(r)}clear(){return this.cache.clear()}close(){return this.cache.close()}},_me=hh(u7(),1),mE=class{constructor({ttl:r="15m"}={}){this.cache=new jde.default({ttl:(0,_me.default)(r)})}async open(){}async get(r){if(!r)throw new Error("Key cannot be null or undefined");return this.cache.get(r)}async set(r,e){this.cache.set(r,e)}async delete(r){this.cache.delete(r)}async clear(){this.cache.clear()}async close(){}},Ame={open(){return Promise.resolve()},get(r){return Promise.resolve(void 0)},set(r,e){return Promise.resolve()},delete(r){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},tg=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this.cache=r||Ame;for(let t of e)this.didResolvers.set(t.methodName,t)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(r,e){let t=Jn.parse(r);if(!t)return{...Di,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...Di,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};let i=await this.cache.get(t.uri);if(i)return i;{let a=await n.resolve(t.uri,e);return a.didResolutionMetadata.error||await this.cache.set(t.uri,a),a}}async dereference(r,e){let t=Jn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(t.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!t.fragment||t.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:s=[]}=n,c=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let d of s)if(c.has(d.id)){l=d;break}for(let d of o)if(c.has(d.id)){l=d;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var rg,fF=G(()=>{"use strict";g();MI();jI();vr();Go();bN();xN();SN();Ho();v9();b9();$9();B9();O9();j9();M9();K9();a2();qR();ea();ur();rg=class r{methodHandlers;didResolver;messageStore;dataStore;resumableTaskStore;stateIndex;tenantGate;eventLog;storageController;resumableTaskManager;_coreProtocols;ownsResolver;constructor(e){this.didResolver=e.didResolver,this.ownsResolver=e.ownsResolver??!1,this.tenantGate=e.tenantGate,this.messageStore=e.messageStore,this.dataStore=e.dataStore,this.resumableTaskStore=e.resumableTaskStore,this.stateIndex=e.stateIndex,this.eventLog=e.eventLog,this.storageController=new $y({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new o2(e.resumableTaskStore,this.storageController),this._coreProtocols=new py,this._coreProtocols.register(new rt);let t={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[ve.Messages+me.Read]:new px(t),[ve.Messages+me.Subscribe]:new yx(t),[ve.Messages+me.Sync]:new wx(t),[ve.Protocols+me.Configure]:new r2(t),[ve.Protocols+me.Query]:new i2(t),[ve.Records+me.Count]:new s2(t),[ve.Records+me.Delete]:new c2(t),[ve.Records+me.Query]:new d2(t),[ve.Records+me.Read]:new l2(t),[ve.Records+me.Subscribe]:new f2(t),[ve.Records+me.Write]:new p2(t)}}static async create(e){e.didResolver||(e.didResolver=new tg({didResolvers:[vo,bo,cb,uF],cache:new mE}),e.ownsResolver=!0),e.tenantGate??=new hy;let t=new r(e);return await t.open(),t}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,t,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(t);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:o}=n,s=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[s].handle({tenant:e,message:t,dataStream:a,subscriptionHandler:o})}async validateTenant(e){let t=await this.tenantGate.isActiveTenant(e);if(!t.isActiveTenant)return{status:{code:401,detail:t.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let t=e?.descriptor?.interface,n=e?.descriptor?.method;if(t===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${t}, method: ${n}`}};try{ye.validateJsonSchema(e)}catch(i){return wt(i,400)}}}});function Tme(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Zn(r,e){return e?Promise.race([r,Tme(e)]):r}var yE=G(()=>{"use strict";g()});import{Level as Ime}from"level";async function Ys(r,e){return new Ime(r,{...e,keyEncoding:"utf8"})}var qa,kf=G(()=>{"use strict";g();yE();qa=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Ys,...e},this.db=t}async open(){switch(await this.createLevelDatabase(),this.db.status){case"open":return;case"opening":return new Promise(e=>{this.db.once("open",e)});case"closing":return new Promise((e,t)=>{let n=()=>{this.db.open().then(e).catch(t)};this.db.once("closed",n)});case"closed":return this.db.open()}}async close(){if(this.db)switch(this.db.status){case"open":return this.db.close();case"opening":return new Promise((e,t)=>{let n=()=>{this.db.close().then(e).catch(t)};this.db.once("open",n)});case"closing":return new Promise(e=>{this.db.once("closed",e)});case"closed":return}}async partition(e){return await this.createLevelDatabase(),new r(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,t){t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal);try{return await Zn(this.db.get(String(e)),t?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,t){return!!await this.get(e,t)}async*keys(e){e?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),e?.signal);for await(let t of this.db.keys())e?.signal?.throwIfAborted(),yield t}async*iterator(e,t){t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal);for await(let n of this.db.iterator(e))t?.signal?.throwIfAborted(),yield n}async put(e,t,n){return n?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),n?.signal),Zn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal),Zn(this.db.del(String(e)),t?.signal)}async isEmpty(e){for await(let t of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,t){return t?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),t?.signal),Zn(this.db.batch(e),t?.signal)}createPartitionOperation(e,t){return{...t,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Zn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Zn(n.db.compactRange?.(...t),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let t=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,t]}get root(){let e=this.db;for(let t=e.db;t&&t!==e;)e=t;return new r(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var _f,gE=G(()=>{"use strict";g();kw();kf();_f=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Ys,...e},this.db=t??new qa({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let t=await this.db.partition(e);return new r({...this.config,location:""},t)}async put(e,t,n){return await this.db.put(String(e),t,n),tr.parse(e.toString())}async get(e,t){return await this.db.get(String(e),t)}async has(e,t){return this.db.has(String(e),t)}async delete(e,t){return this.db.delete(String(e),t)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,t){for await(let n of e)await this.put(n.cid,n.block,t),yield n.cid}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async*getAll(e){let t=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of t)yield{cid:tr.decode(n),block:i}}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async clear(){return this.db.clear()}}});function Dme(r){return r[Symbol.asyncIterator]!=null}function Rme(r){if(Dme(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var pF,hF=G(()=>{g();pF=Rme});var mF,Cme,yF,$me,gF,wF=G(()=>{g();Nf();Xh();mF=0,Cme="identity",yF=Ha,$me=r=>Gf(mF,yF(r)),gF={code:mF,name:Cme,encode:yF,digest:$me}});var vF,Bme,bF,PF=G(()=>{g();km();vF=Tn(la(),1);al();Bme=async(r,e,t,n,i,a,o,s)=>{let c=await o.get(r,s),l=S_(c),d=l,u=t;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),u=`${u}/${f}`;let p=tr.asCID(d[f]);if(p!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}},next:{cid:p,name:f,path:u,toResolve:n}};d=d[f]}else throw(0,vF.default)(new Error(`No property named ${f} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}}}},bF=Bme});function Ome(r,e,t,n){let i=BigInt(r.length),a=BigInt(e+i);return t>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(r=r.subarray(0,Number(n-e))),t>=e&&t<a&&(r=r.subarray(Number(t-e))),r)}var xh,wE=G(()=>{g();xh=Ome});var db,jme,ng,vE=G(()=>{g();db=Tn(la(),1),jme=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),a=BigInt(t);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,db.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,db.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,db.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,db.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},ng=jme});var xF,Mme,Kme,EF,SF=G(()=>{g();xF=Tn(la(),1);Xh();dl();wE();vE();Mme=r=>{async function*e(t={}){let{start:n,end:i}=ng(r.length,t.offset,t.length),a=xh(r,0n,n,i);t.onProgress?.(new Cn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Kme=async(r,e,t,n,i,a,o,s)=>{if(n.length>0)throw(0,xF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Hb(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:Mme(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},EF=Kme});var kF,Nme,Ume,_F,AF=G(()=>{g();kF=Tn(la(),1);dl();wE();vE();Nme=r=>{async function*e(t={}){let{start:n,end:i}=ng(r.length,t.offset,t.length),a=xh(r,0n,n,i);t.onProgress?.(new Cn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Ume=async(r,e,t,n,i,a,o,s)=>{if(n.length>0)throw(0,kF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await o.get(r,s);return{entry:{type:"raw",name:e,path:t,cid:r,content:Nme(c),depth:a,size:BigInt(c.length),node:c}}},_F=Ume});var Lme,qme,TF,zme,IF,DF,RF=G(()=>{g();ua();SA();kA();Lme=async function(r){return(await W1.encode(r)).slice(0,8).reverse()},qme=async(r,e,t)=>{await Promise.all(r.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);e._putObjectAt(i,new Hc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},TF=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),zme=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},IF=async(r,e,t,n,i)=>{if(n==null){let d=Y1({hashFn:Lme});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await qme(r.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=TF(a.pos),s=zme(a);s.length>n.hamtDepth&&(n.lastBucket=s[n.hamtDepth],o=TF(n.lastBucket._posAtParent));let c=r.Links.find(d=>{if(d.Name==null)return!1;let u=d.Name.substring(0,2),f=d.Name.substring(2);return!(u!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let l=await t.get(c.Hash,i);return r=cl(l),IF(r,e,t,n,i)},DF=IF});function Fme(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var bE,o6=G(()=>{g();bE=Fme});function Gme(r){return r[Symbol.asyncIterator]!=null}function Hme(r,e){let t=0;if(Gme(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=bE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){await o&&(yield i);for(let c of n)await e(c,t++)&&(yield c)}();let s=e;return function*(){o===!0&&(yield i);for(let c of n)s(c,t++)&&(yield c)}()}var CF,$F=G(()=>{g();o6();CF=Hme});function Vme(r){return r[Symbol.asyncIterator]!=null}function Wme(r,e){let t=0;if(Vme(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=bE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,t++)}();let s=e;return function*(){yield o;for(let c of n)yield s(c,t++)}()}var ig,PE=G(()=>{g();o6();ig=Wme});function Po(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var xE=G(()=>{g()});async function*Eh(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],o=Po(),s=Po(),c=!1,l,d=!1;i.addEventListener("task-complete",()=>{s.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(a.length===t&&(o=Po(),await o.promise),d)break;let m={done:!1};a.push(m),h().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new EE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new EE("task-complete"))})}c=!0,i.dispatchEvent(new EE("task-complete"))}catch(h){l=h,i.dispatchEvent(new EE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(h=>h.done)}function*f(){for(;a.length>0&&a[0].done;){let h=a[0];if(a.shift(),h.ok)yield h.value;else throw d=!0,o.resolve(),h.err;o.resolve()}}function*p(){for(;u();)for(let h=0;h<a.length;h++)if(a[h].done){let m=a[h];if(a.splice(h,1),h--,m.ok)yield m.value;else throw d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(u()||(s=Po(),await s.promise),l!=null||(n?yield*f():yield*p(),l!=null))throw l;if(c&&a.length===0)break}}var EE,SE=G(()=>{g();xE();EE=globalThis.CustomEvent??Event});var kE,sg,BF=G(()=>{g();kE=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},sg=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new kE(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new kE(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}});function _E(r={}){return Jme(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Jme(r,e){e=e??{};let t=e.onEnd,n=new sg,i,a,o,s=Po(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,v)=>{a=w=>{a=null,n.push(w);try{y(r(n))}catch(x){v(x)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{s.resolve(),s=Po()})}},l=y=>a!=null?a(y):(n.push(y),i),d=y=>(n=new sg,a!=null?a({error:y}):(n.push({error:y}),i)),u=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>o?i:(o=!0,y!=null?d(y):l({done:!0})),p=()=>(n=new sg,f(),{done:!0}),h=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,x;v!=null&&(w=new Promise((_,A)=>{x=()=>{A(new a6)},v.addEventListener("abort",x)}));try{await Promise.race([s.promise,w])}finally{x!=null&&v!=null&&v?.removeEventListener("abort",x)}}},t==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var a6,c6=G(()=>{g();xE();BF();a6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function Zme(r){return r.reason}async function OF(r,e,t){if(e==null)return r;let n=t?.translateError??Zme;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((a,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var jF=G(()=>{g()});function MF(){return new d6}var d6,KF=G(()=>{g();xE();jF();d6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Po(),this.haveNext=Po()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Po(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Po(),await OF(this.readNext.promise,t?.signal,t)}}});function Yme(r){return r[Symbol.asyncIterator]!=null}async function Xme(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Qme(r){let e=new AbortController,t=MF();Xme(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*eye(r){for(let e of r)yield*e}function tye(...r){let e=[];for(let t of r)Yme(t)||e.push(t);return e.length===r.length?eye(e):Qme(r)}var NF,UF=G(()=>{g();KF();NF=tye});function og(r,...e){if(r==null)throw new Error("Empty pipeline");if(l6(r)){let n=r;r=()=>n.source}else if(qF(r)||LF(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&l6(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)l6(t[n])&&(t[n]=nye(t[n]));return rye(...t)}var rye,LF,qF,l6,nye,AE=G(()=>{g();c6();UF();rye=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},LF=r=>r?.[Symbol.asyncIterator]!=null,qF=r=>r?.[Symbol.iterator]!=null,l6=r=>r==null?!1:r.sink!=null&&r.source!=null,nye=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=_E({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,a=r.source;if(LF(a))i=async function*(){yield*a,n.end()};else if(qF(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return NF(n,i())}return r.source}});var iye,zF,FF=G(()=>{g();$F();PE();SE();AE();dl();iye=(r,e,t,n,i,a,o)=>{async function*s(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new Cn("unixfs:exporter:walk:directory",{cid:r})),yield*og(u,f=>ig(f,p=>async()=>{let h=p.Name??"",m=`${n}/${h}`;return(await i(p.Hash,h,m,[],a+1,o,c)).entry}),f=>Eh(f,{ordered:!0}),f=>CF(f,p=>p!=null))}return s},zF=iye});var HF=Ae((Wqe,u6)=>{"use strict";g();var sye=Object.prototype.hasOwnProperty,Xs="~";function lb(){}Object.create&&(lb.prototype=Object.create(null),new lb().__proto__||(Xs=!1));function oye(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function GF(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new oye(t,n||r,i),o=Xs?Xs+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],a]:r._events[o].push(a):(r._events[o]=a,r._eventsCount++),r}function TE(r,e){--r._eventsCount===0?r._events=new lb:delete r._events[e]}function ks(){this._events=new lb,this._eventsCount=0}ks.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)sye.call(t,n)&&e.push(Xs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ks.prototype.listeners=function(e){var t=Xs?Xs+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=new Array(a);i<a;i++)o[i]=n[i].fn;return o};ks.prototype.listenerCount=function(e){var t=Xs?Xs+e:e,n=this._events[t];return n?n.fn?1:n.length:0};ks.prototype.emit=function(e,t,n,i,a,o){var s=Xs?Xs+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var f=c.length,p;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!d)for(p=1,d=new Array(l-1);p<l;p++)d[p-1]=arguments[p];c[u].fn.apply(c[u].context,d)}}return!0};ks.prototype.on=function(e,t,n){return GF(this,e,t,n,!1)};ks.prototype.once=function(e,t,n){return GF(this,e,t,n,!0)};ks.prototype.removeListener=function(e,t,n,i){var a=Xs?Xs+e:e;if(!this._events[a])return this;if(!t)return TE(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&TE(this,a);else{for(var s=0,c=[],l=o.length;s<l;s++)(o[s].fn!==t||i&&!o[s].once||n&&o[s].context!==n)&&c.push(o[s]);c.length?this._events[a]=c.length===1?c[0]:c:TE(this,a)}return this};ks.prototype.removeAllListeners=function(e){var t;return e?(t=Xs?Xs+e:e,this._events[t]&&TE(this,t)):(this._events=new lb,this._eventsCount=0),this};ks.prototype.off=ks.prototype.removeListener;ks.prototype.addListener=ks.prototype.on;ks.prefixed=Xs;ks.EventEmitter=ks;typeof u6<"u"&&(u6.exports=ks)});var f6,VF=G(()=>{g();f6=Tn(HF(),1)});function h6(r,e,t,n){let i,a=new Promise((o,s)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&s(JF(c)),c.addEventListener("abort",()=>{s(JF(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(d){s(d)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new ub(c);typeof r.cancel=="function"&&r.cancel(),s(l)},e),(async()=>{try{o(await r)}catch(c){s(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var ub,p6,WF,JF,ZF=G(()=>{g();ub=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},p6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},WF=r=>globalThis.DOMException===void 0?new p6(r):new DOMException(r),JF=r=>{let e=r.reason===void 0?WF("This operation was aborted."):r.reason;return e instanceof Error?e:WF(e)}});function m6(r,e,t){let n=0,i=r.length;for(;i>0;){let a=Math.trunc(i/2),o=n+a;t(r[o],e)<=0?(n=++o,i-=a+1):i=a}return n}var YF=G(()=>{g()});var Sh,Hl,y6,XF,QF=G(()=>{g();YF();Sh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},y6=class{constructor(){Hl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Sh(this,Hl,"f")[this.size-1].priority>=t.priority){Sh(this,Hl,"f").push(n);return}let i=m6(Sh(this,Hl,"f"),n,(a,o)=>o.priority-a.priority);Sh(this,Hl,"f").splice(i,0,n)}dequeue(){let e=Sh(this,Hl,"f").shift();return e?.run}filter(e){return Sh(this,Hl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Sh(this,Hl,"f").length}};Hl=new WeakMap;XF=y6});var _n,Ye,Yn,pb,hb,Tf,BE,mb,IE,Dc,fb,ta,DE,ra,yb,Af,RE,eG,tG,iG,rG,nG,CE,g6,w6,OE,sG,$E,jE,v6,oG,aG=G(()=>{g();VF();ZF();QF();_n=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Ye=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},jE=class extends Error{},v6=class extends f6.default{constructor(e){var t,n,i,a;if(super(),Yn.add(this),pb.set(this,void 0),hb.set(this,void 0),Tf.set(this,0),BE.set(this,void 0),mb.set(this,void 0),IE.set(this,0),Dc.set(this,void 0),fb.set(this,void 0),ta.set(this,void 0),DE.set(this,void 0),ra.set(this,0),yb.set(this,void 0),Af.set(this,void 0),RE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:XF,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);_n(this,pb,e.carryoverConcurrencyCount,"f"),_n(this,hb,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),_n(this,BE,e.intervalCap,"f"),_n(this,mb,e.interval,"f"),_n(this,ta,new e.queueClass,"f"),_n(this,DE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,_n(this,RE,e.throwOnTimeout===!0,"f"),_n(this,Af,e.autoStart===!1,"f")}get concurrency(){return Ye(this,yb,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);_n(this,yb,e,"f"),Ye(this,Yn,"m",OE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Ye(this,RE,"f"),...t},new Promise((n,i)=>{Ye(this,ta,"f").enqueue(async()=>{var a,o,s;_n(this,ra,(o=Ye(this,ra,"f"),o++,o),"f"),_n(this,Tf,(s=Ye(this,Tf,"f"),s++,s),"f");try{if(!((a=t.signal)===null||a===void 0)&&a.aborted)throw new jE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=h6(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Ye(this,Yn,"m",sG).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof ub&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Ye(this,Yn,"m",iG).call(this)}},t),this.emit("add"),Ye(this,Yn,"m",CE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Ye(this,Af,"f")?(_n(this,Af,!1,"f"),Ye(this,Yn,"m",OE).call(this),this):this}pause(){_n(this,Af,!0,"f")}clear(){_n(this,ta,new(Ye(this,DE,"f")),"f")}async onEmpty(){Ye(this,ta,"f").size!==0&&await Ye(this,Yn,"m",$E).call(this,"empty")}async onSizeLessThan(e){Ye(this,ta,"f").size<e||await Ye(this,Yn,"m",$E).call(this,"next",()=>Ye(this,ta,"f").size<e)}async onIdle(){Ye(this,ra,"f")===0&&Ye(this,ta,"f").size===0||await Ye(this,Yn,"m",$E).call(this,"idle")}get size(){return Ye(this,ta,"f").size}sizeBy(e){return Ye(this,ta,"f").filter(e).length}get pending(){return Ye(this,ra,"f")}get isPaused(){return Ye(this,Af,"f")}};pb=new WeakMap,hb=new WeakMap,Tf=new WeakMap,BE=new WeakMap,mb=new WeakMap,IE=new WeakMap,Dc=new WeakMap,fb=new WeakMap,ta=new WeakMap,DE=new WeakMap,ra=new WeakMap,yb=new WeakMap,Af=new WeakMap,RE=new WeakMap,Yn=new WeakSet,eG=function(){return Ye(this,hb,"f")||Ye(this,Tf,"f")<Ye(this,BE,"f")},tG=function(){return Ye(this,ra,"f")<Ye(this,yb,"f")},iG=function(){var e;_n(this,ra,(e=Ye(this,ra,"f"),e--,e),"f"),Ye(this,Yn,"m",CE).call(this),this.emit("next")},rG=function(){Ye(this,Yn,"m",w6).call(this),Ye(this,Yn,"m",g6).call(this),_n(this,fb,void 0,"f")},nG=function(){let e=Date.now();if(Ye(this,Dc,"f")===void 0){let t=Ye(this,IE,"f")-e;if(t<0)_n(this,Tf,Ye(this,pb,"f")?Ye(this,ra,"f"):0,"f");else return Ye(this,fb,"f")===void 0&&_n(this,fb,setTimeout(()=>{Ye(this,Yn,"m",rG).call(this)},t),"f"),!0}return!1},CE=function(){if(Ye(this,ta,"f").size===0)return Ye(this,Dc,"f")&&clearInterval(Ye(this,Dc,"f")),_n(this,Dc,void 0,"f"),this.emit("empty"),Ye(this,ra,"f")===0&&this.emit("idle"),!1;if(!Ye(this,Af,"f")){let e=!Ye(this,Yn,"a",nG);if(Ye(this,Yn,"a",eG)&&Ye(this,Yn,"a",tG)){let t=Ye(this,ta,"f").dequeue();return t?(this.emit("active"),t(),e&&Ye(this,Yn,"m",g6).call(this),!0):!1}}return!1},g6=function(){Ye(this,hb,"f")||Ye(this,Dc,"f")!==void 0||(_n(this,Dc,setInterval(()=>{Ye(this,Yn,"m",w6).call(this)},Ye(this,mb,"f")),"f"),_n(this,IE,Date.now()+Ye(this,mb,"f"),"f"))},w6=function(){Ye(this,Tf,"f")===0&&Ye(this,ra,"f")===0&&Ye(this,Dc,"f")&&(clearInterval(Ye(this,Dc,"f")),_n(this,Dc,void 0,"f")),_n(this,Tf,Ye(this,pb,"f")?Ye(this,ra,"f"):0,"f"),Ye(this,Yn,"m",OE).call(this)},OE=function(){for(;Ye(this,Yn,"m",CE).call(this););},sG=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new jE("The task was aborted."))},{once:!0})})},$E=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};oG=v6});async function cG(r,e,t,n,i,a,o){if(e instanceof Uint8Array){let l=xh(e,n,i,a);t.push(l);return}if(e.Data==null)throw(0,kh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let s;try{s=Pi.unmarshal(e.Data)}catch(l){throw(0,kh.default)(l,"ERR_NOT_UNIXFS")}if(s.data!=null){let l=s.data,d=xh(l,n,i,a);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==s.blockSizes.length)throw(0,kh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+s.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await og(c,l=>ig(l,d=>async()=>{let u=await r.get(d.link.Hash,o);return{...d,block:u}}),l=>Eh(l,{ordered:!0}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let p;switch(d.Hash.code){case Dw:p=cl(u);break;case bu:p=u;break;default:t.end((0,kh.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new oG({concurrency:1});h.on("error",m=>{t.end(m)}),h.add(async()=>{o.onProgress?.(new Cn("unixfs:exporter:walk:file",{cid:d.Hash})),await cG(r,p,t,f,i,a,o)}),await h.onIdle()}}),n>=a&&t.end()}var kh,aye,b6,dG=G(()=>{g();ua();kh=Tn(la(),1);vu();PE();SE();AE();c6();Kw();aG();dl();wE();vE();aye=(r,e,t,n,i,a,o)=>{async function*s(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=ng(l,c.offset,c.length);if(u===0n)return;let f=0n,p=u-d,h=_E();c.onProgress?.(new Cn("unixfs:exporter:walk:file",{cid:r})),cG(o,e,h,0n,d,u,c).catch(m=>{h.end(m)});for await(let m of h)if(m!=null){if(f+=BigInt(m.byteLength),f>p)throw h.end(),(0,kh.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");f===p&&h.end(),c.onProgress?.(new Cn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:p,fileSize:l})),yield m}if(f<p)throw(0,kh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return s},b6=aye});async function*lG(r,e,t,n,i,a){let o=r.Links,s=og(o,c=>ig(c,l=>async()=>{let d=l.Name!=null?l.Name.substring(2):null;if(d!=null&&d!==""){let u=await t(l.Hash,d,`${e}/${d}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return r=cl(u),a.onProgress?.(new Cn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:lG(r,e,t,n,i,a)}}}),c=>Eh(c,{ordered:!0}));for await(let{entries:c}of s)yield*c}var cye,uG,fG=G(()=>{g();ua();PE();SE();AE();dl();cye=(r,e,t,n,i,a,o)=>{function s(c={}){return c.onProgress?.(new Cn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),lG(e,n,i,a,o,c)}return s};uG=cye});var gb,dye,lye,uye,pG,hG=G(()=>{g();ua();gb=Tn(la(),1);vu();RF();FF();dG();fG();dye=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,lye={raw:b6,file:b6,directory:zF,"hamt-sharded-directory":uG,metadata:(r,e,t,n,i,a,o)=>()=>[],symlink:(r,e,t,n,i,a,o)=>()=>[]},uye=async(r,e,t,n,i,a,o,s)=>{let c=await o.get(r,s),l=cl(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,gb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=Pi.unmarshal(l.Data)}catch(p){throw(0,gb.default)(p,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let p;if(d?.type==="hamt-sharded-directory"?p=await DF(l,n[0],o):p=dye(l,n[0]),p==null)throw(0,gb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),m=`${t}/${h}`;u={cid:p,toResolve:n,name:h??"",path:m}}let f=lye[d.type](r,l,d,t,i,a,o);if(f==null)throw(0,gb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}},pG=uye});var mG,fye,yG,gG,wG=G(()=>{g();km();ua();mG=Tn(la(),1);Kw();wF();PF();SF();AF();hG();fye={[Dw]:pG,[bu]:_F,[mu]:bF,[gF.code]:EF},yG=async(r,e,t,n,i,a,o)=>{let s=fye[r.code];if(s==null)throw(0,mG.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return s(r,e,t,n,yG,i,a,o)},gG=yG});async function*mye(r,e,t={}){let{cid:n,toResolve:i}=hye(r),a=n.toString(),o=a,s=i.length;for(;;){let c=await gG(n,a,o,i,s,e,t);if(c.entry==null&&c.next==null)throw(0,ME.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function vG(r,e,t={}){let n=await pF(mye(r,e,t));if(n==null)throw(0,ME.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var ME,pye,hye,bG=G(()=>{g();ME=Tn(la(),1);hF();al();wG();pye=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),hye=r=>{if(r instanceof Uint8Array)return{cid:tr.decode(r),toResolve:[]};let e=tr.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=pye(r);return{cid:tr.parse(t[0]),toResolve:t.slice(1)}}throw(0,ME.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var P6,KE,If,PG=G(()=>{"use strict";g();gE();kf();yu();bG();TA();P6=new TextEncoder,KE=new TextDecoder,If=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ys,...e},this.blockstore=new _f({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,t,n,i){let a=await this.getRefsPartition(e,t),o=await a.get(n);if(o){await i.cancel();let{dataSize:u}=JSON.parse(KE.decode(o));return{dataSize:u}}let s=await this.getRefcountsPartition(),c=await s.get(n),l=c?JSON.parse(KE.decode(c)):{count:0,dataSize:0},d;if(l.count>0)await i.cancel(),d=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Lw([{content:Wt.asAsyncIterable(i)}],u,{cidVersion:1}),p;for await(p of f);d=Number(p.unixfs?.fileSize()??p.size)}return await a.put(n,P6.encode(JSON.stringify({dataSize:d}))),await s.put(n,P6.encode(JSON.stringify({count:l.count+1,dataSize:d}))),{dataSize:d}}async get(e,t,n){let a=await(await this.getRefsPartition(e,t)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(KE.decode(a)),s=await this.getBlocksPartition(n);if(!await s.has(n))return;let d=(await vG(n,s)).content(),u=new ReadableStream({async pull(f){let p=await d.next();p.done?f.close():f.enqueue(p.value)}});return{dataSize:o,dataStream:u}}async delete(e,t,n){let i=await this.getRefsPartition(e,t);if(!await i.get(n))return;await i.delete(n);let o=await this.getRefcountsPartition(),s=await o.get(n);if(!s)return;let c=JSON.parse(KE.decode(s)),l=c.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,P6.encode(JSON.stringify({count:l,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,t){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(t)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function xG(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function EG(r,e,t,n,i){let a=[];for(let l of t.properties){let d=e[l];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[t.sortProperty];if(o===void 0||Array.isArray(o))return;let s=a.join(NE),c=n(o);return s+NE+c+i+r}function SG(r,e,t){let n=[];for(let i of e.properties){let a=r[i];if(a===void 0||typeof a=="object")return;n.push(t(a))}return n.join(NE)+NE}function kG(r,e,t,n,i,a){let o=EG(t.messageCid,t.indexes,n,i,a);if(o!==void 0)return AG(r,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(t)})}function _G(r,e,t,n,i,a,o){let s=EG(t,n,i,a,o);if(s!==void 0)return AG(r,e,`__compound:${i.name}__`,{type:"del",key:s})}async function AG(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function x6(r,e,t){let n,i=0;for(let a of t){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let s of a.properties){let c=r[s];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function TG(r,e,t,n,i,a,o,s,c){let{sortDirection:l=Rt.Ascending,cursor:d,limit:u}=n,f=SG(t,i,a);if(f===void 0)return s(e,[t],n,c);let p=await xG(r,e,i),h={};if(d!==void 0){let x=a(d.value),_=f+x+o+d.messageCid;l===Rt.Ascending?(h.gt=_,h.lt=f+"\xFF"):(h.lt=_,h.gt=f,h.reverse=!0)}else l===Rt.Ascending?(h.gt=f,h.lt=f+"\xFF"):(h.gt=f,h.lt=f+"\xFF",h.reverse=!0);let m=new Set(i.properties),y={},v=!1;for(let x in t)m.has(x)||(y[x]=t[x],v=!0);let w=[];for await(let[x,_]of p.iterator(h,c)){if(u!==void 0&&w.length===u)break;let A=JSON.parse(_);v&&!nr.matchFilter(A.indexes,y)||w.push(A)}return w}async function IG(r,e,t,n,i,a,o){let s=SG(t,n,i);if(s===void 0)return(await a(e,[t],{sortProperty:n.sortProperty},o)).length;let c=await xG(r,e,n),l=new Set(n.properties),d=!1,u={};for(let h in t)l.has(h)||(u[h]=t[h],d=!0);let f={gt:s,lt:s+"\xFF"},p=0;if(d)for await(let[h,m]of c.iterator(f,o)){let y=JSON.parse(m);nr.matchFilter(y.indexes,u)&&p++}else for await(let[h,m]of c.iterator(f,o))p++;return p}var NE,DG=G(()=>{"use strict";g();yc();ed();NE=""});var RG,_h,E6=G(()=>{"use strict";g();Oi();DA();ed();DG();kf();Et();yc();RG="index",_h=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ys,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async clear(){await this.db.clear()}async put(e,t,n,i){if(hp(n))throw new ie(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:t,indexes:n},o=[];for(let d in n){let u=n[d];if(Array.isArray(u))for(let f of u){let p=this.createPutIndexedItemOperation(e,a,d,f);o.push(p)}else{let f=this.createPutIndexedItemOperation(e,a,d,u);o.push(f)}}for(let d of this._compoundIndexes){let u=kG(this.db,e,a,d,r.encodeValue,r.delimiter);u!==void 0&&o.push(u)}let s=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});o.push(s);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,i)}async delete(e,t,n){let i=[],a=await this.getIndexes(e,t);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(o);for(let l in a){let d=a[l];if(Array.isArray(d))for(let u of d){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,d);i.push(u)}}for(let l of this._compoundIndexes){let d=_G(this.db,e,t,a,l,r.encodeValue,r.delimiter);d!==void 0&&i.push(d)}let s=await Promise.all(i);await(await this.db.partition(e)).batch(s,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:a}=t,o=r.keySegmentJoin(r.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),a=r.getIndexPartitionName(t);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(RG,t)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,t){let n=r.getIndexPartitionName(t);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(RG)}async query(e,t,n,i){if(t.length===1&&!hp(t[0])){let a=x6(t[0],n,this._compoundIndexes);if(a!==void 0)return TG(this.db,e,t[0],n,a,r.encodeValue,r.delimiter,this.queryWithIteratorPaging.bind(this),i)}return r.shouldQueryWithInMemoryPaging(t,n)?this.queryWithInMemoryPaging(e,t,n,i):this.queryWithIteratorPaging(e,t,n,i)}async count(e,t,n,i){if(t.length===1&&!hp(t[0])){let o=x6(t[0],{...n},this._compoundIndexes);if(o!==void 0)return IG(this.db,e,t[0],o,r.encodeValue,this.query.bind(this),i)}return(await this.query(e,t,{...n},i)).length}async queryWithIteratorPaging(e,t,n,i){let{cursor:a,limit:o}=n,s=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let l of this.getIndexIterator(e,s,n,i)){if(o!==void 0&&o===c.length)break;let{indexes:d}=l;nr.matchAnyFilter(d,t)&&c.push(l)}return c}async*getIndexIterator(e,t,n,i){let{sortProperty:a,sortDirection:o=Rt.Ascending,cursor:s}=n,c={gt:t};o===Rt.Descending&&(c.reverse=!0,s!==void 0&&(c.lt=t,delete c.gt));let l=await this.getIndexPartition(e,a);for await(let[d,u]of l.iterator(c,i)){let{indexes:f,messageCid:p}=JSON.parse(u);yield{indexes:f,messageCid:p}}}createStartingKeyFromCursor(e){let{messageCid:t,value:n}=e;return r.keySegmentJoin(r.encodeValue(n),t)}static createCursorFromLastArrayItem(e,t){if(e.length>0)return this.createCursorFromItem(e.at(-1),t)}static createCursorFromItem(e,t){let{messageCid:n,indexes:i}=e,a=i[t];if(a===void 0)throw new ie(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ie(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:a,sortDirection:o=Rt.Ascending,cursor:s,limit:c}=n,l=s?this.createStartingKeyFromCursor(s):void 0,d=new Map;t.length===0&&(t=[{}]);try{for(let h of t)await this.executeSingleFilterQuery(e,h,a,d,i)}catch(h){if(h.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...d.values()].sort((h,m)=>this.sortItems(h,m,a,o)),f=l!==void 0?this.findCursorStartingIndex(u,o,a,l):0;if(f<0)return[];let p=c!==void 0?f+c:void 0;return u.slice(f,p)}async executeSingleFilterQuery(e,t,n,i,a){let o=c=>{for(let l of c)if(!(i.has(l.messageCid)||!nr.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ie(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(hp(t)){let c=await this.getAllItems(e,n);o(c);return}let s=xP.reduceFilter(t);for(let c in s){let l=s[c];if(nr.isEqualFilter(l)){let d=await this.filterExactMatches(e,c,l,a);o(d)}else if(nr.isOneOfFilter(l))for(let d of new Set(l)){let u=await this.filterExactMatches(e,c,d,a);o(u)}else if(nr.isRangeFilter(l)){let d=await this.filterRangeMatches(e,c,l,a);o(d)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[a,o]of n.iterator())i.push(JSON.parse(o));return i}async filterExactMatches(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(n)),o={gt:a},s=await this.getIndexPartition(e,t),c=[];for await(let[l,d]of s.iterator(o,i)){if(!l.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,t,n,i){let a={};for(let c in n){let l=c,d=r.encodeValue(n[l]);l==="lte"?a[l]=d+"\xFF":a[l]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],s=await this.getIndexPartition(e,t);for await(let[c,l]of s.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(c)===r.encodeValue(n.gt)||o.push(JSON.parse(l));return o}sortItems(e,t,n,i){let a=e.indexes[n],o=t.indexes[n],s=r.encodeValue(a)+e.messageCid,c=r.encodeValue(o)+t.messageCid;return i===Rt.Ascending?qw(s,c):qw(c,s)}findCursorStartingIndex(e,t,n,i){let a=c=>{let{messageCid:l,indexes:d}=c,u=d[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===Rt.Ascending?f>i:f<i},o=0,s=e.length;for(;o<s;){let c=o+s>>>1;a(e[c])?s=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,t){let i=await(await this.getIndexesLookupPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[t]=e.split(r.delimiter);return t}static delimiter="\0";static keySegmentJoin(...e){return e.join(r.delimiter)}static encodeNumberValue(e){let t=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?t:0;return a+String(e+o).padStart(i,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,t){for(let n of e)if(!r.isFilterConcise(n,t))return!1;return!0}static isFilterConcise(e,t){return e.recordId!==void 0?!0:t.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function UE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*yye(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],a=tr.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*S6(n,i))}else{let t=tr.asCID(e);t?yield[r.join("/"),t]:yield*S6(e,r)}}function*S6(r,e){if(r==null||r instanceof Uint8Array)return;let t=tr.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let a=[...e,n];yield*yye(a,i)}}function*gye(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!tr.asCID(n)&&(yield*k6(n,i))}else yield*k6(e,r)}function*k6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!tr.asCID(n)&&(yield*gye(i,n))}}function wye(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=tr.asCID(t);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:t}}async function CG({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),i=await t.digest(n),a=tr.create(1,e.code,i);return new LE({value:r,bytes:n,cid:a})}async function $G({bytes:r,codec:e,hasher:t}){if(!r)throw new Error('Missing required argument "bytes"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),i=await t.digest(r),a=tr.create(1,e.code,i);return new LE({value:n,bytes:r,cid:a})}var LE,BG=G(()=>{g();kw();D_();LE=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:UE(),bytes:UE(),value:UE(),asBlock:UE()})}links(){return S6(this.value,[])}tree(){return k6(this.value,[])}get(e="/"){return wye(this.value,e.split("/").filter(Boolean))}}});var bye,Df,OG=G(()=>{"use strict";g();BG();km();gE();ll();al();kf();yE();E6();vr();Yl();ed();bye=[{name:"protocol-protocolPath-messageTimestamp",properties:["protocol","protocolPath"],sortProperty:"messageTimestamp"},{name:"protocol-protocolPath-dateCreated",properties:["protocol","protocolPath"],sortProperty:"dateCreated"},{name:"schema-messageTimestamp",properties:["schema"],sortProperty:"messageTimestamp"},{name:"schema-dateCreated",properties:["schema"],sortProperty:"dateCreated"},{name:"protocol-contextId-messageTimestamp",properties:["protocol","contextId"],sortProperty:"messageTimestamp"}],Df=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Ys,...e},this.blockstore=new _f({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new _h({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??bye})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,t,n){n?.signal?.throwIfAborted();let i=await Zn(this.blockstore.partition(e),n?.signal),a=tr.parse(t),o=await i.get(a,n);return o?(await Zn($G({bytes:o,codec:ol,hasher:Mn}),n?.signal)).value:void 0}async query(e,t,n,i,a){a?.signal?.throwIfAborted();let o=r.buildQueryOptions(n,i),s=await this.index.query(e,t,o,a),c;i?.limit!==void 0&&i.limit<s.length&&(s.splice(-1),c=_h.createCursorFromLastArrayItem(s,o.sortProperty));let l=[];for(let d=0;d<s.length;d++){let{messageCid:u}=s[d],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:c}}async count(e,t,n,i){i?.signal?.throwIfAborted();let a=r.buildQueryOptions(n);return this.index.count(e,t,a,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:a,datePublished:o,messageTimestamp:s}=e,c=Rt.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":o!==void 0?l="datePublished":s!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(c=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Zn(this.blockstore.partition(e),n?.signal),a=tr.parse(t);await i.delete(a,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let a=await Zn(this.blockstore.partition(e),i?.signal),o=await Zn(CG({value:t,codec:ol,hasher:Mn}),i?.signal),s=mr.parseCid(await ye.getCid(t));await a.put(s,o.bytes,i);let c=s.toString();await this.index.put(e,c,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var Rf,jG=G(()=>{"use strict";g();ll();kf();Rf=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ys,...e},this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async register(e,t){let n=await mr.computeCid(e),i={id:n,timeout:Date.now()+t*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let t=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),t.push(a)),t.length>=e)break}return t}async read(e){let t=await this.db.get(e);if(t)return JSON.parse(t)}async extend(e,t){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+t*1e3,await this.db.put(i.id,JSON.stringify(i))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}}});function MG(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}var KG=G(()=>{g()});var NG,Cf,UG=G(()=>{"use strict";g();KG();yc();Et();NG="events",Cf=class r{emitter=MG();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;epoch;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,this.epoch=crypto.randomUUID(),e.errorHandler&&(this.errorHandler=e.errorHandler)}async getStreamId(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(n);return Array.from(i.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,t,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(t),messageCid:n}}async validateCursor(e,t){let n=await this.getStreamId(e),i;if(t.streamId!==n)i="stream_mismatch";else if(t.epoch!==this.epoch)i="epoch_mismatch";else{let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let l=c.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}let a=await this.getReplayBounds(e),o={requested:t,oldestAvailable:a?.oldest??t,latestAvailable:a?.latest??t,reason:i},s=new ie(re.EventLogProgressGap,`progress token gap: ${i}`);throw s.gapInfo=o,s}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,t,n,i){if(!this.isOpen){this.errorHandler(new ie(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let s=this.tenantLogs.get(e);if(s===void 0&&(s=new Map,this.tenantLogs.set(e,s)),s.set(o,{event:t,indexes:n,messageCid:i}),s.size>this.maxEventsPerTenant){let l=s.size-this.maxEventsPerTenant,d=0;for(let u of s.keys()){if(d>=l)break;s.delete(u),d++}}let c=`${e}_${NG}`;return this.emitter.emit(c,{tenant:e,event:t,indexes:n,seq:o,messageCid:i}),this.buildToken(e,o,i)}async read(e,t={}){let{cursor:n,limit:i,filters:a}=t;n!==void 0&&await this.validateCursor(e,n);let o=n!==void 0?r.parsePosition(n.position):void 0,s=this.tenantLogs.get(e);if(s===void 0||s.size===0)return{events:[],cursor:n};let c=[],l=i??Number.MAX_SAFE_INTEGER;for(let[d,u]of s)if(!(o!==void 0&&d<=o)&&!(a!==void 0&&a.length>0&&!nr.matchAnyFilter(u.indexes,a))&&(c.push({seq:d,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),c.length>=l))break;if(c.length>0){let d=c[c.length-1],u=await this.buildToken(e,d.seq,d.messageCid);return{events:c,cursor:u}}return{events:c,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ie(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ie?t:new ie(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let a=`${e}_${NG}`,{cursor:o,filters:s}=i??{},c=async d=>this.buildToken(e,d.seq,d.messageCid);if(o!==void 0){await this.validateCursor(e,o);let d=r.parsePosition(o.position),u=[],f=!1,p=v=>{s!==void 0&&s.length>0&&!nr.matchAnyFilter(v.indexes,s)||(f?c(v).then(w=>{n({type:"event",cursor:w,event:v.event})}):u.push({event:v.event,seq:v.seq,messageCid:v.messageCid}))};this.emitter.on(a,p);let h=await this.read(e,{cursor:o,filters:s}),m=h.cursor??o,y=h.cursor!==void 0?r.parsePosition(h.cursor.position):d;for(let v of h.events){let w=await this.buildToken(e,v.seq,v.messageCid??"");n({type:"event",cursor:w,event:v.event})}f=!0;for(let v of u)if(v.seq>y){let w=await this.buildToken(e,v.seq,v.messageCid);n({type:"event",cursor:w,event:v.event})}return n({type:"eose",cursor:m}),{id:t,close:async()=>{this.emitter.off(a,p)}}}let l=d=>{s!==void 0&&s.length>0&&!nr.matchAnyFilter(d.indexes,s)||c(d).then(u=>{n({type:"event",cursor:u,event:d.event})})};return this.emitter.on(a,l),{id:t,close:async()=>{this.emitter.off(a,l)}}}async getReplayBounds(e){let t=this.tenantLogs.get(e);if(t===void 0||t.size===0)return;let n=[...t.keys()],i=n[0],a=n[n.length-1],o=t.get(i),s=t.get(a),c=await this.buildToken(e,i,o.messageCid),l=await this.buildToken(e,a,s.messageCid);return{oldest:c,latest:l}}async trim(e,t){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof t=="number")for(let i of n.keys())if(i<t)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var ag,_6=G(()=>{"use strict";g();Hu();ag=class{db;nodesPartition;metaPartition;initialized=!1;constructor(e){this.db=e}async open(){this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta"),this.initialized=!0}async close(){this.initialized=!1}async clear(){await this.db.clear(),this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta")}async getNode(e){this.ensureInitialized();let t=an(e),n=await this.nodesPartition.get(t);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,t){this.ensureInitialized();let n=an(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=an(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return Gu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",an(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:an(e.leftHash),rightHash:an(e.rightHash)}:{type:"leaf",keyHash:an(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Gu(e.leftHash),rightHash:Gu(e.rightHash)}:{type:"leaf",keyHash:Gu(e.keyHash),valueCid:e.valueCid}}}});var cg,A6=G(()=>{"use strict";g();Hu();cg=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Al()}async close(){await this.store.close()}async clear(){await this.store.clear()}async getRoot(){let e=await this.store.getRoot();return e===void 0?this.defaultHashes[0]:e}async insert(e){let t=await Fu(e),n=await yy(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),o=await this.insertAtNode(a,t,n,i,0);return await this.store.setRoot(o),o}async delete(e){let t=await Fu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,t,0);return await this.store.setRoot(i),i}async has(e){let t=await Fu(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Fu(e),n=await this.getRoot();return this.generateProof(n,t,0)}async getSubtreeHash(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(on(t,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(t);if(i===void 0||i.type==="leaf")return i!==void 0&&i.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(on(t,this.defaultHashes[n]))return[];let i=await this.store.getNode(t);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(on(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(t,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,t,n,i,a){if(a>=ys||on(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return on(o.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,i,n,a);let s=o,c=uo(t,a),l,d;c?(l=s.leftHash,d=await this.insertAtNode(s.rightHash,t,n,i,a+1)):(l=await this.insertAtNode(s.leftHash,t,n,i,a+1),d=s.rightHash);let u=await Tl(l,d);if(!on(u,e)){let f={type:"internal",leftHash:l,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,a){let o=a;for(;o<ys&&uo(e.keyHash,o)===uo(n.keyHash,o);)o++;if(o>=ys)return i;let s=uo(e.keyHash,o),c,l;s?(c=i,l=t):(c=t,l=i);let d=await Tl(c,l);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:l});for(let u=o-1;u>=a;u--){let f=uo(e.keyHash,u),p=this.defaultHashes[u+1],h,m;f?(h=p,m=d):(h=d,m=p),d=await Tl(h,m),await this.store.putNode(d,{type:"internal",leftHash:h,rightHash:m})}return d}async deleteAtNode(e,t,n){if(n>=ys)return this.defaultHashes[ys];if(on(e,this.defaultHashes[n]))return e;let i=await this.store.getNode(e);if(i===void 0)return this.defaultHashes[n];if(i.type==="leaf")return on(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,o=uo(t,n),s,c;if(o?(s=a.leftHash,c=await this.deleteAtNode(a.rightHash,t,n+1)):(s=await this.deleteAtNode(a.leftHash,t,n+1),c=a.rightHash),on(s,this.defaultHashes[n+1])&&on(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=on(s,this.defaultHashes[n+1]),d=on(c,this.defaultHashes[n+1]);if(l||d){let f=l?c:s,p=await this.store.getNode(f);if(p!==void 0&&p.type==="leaf")return await this.store.deleteNode(e),f}let u=await Tl(s,c);if(!on(u,e)){let f={type:"internal",leftHash:s,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=ys||on(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return on(i.keyHash,t);let a=i;return uo(t,n)?this.existsAtNode(a.rightHash,t,n+1):this.existsAtNode(a.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=ys)return{siblings:[],leafNode:void 0,depth:n};if(on(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let i=await this.store.getNode(e);if(i===void 0)return{siblings:[],leafNode:void 0,depth:n};if(i.type==="leaf")return{siblings:[],leafNode:i,depth:n};let a=i,o=uo(t,n),s,c;o?(s=a.rightHash,c=a.leftHash):(s=a.leftHash,c=a.rightHash);let l=await this.generateProof(s,t,n+1);return l.siblings.unshift(c),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(uo(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await yy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(uo(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=ys||on(e,this.defaultHashes[t]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let i=n,a=await this.collectLeaves(i.leftHash,t+1),o=await this.collectLeaves(i.rightHash,t+1);return[...a,...o]}async diffAtNode(e,t,n,i,a,o,s){if(on(e,t)||n>=ys)return;let c=on(e,this.defaultHashes[n]),l=on(t,this.defaultHashes[n]);if(c&&!l){let f=await a.collectLeaves(t,n);s.push(...f);return}if(!c&&l){let f=await i.collectLeaves(e,n);o.push(...f);return}let d=await i.store.getNode(e),u=await a.store.getNode(t);if(d?.type==="leaf"&&u?.type==="leaf"){on(d.keyHash,u.keyHash)?d.valueCid!==u.valueCid&&(o.push(d.valueCid),s.push(u.valueCid)):(o.push(d.valueCid),s.push(u.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(t,n),p=d.valueCid;new Set(f).has(p)||o.push(p);for(let m of f)m!==p&&s.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),p=u.valueCid;new Set(f).has(p)||s.push(p);for(let m of f)m!==p&&o.push(m);return}if(d?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(d.leftHash,u.leftHash,n+1,i,a,o,s),await this.diffAtNode(d.rightHash,u.rightHash,n+1,i,a,o,s);return}if(d===void 0){let f=await a.collectLeaves(t,n);s.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);o.push(...f)}}}});var $f,LG=G(()=>{"use strict";g();Hu();_6();A6();kf();$f=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Ys,...e}}async open(){this.db=new qa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Al()}async close(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.close()}async clear(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.clear()}async insert(e,t,n){await(await this.getGlobalTree(e)).insert(t);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let a=await this.getStoredIndexes(e,i);if(await n.delete(i),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(i)}await this.deleteStoredIndexes(e,i)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,t){return(await this.getProtocolTree(e,t)).getRoot()}async getSubtreeHash(e,t){return(await this.getGlobalTree(e)).getSubtreeHash(t)}async getProtocolSubtreeHash(e,t,n){return(await this.getProtocolTree(e,t)).getSubtreeHash(n)}async getLeaves(e,t){return(await this.getGlobalTree(e)).getLeaves(t)}async getProtocolLeaves(e,t,n){return(await this.getProtocolTree(e,t)).getLeaves(n)}getGlobalTree(e){let t=this.globalTrees.get(e);return t!==void 0||(t=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,t)),t}getProtocolTree(e,t){let n=`${e}\0${t}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",t]),this.protocolTrees.set(n,i)),i}async createTree(e,t){let n=e;for(let o of t)n=await n.partition(o);let i=new ag(n),a=new cg(i);return await a.initialize(),a}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(t,JSON.stringify(a))}async getStoredIndexes(e,t){let i=await(await this.getMetaPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,t){await(await this.getMetaPartition(e)).delete(t)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var qE,qG=G(()=>{"use strict";g();Hu();qE=class{nodes=new Map;root;async open(){}async close(){}async clear(){this.nodes.clear(),this.root=void 0}async getNode(e){return this.nodes.get(an(e))}async putNode(e,t){this.nodes.set(an(e),t)}async deleteNode(e){this.nodes.delete(an(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var Pye,zE,zG=G(()=>{"use strict";g();km();al();yu();ea();CS();In();Kc();fx();mx();Ho();u1();t2();n2();ti();dx();b0();lx();u2();Gs();Oi();Vb();Yl();ms();Pn();lv();ur();Um();Pye={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},zE=class r{static async generatePersona(e){let t=e?.did;t||(t=`did:example:${r.randomString(32)}`);let n=r.randomString(10),i=e?.keyId??`${t}#${n}`,a=e?.keyPair??await Va.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await At.generateKey();o={publicJwk:await At.getPublicKey({key:c}),privateJwk:c}}return{did:t,keyId:i,keyPair:a,encryptionKeyPair:o,signer:new rl({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await _a.create({definition:Pye,signer:ut.createSigner(t)}),i=await e.processMessage(t.did,n.message);if(i.status.code!==202)throw new Error(`Failed to install default test protocol: ${i.status.code} ${i.status.detail}`)}static async generateProtocolsConfigure(e){let t=e?.author??await r.generatePersona(),n=e?.protocolDefinition;if(!n){let s="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[s]={schema:"test-object",dataFormats:["text/plain"]},n.structure[s]={}}let i=ut.createSigner(t),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await _a.create(a);return{author:t,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};rr(i);let a=await Aa.create(i);return{author:t,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??kt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:ve.Messages,method:me.Read},o=ut.createSigner(t),s=n.did,c={signer:o,grantedTo:s,dateExpires:i,scope:a,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await rt.createGrant(c);return{dataStream:Wt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i=ut.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,s,c;a===void 0&&o===void 0&&(s=e?.data??r.randomBytes(32),c=Wt.fromBytes(s));let l={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${r.randomString(20)}`,tags:e?.tags,recordId:e?.recordId,parentContextId:e?.parentContextId,published:e?.published,dataFormat:e?.dataFormat??"application/json",dateCreated:e?.dateCreated,messageTimestamp:e?.messageTimestamp,datePublished:e?.datePublished,data:s,dataCid:a,dataSize:o,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await _t.create(l),u=d.message;return{author:t,message:u,dataCid:a,dataSize:o,dataBytes:s,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:a,protocolPath:o,protocolParentContextId:s,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:l}=e,d=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:p}=await Ei.aeadEncrypt(di.A256GCM,u,d,t),h=o.split("/"),m=h[h.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:a.protocol,protocolPath:o,parentContextId:s,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),x={initializationVector:d,key:u,authenticationTag:p,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let $ of h)_=_[$];let A=_.$encryption?.publicKeyJwk,N={publicKeyId:_.$encryption?.rootKeyId,publicKey:A,derivationScheme:Pt.ProtocolPath};x.keyEncryptionInputs.push(N)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(s===void 0){let A={rootKeyId:n.keyId,derivationScheme:Pt.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await _t.getEntryId(n.did,y.descriptor),N=Ie.constructKeyDerivationPathUsingProtocolContextScheme(D),$=await Ni.derivePublicKey(A,N);_={publicKeyId:n.keyId,publicKey:$,derivationScheme:Pt.ProtocolContext}}else{if(c===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:l,derivationScheme:Pt.ProtocolContext}}x.keyEncryptionInputs.push(_)}return await w.encryptSymmetricEncryptionKey(x),await w.sign({signer:ut.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:x}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=kt.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),a=e.datePublished??(i?n:void 0),o=e.data??r.randomBytes(32),s=Wt.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ut.createSigner(e.author)},l=await _t.createFrom(c);return{message:l.message,recordsWrite:l,dataBytes:o,dataStream:s}}static async generateRecordsQuery(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};rr(a);let s=(await ba.create(a)).message;return{author:t,message:s}}static async generateRecordsSubscribe(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};rr(a);let s=(await Ia.create(a)).message;return{author:t,message:s}}static async generateRecordsCount(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ut.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};rr(a);let s=(await hd.create(a)).message;return{author:t,message:s}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await Ta.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ut.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=ut.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};rr(i);let a=await gd.create(i),o=a.message;return{author:t,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:ut.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await yd.create(i);return{author:t,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Kg.generateKeyPair(),t=await Kg.sign(r.randomBytes(32),e.privateJwk);return De.bytesToBase64Url(t)}static randomString(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=t.charAt(Math.floor(Math.random()*t.length));return n}static randomBytes(e){let t=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return t}static async randomCborSha256Cid(){let e=r.randomBytes(32),t=await Mn.digest(e);return(await tr.createV1(mu,t)).toString()}static randomInt(e,t){return Math.floor(Math.random()*(t-e)+e)}static randomTimestamp(e){let{year:t,month:n,day:i,hour:a,minute:o,second:s,millisecond:c,microsecond:l}=e||{};return kt.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:s||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:l||this.randomInt(0,1e3)})}static createDidResolutionResult(e){return{didResolutionMetadata:{},didDocument:{id:e.did,verificationMethod:[{controller:e.did,id:e.keyId,type:"JsonWebKey2020",publicKeyJwk:e.keyPair.publicJwk}]},didDocumentMetadata:{}}}static async generateDidKeyPersona(){let e=await cb.create(),t=await cb.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),a={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},o=await At.generateKey(),c={publicJwk:await At.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new rl({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var FE,FG=G(()=>{"use strict";g();ms();FE=class r{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,t=r.pollRetrySleep,n=r.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await kt.sleep(t)}}}});var GG={};cr(GG,{AllowAllTenantGate:()=>hy,BlockstoreLevel:()=>_f,Cid:()=>mr,ContentEncryptionAlgorithm:()=>di,CoreProtocolRegistry:()=>py,DataStoreLevel:()=>If,DataStream:()=>Wt,DateSort:()=>Ut,Dwn:()=>rg,DwnConstant:()=>lo,DwnError:()=>ie,DwnErrorCode:()=>re,DwnInterfaceName:()=>ve,DwnMethodName:()=>me,Encoder:()=>De,Encryption:()=>Ei,EventEmitterEventLog:()=>Cf,HdKey:()=>Ni,IndexLevel:()=>_h,Jws:()=>ut,KeyAgreementAlgorithm:()=>dv,KeyDerivationScheme:()=>Pt,LevelWrapper:()=>qa,Message:()=>ye,MessageStoreLevel:()=>Df,MessagesRead:()=>yd,MessagesSubscribe:()=>gd,MessagesSync:()=>Vu,PERMISSIONS_REVOCATION_PATH:()=>EP,PermissionConditionPublication:()=>Lm,PermissionGrant:()=>Ir,PermissionRequest:()=>md,PermissionsProtocol:()=>rt,Poller:()=>FE,PrivateKeySigner:()=>rl,ProtocolRecordLimitStrategy:()=>Wl,Protocols:()=>xd,ProtocolsConfigure:()=>_a,ProtocolsQuery:()=>Aa,Records:()=>Ie,RecordsCount:()=>hd,RecordsDelete:()=>Ta,RecordsQuery:()=>ba,RecordsRead:()=>Sd,RecordsSubscribe:()=>Ia,RecordsWrite:()=>_t,ResumableTaskStoreLevel:()=>Rf,SMTStoreLevel:()=>ag,SMTStoreMemory:()=>qE,SMT_DEPTH:()=>ys,Secp256k1:()=>Va,Secp256r1:()=>tl,SortDirection:()=>Rt,SparseMerkleTree:()=>cg,StateIndexLevel:()=>$f,TestDataGenerator:()=>zE,Time:()=>kt,ZERO_HASH:()=>gx,authenticate:()=>yn,createLevelDatabase:()=>Ys,executeUnlessAborted:()=>Zn,getBit:()=>uo,getDefaultHashes:()=>NI,getRuleSetAtPath:()=>Ed,hashChildren:()=>Tl,hashEquals:()=>on,hashKey:()=>Fu,hashLeaf:()=>yy,hashToHex:()=>an,hexToHash:()=>Gu,initDefaultHashes:()=>Al,isCrossProtocolRef:()=>nf,parseCrossProtocolRef:()=>Ws});var Xn=G(()=>{"use strict";g();Bg();Fo();jI();bT();MI();ll();dx();lx();yu();Um();fF();my();Et();ur();In();mx();lv();Gs();yE();Kc();vr();fx();UI();dc();KI();Ho();u1();Xp();t2();n2();ti();b0();LR();u2();Vb();Ok();ed();ms();PT();mp();gE();PG();E6();kf();OG();jG();UG();LG();A6();_6();qG();Hu();zG();FG()});var JE=Ae((EHe,XG)=>{g();var ug=1e3,fg=ug*60,pg=fg*60,Ih=pg*24,Rye=Ih*7,Cye=Ih*365.25;XG.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return $ye(r);if(t==="number"&&isFinite(r))return e.long?Oye(r):Bye(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function $ye(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Cye;case"weeks":case"week":case"w":return t*Rye;case"days":case"day":case"d":return t*Ih;case"hours":case"hour":case"hrs":case"hr":case"h":return t*pg;case"minutes":case"minute":case"mins":case"min":case"m":return t*fg;case"seconds":case"second":case"secs":case"sec":case"s":return t*ug;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Bye(r){var e=Math.abs(r);return e>=Ih?Math.round(r/Ih)+"d":e>=pg?Math.round(r/pg)+"h":e>=fg?Math.round(r/fg)+"m":e>=ug?Math.round(r/ug)+"s":r+"ms"}function Oye(r){var e=Math.abs(r);return e>=Ih?WE(r,e,Ih,"day"):e>=pg?WE(r,e,pg,"hour"):e>=fg?WE(r,e,fg,"minute"):e>=ug?WE(r,e,ug,"second"):r+" ms"}function WE(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();Xn();Xn();var Re=(d=>(d[d.MessagesRead=ve.Messages+me.Read]="MessagesRead",d[d.MessagesSubscribe=ve.Messages+me.Subscribe]="MessagesSubscribe",d[d.MessagesSync=ve.Messages+me.Sync]="MessagesSync",d[d.ProtocolsConfigure=ve.Protocols+me.Configure]="ProtocolsConfigure",d[d.ProtocolsQuery=ve.Protocols+me.Query]="ProtocolsQuery",d[d.RecordsDelete=ve.Records+me.Delete]="RecordsDelete",d[d.RecordsQuery=ve.Records+me.Query]="RecordsQuery",d[d.RecordsRead=ve.Records+me.Read]="RecordsRead",d[d.RecordsSubscribe=ve.Records+me.Subscribe]="RecordsSubscribe",d[d.RecordsWrite=ve.Records+me.Write]="RecordsWrite",d))(Re||{}),Ah={[Re.MessagesRead]:yd,[Re.MessagesSubscribe]:gd,[Re.MessagesSync]:Vu,[Re.ProtocolsConfigure]:_a,[Re.ProtocolsQuery]:Aa,[Re.RecordsDelete]:Ta,[Re.RecordsQuery]:ba,[Re.RecordsRead]:Sd,[Re.RecordsSubscribe]:Ia,[Re.RecordsWrite]:_t};g();async function T6(r){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort()),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort()));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(i),o="";for(let s of a)o+=String.fromCharCode(s);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var I6=100;g();var D6="^",as=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${D6}${t}${D6}${n}`}async getOrCreateLink(e){let t=await T6(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let a=await this.sublevel.get(n),o=JSON.parse(a);return delete o.push,o.connectivity="unknown",o}catch(a){if(a.code!=="LEVEL_NOT_FOUND")throw a}let i={tenantDid:e.tenantDid,remoteEndpoint:e.remoteEndpoint,scopeId:t,scope:e.scope,status:"initializing",connectivity:"unknown",pull:{},needsReconcile:!1,delegateDid:e.delegateDid,protocol:e.protocol};return await this.sublevel.put(n,JSON.stringify(i)),i}async saveLink(e){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),await this.sublevel.put(t,JSON.stringify(e))}async deleteLink(e,t,n){let i=r.buildKey(e,t,n);await this.sublevel.del(i)}async getLinksForTenant(e){let t=`${e}${D6}`,n=[];for await(let[i,a]of this.sublevel.iterator())i.startsWith(t)&&n.push(JSON.parse(a));return n}async getAllLinks(){let e=[];for await(let[,t]of this.sublevel.iterator())e.push(JSON.parse(t));return e}async setStatus(e,t){e.status=t,await this.saveLink(e)}static comparePosition(e,t){let n=BigInt(e.position)-BigInt(t.position);return n<BigInt(0)?-1:n>BigInt(0)?1:0}static validateTokenDomain(e,t){return e.contiguousAppliedToken===void 0?!0:t.streamId===e.contiguousAppliedToken.streamId&&t.epoch===e.contiguousAppliedToken.epoch}static setReceivedToken(e,t){(e.receivedToken===void 0||r.comparePosition(t,e.receivedToken)>0)&&(e.receivedToken=t)}static commitContiguousToken(e,t){e.contiguousAppliedToken=t}static resetCheckpoint(e,t){e.contiguousAppliedToken=t,e.receivedToken=t}async markNeedsReconcile(e,t){e.needsReconcile||(e.needsReconcile=!0,await this.saveLink(e))}async clearNeedsReconcile(e){e.needsReconcile&&(e.needsReconcile=!1,await this.saveLink(e))}};g();var R6=(p=>(p.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",p.InitialWriteMissing="ClosureInitialWriteMissing",p.ParentChainMissing="ClosureParentChainMissing",p.ContextChainMissing="ClosureContextChainMissing",p.GrantMissing="ClosureGrantMissing",p.GrantNotYetActive="ClosureGrantNotYetActive",p.GrantExpired="ClosureGrantExpired",p.GrantRevocationMissing="ClosureGrantRevocationMissing",p.VisibilityFloorMissing="ClosureVisibilityFloorMissing",p.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",p.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",p.DependencyForbidden="ClosureDependencyForbidden",p.DepthExceeded="ClosureDepthExceeded",p))(R6||{});function wb(r,e,t){return{tenantDid:r,protocolCache:new Map,grantCache:new Map,satisfiedDeps:new Set,missingDeps:new Set,maxDepth:e??32,isDelegateSession:t?.isDelegateSession}}function HG(r,e){let t=e.descriptor;if(t.interface==="Protocols"&&t.method==="Configure"){let n=t.definition?t.definition.protocol:void 0;n&&r.protocolCache.delete(n)}if(t.protocol==="https://identity.foundation/dwn/permissions"){let n=e.recordId,i=t.protocolPath;if(i==="grant"&&n&&(r.grantCache.delete(n),r.satisfiedDeps.delete(`permissionGrant:grantId:${n}`),r.missingDeps.delete(`permissionGrant:grantId:${n}`)),i==="grant/revocation"){let a=t.parentId;a&&(r.grantCache.delete(`revocation:${a}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${a}`),r.missingDeps.delete(`grantRevocation:grantId:${a}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${a}`),r.missingDeps.delete(`permissionGrant:grantId:${a}`))}}if(t.interface==="Records"){let n=e.recordId,i=t.protocol,a=t.protocolPath;if(n){let o=s=>{let c=s.indexOf(n);if(c===-1)return!1;let l=c>0?s[c-1]:":",d=c+n.length<s.length?s[c+n.length]:"|",u=l===":"||l==="|",f=d==="|"||d===void 0;return u&&(c+n.length===s.length||f)};for(let s of r.satisfiedDeps)o(s)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)o(s)&&r.missingDeps.delete(s)}if(i&&a){let o=`filter:${i}|${a}`;for(let s of r.satisfiedDeps)s.includes(o)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)s.includes(o)&&r.missingDeps.delete(s)}if(i==="https://identity.foundation/protocols/key-delivery"){let s=e.descriptor?.tags?.protocol;if(s){let c=`messageCid:${s}|`;for(let l of r.satisfiedDeps)l.includes(c)&&r.satisfiedDeps.delete(l);for(let l of r.missingDeps)l.includes(c)&&r.missingDeps.delete(l)}}else if(i){let o=`messageCid:${i}|`;for(let s of r.satisfiedDeps)s.includes(o)&&r.satisfiedDeps.delete(s);for(let s of r.missingDeps)s.includes(o)&&r.missingDeps.delete(s)}}}g();Xn();g();function VG(r,e){let t=e.split("/"),n=r.structure;for(let i of t)if(n=n[i],!n)return;return n}function zGe(r){return r.split("/")[0]||r}function Th(r,e){let t=VG(r,e);if(!t)return!1;function n(i){for(let a in i)if(!a.startsWith("$")){let o=i[a];if(o.$role===!0||n(o))return!0}return!1}return n(t)?!0:C6(void 0,e,r)}function C6(r,e,t){let n=t.structure;function i(a){if(a.$actions){for(let o of a.$actions)if(o.who&&o.who!=="anyone"&&(r===void 0||o.who===r)&&o.of===e&&o.can?.includes("read"))return!0}for(let o in a)if(!o.startsWith("$")&&i(a[o]))return!0;return!1}return i(n)}function $6({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let a=new Set,o=VG(r,e);return o&&(o.$role===!0&&t&&a.add(t),t&&t!==n&&C6("recipient",e,r)&&a.add(t),i&&i!==n&&C6("author",e,r)&&a.add(i),a.delete(n)),a}function xye(r){let t=r.descriptor.protocol;return t?t===rt.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function Eye(r){let e=r.descriptor,t=[];if(e.interface!=="Records")return[];let n=r.recordId,i=e.parentId;i&&t.push({dependencyClass:2,label:"parentRecord",identifier:i,identifierType:"recordId"});let a=r.contextId;if(a&&n&&a!==n){let o=a.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:o,identifierType:"recordId"})}if(n&&e.method==="Write"){let o=e.dateCreated,s=e.messageTimestamp;o&&s&&o!==s&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"})}return n&&e.method==="Delete"&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"}),t}function Sye(r){let e=[],t=r.authorization;if(!t)return[];let n=t.signature?.payload;if(n)try{let i=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));i.permissionGrantId&&(e.push({dependencyClass:3,label:"permissionGrant",identifier:i.permissionGrantId,identifierType:"grantId"}),e.push({dependencyClass:3,label:"grantRevocation",identifier:i.permissionGrantId,identifierType:"grantId"}))}catch{}return e}function kye(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let a of t){if(!Object.hasOwn(n,a))return;i=n[a],n=i}return i}function _ye(r,e,t){let n=r.descriptor;if(n.interface!=="Records")return[];let i=n.protocolPath;if(!i)return[];let a=[];if(kye(e?.structure,i)?.$encryption){let d=i.split("/").pop();if(e?.types?.[d??""]?.encryptionRequired===!0){a.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:n.protocol,identifierType:"protocol"});let f=r.contextId,p=!1;if(f){let m=i.split("/")[0];p=Th(e,m)}if(t&&!p||a.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"}),p&&f){let m=f.split("/")[0];a.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${n.protocol}|${m}`,identifierType:"messageCid"})}}}let s=i.split("/")[0],c=e?.structure?.[s];if(c?.$ref){let d=c.$ref.indexOf(":");if(d>0){let u=c.$ref.substring(0,d),p=e?.uses?.[u];if(p){a.push({dependencyClass:6,label:"crossProtocolConfig",identifier:p,identifierType:"protocol"});let h=i.split("/"),m=n.parentId;h.length===2&&m&&a.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${p}|${m}`,identifierType:"recordId"})}}}let l=r.authorization;if(l&&e?.uses){let d=l.signature?.payload;if(d)try{let f=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).protocolRole;if(f&&f.includes(":")){let p=f.indexOf(":"),h=f.substring(0,p),m=e.uses[h];if(m){a.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:m,identifierType:"protocol"});let y=f.substring(p+1),v=ye.getAuthor(r),w=r.contextId;if(v){let x={interface:"Records",method:"Write",protocol:m,protocolPath:y,recipient:v,isLatestBaseState:!0};if(w){let A=y.split("/").length-1;if(A>0){let N=w.split("/").slice(0,A).join("/");N&&(x.contextId={gte:N,lt:N+"\uFFFF"})}}let _=x.contextId?JSON.stringify(x.contextId):"no-context";a.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${m}|${y}|${v}|${_}`,identifierType:"filter",filter:x})}}}}catch{}}return a}async function GE(r,e,t,n){if(t.kind==="full")return{complete:!0,rootMessageCid:await ye.getCid(r),edges:[],depth:0};let i=await ye.getCid(r),a=[],o=new Set,s=0,c=[r];for(o.add(i);c.length>0;){if(s>=n.maxDepth)return{complete:!1,rootMessageCid:i,edges:a,failure:{code:"ClosureDepthExceeded",edge:{dependencyClass:1,label:"depth",identifier:String(s),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:s};let l=c.length;for(let d=0;d<l;d++){let u=c.shift(),f=[...xye(u),...Eye(u),...Sye(u)],p=await WG(f,a,e,n,o,c,i,s);if(p)return p;let m=u.descriptor.protocol;if(m){let v=n.protocolCache.get(m)?.descriptor?.definition;if(v){let w=_ye(u,v,n.isDelegateSession),x=await WG(w,a,e,n,o,c,i,s);if(x)return x}}if(s===0){let y=Tye(u,a,n,i,s);if(y)return y}}s++}return{complete:!0,rootMessageCid:i,edges:a,depth:s}}async function Aye(r,e,t,n,i){let a=wb(n,i),o=[];for(let s of r){let c=await GE(s,e,t,a);o.push(c)}return o}function Tye(r,e,t,n,i){let a=e.find(p=>p.label==="permissionGrant");if(!a)return null;let o=r.descriptor.messageTimestamp;if(!o)return null;let s=t.grantCache.get(a.identifier);if(!s)return null;let c=s.descriptor.dateCreated,l,d=s.encodedData;if(d)try{l=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).dateExpires}catch{}if(c&&o<c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantNotYetActive",edge:a,detail:`grant '${a.identifier}' is not yet active at message timestamp ${o} (dateGranted: ${c})`},depth:i};if(l&&o>=l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantExpired",edge:a,detail:`grant '${a.identifier}' expired at ${l}, message timestamp is ${o}`},depth:i};let u=`revocation:${a.identifier}`,f=t.grantCache.get(u);if(f&&f.descriptor.interface!=="Synthetic"){let p=f.descriptor.messageTimestamp;if(p&&p<=o)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantRevocationMissing",edge:e.find(h=>h.label==="grantRevocation")??a,detail:`grant '${a.identifier}' was revoked at ${p}, before message timestamp ${o}`},depth:i}}return null}async function WG(r,e,t,n,i,a,o,s){for(let c of r){e.push(c);let l=`${c.label}:${c.identifierType}:${c.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:o,edges:e,failure:{code:JG(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) is missing`},depth:s};let d=await Iye(c,t,n);if(!d)return n.missingDeps.add(l),{complete:!1,rootMessageCid:o,edges:e,failure:{code:JG(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) not found locally`},depth:s};if(n.satisfiedDeps.add(l),!(c.identifierType==="grantId"||c.identifierType==="filter"||c.label==="contextKeyRecord")){let f=await ye.getCid(d);i.has(f)||(i.add(f),a.push(d))}}return null}async function Iye(r,e,t){switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return t.protocolCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.protocolCache.set(r.identifier,i),i}case"recordId":{if(r.label==="initialWrite"){let{messages:i}=await e.query(t.tenantDid,[{entryId:r.identifier}]);if(i.length>0)return i[0];let{messages:a}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return a.length>0?a[0]:null}if(r.label==="crossProtocolParent"){let i=r.identifier.indexOf("|");if(i>0){let a=r.identifier.substring(0,i),o=r.identifier.substring(i+1),{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:a,recordId:o,isLatestBaseState:!0}]);return s.length>0?s[0]:null}}let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return n.length>0?n[0]:null}case"grantId":{if(r.label==="grantRevocation"){let a=`revocation:${r.identifier}`;if(t.grantCache.has(a))return t.grantCache.get(a)??null;let{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),s;for(let d of o){let u=d.descriptor.messageTimestamp;(!s||u<s.descriptor.messageTimestamp)&&(s=d)}let l=s??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(a,l),l}if(t.grantCache.has(r.identifier))return t.grantCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.grantCache.set(r.identifier,i),i}case"messageCid":{if(r.label==="contextKeyRecord"){let n=r.identifier.indexOf("|");if(n>0){let i=r.identifier.substring(0,n),a=r.identifier.substring(n+1),{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":i,"tag.contextId":a}]);return o.length>0?o[0]:null}}return await e.get(t.tenantDid,r.identifier)??null}case"filter":{if(!r.filter)return null;let{messages:n}=await e.query(t.tenantDid,[r.filter]);return n.length>0?n[0]:null}default:return null}}function JG(r){switch(r.dependencyClass){case 1:return"ClosureProtocolMetadataMissing";case 2:return r.label==="initialWrite"?"ClosureInitialWriteMissing":r.label==="parentRecord"?"ClosureParentChainMissing":r.label==="contextRoot"?"ClosureContextChainMissing":"ClosureParentChainMissing";case 3:return r.label==="permissionGrant"?"ClosureGrantMissing":"ClosureGrantRevocationMissing";case 4:return r.label==="squashContextRoot"?"ClosureVisibilityFloorMissing":"ClosureVisibilityFloorMissing";case 5:return"ClosureEncryptionDependencyMissing";case 6:return"ClosureCrossProtocolReferenceMissing";default:return"ClosureDependencyForbidden"}}g();ea();Sr();var Bf=class extends hE{constructor({agent:t,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=t}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(t){this._agent=t}async get(t){try{let n=await this.cache.get(t),i=JSON.parse(n);if(!this._resolving.has(t)&&Date.now()>=i.ttlMillis){this._resolving.set(t,!0);let a=await this.agent.did.get({didUri:t,tenant:this.agent.agentDid.uri});if(typeof a<"u")try{let o=await this.agent.did.resolve(t);if(!o.didResolutionMetadata.error&&o.didDocument){let s={...a,document:o.didDocument,metadata:o.didDocumentMetadata};try{await this.agent.did.update({portableDid:s,tenant:this.agent.agentDid.uri,publish:!1})}catch(c){c.message&&!c.message.includes("No changes detected, update aborted")&&Ms.error(`Error updating DID: ${c.message}`)}}}finally{this._resolving.delete(t)}else this._resolving.delete(t),this.cache.nextTick(()=>this.cache.del(t))}return i.value}catch(n){if(n.notFound)return;throw n}}};g();Xn();g();ea();Xn();async function dg(r,e){let t=await e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(FC.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function nHe(r){return ye.getAuthor(r)}function iHe(r){return ut.decodePlainObjectPayload(r.authorization.signature)?.protocolRole}function jd(r){return!r||typeof r!="object"||r===null?!1:"message"in r&&typeof r.message=="object"&&r.message!==null&&"descriptor"in r.message&&typeof r.message.descriptor=="object"&&r.message.descriptor!==null&&"interface"in r.message.descriptor&&r.message.descriptor.interface===ve.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function Dye(r){return ye.getCid(r)}async function sHe(r,e){let t=e===Ut.CreatedAscending||e===Ut.CreatedDescending?r.descriptor.dateCreated:r.descriptor.datePublished;if(t===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await Dye(r),value:t}}function oHe(r,e=3e3,t=3e5,n){let i=Date.now()+t,a=null,o=!0;return new Promise((s,c)=>{n&&n.addEventListener("abort",()=>{o=!1,a!==null&&clearTimeout(a),console.log("Polling aborted by user"),s(null)});async function l(){if(!o)return;let d=i-Date.now();if(d<=0){o=!1,console.log("Polling stopped: TTL reached"),s(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(d/1e3)}s)`);try{let u=await r();if(u.ok){o=!1,a!==null&&clearTimeout(a),console.log("Polling stopped: Success condition met"),s(u);return}}catch(u){console.error("Error fetching data:",u),c(u)}o&&(a=setTimeout(l,e))}l()})}function vb(r,e){return r.endsWith("/")&&(r=r.slice(0,-1)),e.startsWith("/")&&(e=e.slice(1)),`${r}/${e}`}var ZG=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}async recordsQuery(e,t){let n=await ba.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,t){let n=await Sd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,t,n){let i=await Ia.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,t){let n=await hd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,t){let n=await Aa.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,t,n,i){let a=await dg(e,this._didResolver),o=[];for(let s of a)try{if(i!==void 0){if(!(await this._rpcClient.getServerInfo(s)).webSocketSupport){o.push({url:s,message:"WebSocket support is not enabled on the server."});continue}let d=new URL(s);d.protocol=d.protocol==="http:"?"ws:":"wss:",s=d.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:s,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(c){o.push({url:s,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(o)}`)}};g();var lg=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();Pn();var B6={"AES-GCM":{implementation:Mm,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Km,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Yc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:wP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:bP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:fc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:fc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:Iu,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Ru,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},xo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:t})}async bytesToPublicKey({algorithm:e,publicKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:t})}async decrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).decrypt(e)}async deriveKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:t}),i;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{i=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{i=e.algorithm.split(/[-+]/)[2];break}default:throw new Fe(Le.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new Fe(Le.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${i}`);let o=await n.deriveKeyBytes({...e,length:a});return await this.bytesToPrivateKey({algorithm:i,privateKeyBytes:o})}async deriveKeyBytes(e){let t=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)}async digest({algorithm:e,data:t}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})}async encrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).encrypt(e)}async generateKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:t}).generateKey({algorithm:e.algorithm});return i.kid??=await vt({jwk:i}),i}async getPublicKey({key:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:t}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:t,key:e})}async unwrapKey(e){let t=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:t}).unwrapKey(e)}async verify({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})}async wrapKey(e){let t=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:t}).wrapKey(e)}getAlgorithm({algorithm:e}){let t=B6[e]?.implementation;if(!t)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({algorithm:e,key:t}){let n=t?.alg??e,i=t?.crv;for(let a of Object.keys(B6)){let o=B6[a].names;if(n&&o.includes(n))return a;if(i&&o.includes(i))return a}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();ea();Pn();g();Sr();ea();g();var HE={protocol:"https://identity.foundation/protocols/web5/identity-store",published:!1,types:{portableDid:{schema:"https://identity.foundation/schemas/web5/portable-did",dataFormats:["application/json"]},identityMetadata:{schema:"https://identity.foundation/schemas/web5/identity-metadata",dataFormats:["application/json"]}},structure:{portableDid:{},identityMetadata:{}}},za={protocol:"https://identity.foundation/protocols/key-delivery",published:!1,types:{contextKey:{dataFormats:["application/json"]}},structure:{contextKey:{$actions:[{who:"recipient",of:"contextKey",can:["read"]}],$tags:{$requiredTags:["protocol","contextId"],$allowUndefinedTags:!1,protocol:{type:"string"},contextId:{type:"string"}}}}},YG={protocol:"https://identity.foundation/protocols/web5/jwk-store",published:!1,types:{privateJwk:{schema:"https://identity.foundation/schemas/web5/private-jwk",dataFormats:["application/json"],encryptionRequired:!0}},structure:{privateJwk:{}}};g();Pn();var Ri="^",VE=class extends Xc{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let t={};for(let n of e){n.kid??=await vt({jwk:n});let i=await this.getKeyUri({key:n});t[i]=n}this._predefinedKeys=new Map(Object.entries(t)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return t}async generateKey(e){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t}async getPublicKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=t;return i}async sign({keyUri:e,data:t}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await Un.sign({data:t,key:n})}};async function Md({agent:r,tenant:e,didUri:t}){if(e)return e;if(r.agentDid)return r.agentDid.uri;if(!t)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return t}g();var bb=Tn(JE(),1);Sr();Xn();var Of=class{constructor(){this.name="DwnDataStore";this._cache=new xi.default({ttl:(0,bb.default)("15 minutes"),max:100});this._index=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._protocolInitializedCache=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._tenantEncryptionActive=new xi.default({ttl:(0,bb.default)("21 days"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:t});if(!a)return!1;let{reply:{status:o}}=await t.dwn.processRequest({author:i,target:i,messageType:Re.RecordsDelete,messageParams:{recordId:a}});if(o.code===202)return this._index.delete(`${i}${Ri}${e}`),this._cache.delete(a),!0;throw new Error(`${this.name}: Failed to delete '${e}' from store: (${o.code}) ${o.detail}`)}async get({id:e,agent:t,tenant:n,useCache:i=!1}){let a=await Md({agent:t,tenant:n,didUri:e}),o=await this.lookupRecordId({id:e,tenantDid:a,agent:t});if(o)return await this.getRecord({recordId:o,tenantDid:a,agent:t,useCache:i})}async list({agent:e,tenant:t}){let n=await Md({tenant:t,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:o=!1,useCache:s=!1}){let c=await Md({agent:i,tenant:n,didUri:e});await this.initialize({tenant:c,agent:i});let l={...this._recordProperties};if(o){let h=await this.getExistingRecordEntry({id:e,tenantDid:c,agent:i});if(!h)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=h.recordsWrite.recordId,l.dateCreated=h.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:c,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=he.object(t).toUint8Array(),u=this.isEncryptionActive(c),{message:f,reply:{status:p}}=await i.dwn.processRequest({author:c,target:c,messageType:Re.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([d],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${p.detail}`);this._index.set(`${c}${Ri}${e}`,f.recordId),s&&this._cache.set(f.recordId,t)}async initialize({tenant:e,agent:t}){let n=await Md({agent:t,tenant:e});if(this._protocolInitializedCache.has(n))return;let{reply:{status:i,entries:a}}=await t.dwn.processRequest({author:n,target:n,messageType:Re.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);if(a?.length===0)await this.installProtocol(n,t);else if(this.encryptionRequired&&!this._tenantEncryptionActive.has(n)){let o=a[0].descriptor?.definition,s=Object.keys(o?.structure??{})[0],c=!!(s&&o?.structure[s]?.$encryption);this._tenantEncryptionActive.set(n,c)}this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}async getAllRecords(e){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")}async getRecord({recordId:e,tenantDid:t,agent:n,useCache:i}){if(i){let c=this._cache.get(e);if(c)return c}let a=this.encryptionRequired||this.isEncryptionActive(t),{reply:o}=await n.dwn.processRequest({author:t,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:e}},...a?{encryption:!0}:{}});if(!o.entry?.data)throw new Error(`${this.name}: Failed to read data from DWN for: ${e}`);let s=await Bm.consumeToJson({readableStream:o.entry.data});return i&&this._cache.set(e,s),s}async installProtocol(e,t){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let o=await t.dwn.getEncryptionKeyDeriver(e);n=await xd.deriveAndInjectPublicEncryptionKeys(n,o),i=!0}this._tenantEncryptionActive.set(e,i);let{reply:{status:a}}=await t.dwn.processRequest({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`)}async lookupRecordId({id:e,tenantDid:t,agent:n}){let i=this._index.get(`${t}${Ri}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:t}),i=this._index.get(`${t}${Ri}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:t,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:t,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:t,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},jf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e});return this.store.has(`${i}${Ri}${e}`)?(this.store.delete(`${i}${Ri}${e}`),!0):!1}async get({id:e,agent:t,tenant:n}){let i=await Md({agent:t,tenant:n,didUri:e});return this.store.get(`${i}${Ri}${e}`)}async list({agent:e,tenant:t}){let n=await Md({tenant:t,agent:e}),i=[];for(let[a,o]of this.store.entries())a.startsWith(`${n}${Ri}`)&&i.push(o);return i}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a,updateExisting:o}){let s=await Md({agent:i,tenant:n,didUri:e});if(o){if(!this.store.has(`${s}${Ri}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${s}${Ri}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=structuredClone(t);this.store.set(`${s}${Ri}${e}`,c)}};var hg=class extends Of{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=HE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(Ph(s)){let c=`${n}${Ri}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},mg=class extends jf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};var jye=(t=>(t.Create="Create",t.Resolve="Resolve",t))(jye||{});function QG(r,e){return r.messageType===e}var Dh=class extends tg{constructor({agent:t,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Bf({agent:t,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=t,this._store=a??new mg;for(let o of n)this._didMethods.set(o.methodName,o)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(t){this._agent=t,"agent"in this.cache&&(this.cache.agent=t)}async create({method:t,tenant:n,options:i,store:a}){let s=await this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(await this.cache.set(s.uri,{didDocument:s.document,didResolutionMetadata:{},didDocumentMetadata:s.metadata}),a??!0){let{uri:c,document:l,metadata:d}=s,u={uri:c,document:l,metadata:d};await this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return s}async export({didUri:t,tenant:n}){let i=await this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return await i.export()}async get({didUri:t,tenant:n}){let i=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?await Ss.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:t,methodId:n}){let i=Jn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let a=this.getMethod(i.method),{didDocument:o,didResolutionMetadata:s}=await this.resolve(t);if(!o)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(s)}`);return await a.getSigningMethod({didDocument:o,methodId:n})}async update({tenant:t,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:t??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(Xw(n.document)===Xw(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let o=await Ss.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:s,document:c,metadata:l}=o,d={uri:s,document:c,metadata:l};if(await this.cache.set(s,{didDocument:c,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:s,data:d,agent:this.agent,tenant:t??s,updateExisting:!0,useCache:!0}),i){let u=Jn.parse(s);u&&u.method==="dht"&&await vo.publish({did:o})}return o}async import({portableDid:t,tenant:n}){let i=await Ss.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:a,document:o,metadata:s}=i,c={uri:a,document:o,metadata:s};return await this.cache.set(a,{didDocument:o,didResolutionMetadata:{},didDocumentMetadata:s}),await this._store.set({id:c.uri,data:c,agent:this.agent,tenant:n??c.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:t,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(t),await this._store.delete({id:t,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});await this.agent.keyManager.deleteKey({keyUri:i})}}async processRequest(t){if(QG(t,"Create"))try{let n=await this.create({...t.messageParams});return{result:{uri:n.uri,document:n.document,metadata:n.metadata},ok:!0,status:{code:201,message:"Created"}}}catch(n){return{ok:!1,status:{code:500,message:n.message??"Unknown error occurred"}}}if(QG(t,"Resolve")){let{didUri:n,options:i}=t.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${t.messageType}`)}getMethod(t){let n=this._didMethods.get(t);if(n===void 0)throw new Error(`DID Method not supported: ${t}`);return n}};g();Xn();Sr();Pn();ea();g();Xn();Sr();var _s=class r{constructor({agent:e}={}){this._cachedPermissions=new xi.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:t,delegate:n,messageType:i,protocol:a,cached:o=!1}){let s=[e,t,i,a].join("~"),c=o?this._cachedPermissions.get(s):void 0;if(c)return c;let l=await this.fetchGrants({author:t,target:t,grantor:e,grantee:t}),d=await r.matchGrantFromArray(e,t,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(s,d),d}async fetchGrants({author:e,target:t,grantee:n,grantor:i,protocol:a,remote:o=!1,checkRevoked:s=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:rt.uri,protocolPath:rt.grantPath,tags:c}}},{reply:d}=o?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=s?await this.fetchRevokedGrantIds({author:e,target:t,grantor:i,remote:o,tags:c}):new Set,f=[];for(let p of d.entries){if(u.has(p.recordId))continue;let h=Ir.parse(p);f.push({grant:h,message:p})}return f}async fetchRevokedGrantIds({author:e,target:t,grantor:n,remote:i,tags:a}){let o={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:rt.uri,protocolPath:rt.revocationPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${s.status.detail}`);let c=new Set;for(let l of s.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:t,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,o={author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:rt.uri,protocolPath:rt.requestPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${s.status.detail}`);let c=[];for(let l of s.entries){let d=md.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:t,grantRecordId:n,remote:i=!1}){let a={author:e,target:t,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:rt.uri,protocolPath:rt.revocationPath}}},{reply:o}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)}async createGrant(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,o;rt.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope};a.delegateKeyDelivery&&(s.delegateKeyDelivery=a.delegateKeyDelivery);let c=he.object(s).toUint8Array(),l={recipient:a.grantedTo,protocol:rt.uri,protocolPath:rt.grantPath,dataFormat:"application/json",tags:o},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,o;rt.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),l={protocol:rt.uri,protocolPath:rt.requestPath,dataFormat:"application/json",tags:o},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{request:md.parse(f),message:f}}async createRevocation(e){let{author:t,store:n=!1,grant:i,description:a}=e,o={description:a},s=he.object(o).toUint8Array(),c;rt.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:rt.uri,protocolPath:rt.revocationPath,dataFormat:"application/json",tags:c};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:Re.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([s])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:he.uint8Array(s).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,t,n,i,a=!1){let o;for(let s of i){let{grant:c,message:l}=s;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:p}=n;if(this.matchScopeFromGrant(e,t,d,c,u,f,p)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};o||(o={grant:c,message:l})}}return o}static matchScopeFromGrant(e,t,n,i,a,o,s){if(i.grantee!==t||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(O6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===o||u.contextId!==void 0&&s?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var Mye="@enbox/dwn-server";function ZE(r){return r.endsWith("/")?r.slice(0,-1):r}var Rh=class{constructor(e,t=1e4,n){this._rpcClient=e;this._cacheTtlMs=t;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=await this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let t=ZE(e),n=await this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}async _tryDiscoveryFile(){if(this._discoveryFile)try{let e=await this._discoveryFile.read();return e&&await this._validateEndpoint(e.endpoint)?e.endpoint:void 0}catch{return}}async _validateEndpoint(e){try{return(await this._rpcClient.getServerInfo(e)).server===Mye}catch{return!1}}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};function Kye(){try{let r=mS,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(t.dirname(i),{recursive:!0}),await e.writeFile(i,a,{encoding:"utf-8",mode:384})},async removeFile(i){try{await e.unlink(i)}catch{}},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var Nye=".enbox",Uye="dwn.json",YE=class{constructor(e,t){let n=e??Kye();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,t)this._filePath=t;else{let a=mS("node:path");this._filePath=a.join(n.homedir(),Nye,Uye)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!Lye(t)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:ZE(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n}async write(e){let t={endpoint:ZE(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function Lye(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||e.capabilities!==void 0&&(!Array.isArray(e.capabilities)||!e.capabilities.every(t=>typeof t=="string")))}g();Xn();function Fa(r,e){return r.messageType===e}function qye(r,e){return e.descriptor.interface+e.descriptor.method===r}function O6(r){return r===Re.RecordsDelete||r===Re.RecordsQuery||r===Re.RecordsRead||r===Re.RecordsSubscribe||r===Re.RecordsWrite}function Ch(r){return r.interface===ve.Records}function zye(r){return r.interface===ve.Messages}g();Xn();Pn();function XE(r){return r===di.XC20P?24:12}function $h(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}async function QE(r,e,t,n=di.A256GCM){let{ciphertextStream:i,tag:a}=await Ei.aeadEncryptStream(n,e,t,Wt.fromBytes(r)),o=await Wt.toBytes(i),s=Wt.fromBytes(o),c=await mr.computeDagPbCidFromStream(s);return{encryptedBytes:o,dataCid:c,dataSize:o.length,authenticationTag:a}}async function na(r,e){let{didDocument:t,didResolutionMetadata:n}=await r.did.resolve(e);if(!t)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=t.keyAgreement;if(!i||i.length===0)throw new Error(`AgentDwnApi: DID '${e}' does not have a keyAgreement verification method. Create the identity with an X25519 key with keyAgreement purpose to use protocol encryption.`);let a=i[0],o;if(typeof a=="string"){let l=a.includes("#")?a.split("#").pop():a;o=t.verificationMethod?.find(d=>d.id.endsWith(`#${l}`))}else o=a;if(!o?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let s=o.publicKeyJwk;if(s.crv==="Ed25519")s=await Un.convertPublicKeyToX25519({publicKey:s});else if(s.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${s.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let c=await r.keyManager.getKeyUri({key:s});return{keyId:o.id,keyUri:c,publicKeyJwk:s}}async function tH(r,e,t,n,i){let{keyId:a,keyUri:o}=await na(r,e),s=Ie.constructKeyDerivationPathUsingProtocolContextScheme(t),c=await r.keyManager.derivePublicKey({keyUri:o,derivationPath:s});return{encryptionInput:$h(n,i,a,c,Pt.ProtocolContext),keyId:a,keyUri:o,contextDerivationPath:s}}function rH(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,o)=>i.jweKeyUnwrap({keyUri:t,derivationPath:a,encryptedKey:o.encryptedKey,ephemeralPublicKey:o.ephemeralPublicKey})}}async function xb(r,e){let{keyId:t,keyUri:n}=await na(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:Pt.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function j6(r,e){let{keyId:t,keyUri:n}=await na(r,e);return rH(r,t,n,Pt.ProtocolPath)}function Pb(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=await Ie.derivePrivateKey(r,e),i=await At.bytesToPrivateKey({privateKeyBytes:n});return Ei.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)}}}function Fye(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=r.derivationPath??[];if(n.length!==e.length||!n.every((o,s)=>o===e[s]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${n.join(", ")}], record path: [${e.join(", ")}].`);let i=await Ie.derivePrivateKey(r,e),a=await At.bytesToPrivateKey({privateKeyBytes:i});return Ei.ecdhEsUnwrapKey(a,t.ephemeralPublicKey,t.encryptedKey)}}}async function eH(r,e,t,n,i,a,o,s,c){let{encryption:l}=t;if(!l?.recipients.some(x=>x.header.derivationScheme===Pt.ProtocolContext)||!t.contextId){if(o&&s){let x=t.descriptor.protocol,_=t.descriptor.protocolPath;if(x){let A=`ddk~${s}`,D=o.get(A);if(D){let N=D.filter(z=>z.protocol===x);if(_){let z=N.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===_);if(z)return Fye(z.derivedPrivateKey)}let $=N.find(z=>z.scope.kind==="protocol");if($)return Pb($.derivedPrivateKey)}}}return j6(r,e)}let u=l.recipients.find(x=>x.header.derivationScheme===Pt.ProtocolContext),f=t.contextId.split("/")[0];if(c&&s){let x=t.descriptor.protocol;if(x){let _=`dctx~${s}~${x}~${f}`,A=c.get(_);if(A)return Pb(A);try{let D=await a({ownerDid:e,requesterDid:s,sourceProtocol:x,sourceContextId:f});if(D)return c.set(_,D),Pb(D)}catch{}}throw new Error(`AgentDwnApi: Delegate '${s}' does not have a context key for context '${f}'. No delivered contextKey record was found via the key-delivery protocol. The delegate may need to reconnect or wait for sync.`)}let{keyId:p,keyUri:h}=await na(r,e);if(u.header.kid===p)return rH(r,p,h,Pt.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return Pb(y);let v=t.descriptor.protocol,w=await a({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:x}=await Promise.resolve().then(()=>(Xn(),GG)),_=n??x.getSignerDid(t.authorization.signature.signatures[0]);w=await a({ownerDid:_,requesterDid:e,sourceProtocol:v,sourceContextId:f})}if(!w)throw new Error(`AgentDwnApi: Failed to decrypt record '${t.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(m,w),Pb(w)}async function nH(r,e,t,n,i,a,o){if(!(!("encryption"in r)||!r.encryption)){if(Fa(r,Re.RecordsRead)){let s=e;if(s.status.code===200&&s.entry?.recordsWrite?.encryption&&s.entry?.data){let c=await eH(t,r.author,s.entry.recordsWrite,r.target,n,i,a,r.granteeDid,o);try{s.entry.data=await Ie.decrypt(s.entry.recordsWrite,c,s.entry.data)}catch(l){throw new Error(`AgentDwnApi: Failed to decrypt record '${s.entry.recordsWrite.recordId}'. Original error: ${l.message}`)}}}if(Fa(r,Re.RecordsQuery)){let s=e;if(s.status.code===200&&s.entries){for(let c of s.entries)if(c.encryption&&c.encodedData){let l=await eH(t,r.author,c,r.target,n,i,a,r.granteeDid,o);try{let d=De.base64UrlToBytes(c.encodedData),u=Wt.fromBytes(d),f=await Ie.decrypt(c,l,u),p=await Wt.toBytes(f);c.encodedData=De.bytesToBase64Url(p)}catch(d){throw new Error(`AgentDwnApi: Failed to decrypt record '${c.recordId}'. Original error: ${d.message}`)}}}}}}g();Xn();async function iH(r,e,t,n,i,a){if(i.get(e))return;let o=za.protocol;if(!await n(e,o)){let c=await xb(r,e),l=await xd.deriveAndInjectPublicEncryptionKeys(za,c),{reply:{status:d}}=await t({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:l}});if(d.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${d.code} - ${d.detail}`);a.delete(`${e}~${o}`)}i.set(e,!0)}async function sH(r,e,t,n,i){let{tenantDid:a,recipientDid:o,contextKeyData:s,sourceProtocol:c,sourceContextId:l,recipientKeyDeliveryPublicKey:d}=e;await n(a);let u=za.protocol,f=new TextEncoder().encode(JSON.stringify(s)),p={protocol:u,protocolPath:"contextKey",dataFormat:"application/json",recipient:o,tags:{protocol:c,contextId:l}},h,m;if(d){let y=di.A256GCM,v=crypto.getRandomValues(new Uint8Array(32)),w=crypto.getRandomValues(new Uint8Array(XE(y))),{encryptedBytes:x,dataCid:_,dataSize:A,authenticationTag:D}=await QE(f,v,w,y),N={...$h(v,w,d.rootKeyId,d.publicKeyJwk,Pt.ProtocolPath),authenticationTag:D};({message:h,reply:{status:m}}=await t({author:a,target:a,messageType:Re.RecordsWrite,messageParams:{...p,dataCid:_,dataSize:A,encryptionInput:N},dataStream:new Blob([x])}))}else({message:h,reply:{status:m}}=await t({author:a,target:a,messageType:Re.RecordsWrite,messageParams:p,dataStream:new Blob([f],{type:"application/json"}),encryption:!0}));if(!(h&&m.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${o}: ${m.code} - ${m.detail}`);return i(a,h).catch(y=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${h.recordId}' to remote DWN failed: ${y.message}. Sync will deliver it later.`)}),h.recordId}async function oH(r,e,t,n,i,a){let o;try{o=await a(e)}catch{return}if(o.length===0)return;let{data:s}=await n({author:e,messageType:Re.RecordsWrite,messageCid:await ye.getCid(t)});await i({targetDid:e,dwnEndpointUrls:o,message:t,data:s})}async function Gye(r,e,t,n,i){try{let{reply:a}=await r({author:e,target:t,messageType:Re.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!a.entries?.length)return;let o=a.entries[0].recordId,{reply:s}=await r({author:e,target:t,messageType:Re.RecordsRead,messageParams:{filter:{recordId:o}},encryption:!0}),c=s;return c.entry?.data?i(await Wt.toBytes(c.entry.data)):void 0}catch{return}}async function aH(r,e,t){let{ownerDid:n,requesterDid:i,sourceProtocol:a,sourceContextId:o}=e,s=za.protocol,c=n===i,l={protocol:s,protocolPath:"contextKey",recipient:i,tags:{protocol:a,contextId:o}},d=u=>JSON.parse(new TextDecoder().decode(u));if(c){let{reply:u}=await t({author:i,target:n,messageType:Re.RecordsQuery,messageParams:{filter:l}});if(u.status.code!==200||!u.entries?.length)return;let f=u.entries[0].recordId,{reply:p}=await t({author:i,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:f}},encryption:!0}),h=p;return h.entry?.data?d(await Wt.toBytes(h.entry.data)):void 0}return Gye(t,i,n,l,d)}g();Xn();async function cH(r,e,t,n,i,a,o){let s=`${r}~${e}`,c=i.get(s);if(c)return c;let d=await n(a??r),u=await Ah[Re.ProtocolsQuery].create({filter:{protocol:e},signer:d,...o?{permissionGrantId:o}:{}}),f=await t.processMessage(r,u.message);if(f.status.code!==200||!f.entries?.length)return;let p=f.entries[0].descriptor.definition;return i.set(s,p),p}async function dH(r,e,t,n,i){let a=`remote~${r}~${e}`,o=i.get(a);if(o)return o;let s=await Ah[Re.ProtocolsQuery].create({filter:{protocol:e}}),c=await n({targetDid:r,dwnEndpointUrls:await t(r),message:s.message});if(c.status.code!==200||!c.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let l=c.entries[0].descriptor.definition;return i.set(a,l),l}async function lH(r,e,t,n,i,a,o){let s=await a(n),c=await Ah[Re.RecordsQuery].create({signer:s,filter:{protocol:e,contextId:t}}),l=await i(r),d=await o({targetDid:r,dwnEndpointUrls:l,message:c.message});if(!(d.status.code!==200||!d.entries?.length)){for(let u of d.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(p=>p.header.derivationScheme===Pt.ProtocolContext&&p.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Vl=class r{constructor(e){this._protocolDefinitionCache=new xi.default({ttl:30*60*1e3});this._contextKeyCache=new xi.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new xi.default({ttl:30*60*1e3});this._delegateDecryptionKeyCache=new xi.default({ttl:24*60*60*1e3});this._delegateContextKeyCache=new xi.default({ttl:24*60*60*1e3});this._delegateContextKeyCacheIndex=new Map;this._delegateMultiPartyProtocols=new Map;this._localManagedDidCache=new xi.default({ttl:30*60*1e3});this._keyDeliveryProtocolInstalledCache=new xi.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:t,localDwnStrategy:n="prefer"}=e;this._agent=t,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,t&&(this._localDwnDiscovery=new Rh(t.rpc,1e4,r._tryCreateDiscoveryFile()))}get isRemoteMode(){return this._dwn===void 0}get agent(){if(this._agent===void 0)throw new Error("AgentDwnApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._localDwnDiscovery=new Rh(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new Rh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return dg(e,this.agent.did);let n=await this.getLocalDwnEndpoint();if(this._localDwnStrategy==="only"){if(!n)throw new Error("AgentDwnApi: Local DWN strategy is 'only' but no local DWN endpoint was discovered. Ensure the local DWN server is running and discoverable via the discovery file (~/.enbox/dwn.json) or dwn://connect.");return[n]}let i=[];try{i=await dg(e,this.agent.did)}catch(o){if(!n)throw o}return n?[...new Set([n,...i])]:i}async getRemoteDwnEndpointUrls(e){return dg(e,this.agent.did)}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new Rh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new YE}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let t=this._localManagedDidCache.get(e);if(t!==void 0)return t;if(e===this.agent.agentDid.uri)return this._localManagedDidCache.set(e,!0),!0;let n=await this.agent.identity.list(),i=new Set;for(let o of n)i.add(o.did.uri),o.metadata.connectedDid&&i.add(o.metadata.connectedDid);for(let o of i)this._localManagedDidCache.set(o,!0);let a=i.has(e);return a||this._localManagedDidCache.set(e,!1),a}get node(){if(!this._dwn)throw new Error(`AgentDwnApi: The in-process DWN instance is not available. The agent is operating in remote mode (local DWN server at '${this._localDwnEndpoint}'). Use processRequest() instead of accessing the DWN node directly.`);return this._dwn}static async createDwn({dataPath:e,dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:o,tenantGate:s,resumableTaskStore:c}){return t??=new If({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new tg({didResolvers:[vo,bo],cache:new hE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new $f({location:`${e}/DWN_STATEINDEX`}),o??=new Df({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),c??=new Rf({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Cf,await rg.create({dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:o,tenantGate:s,resumableTaskStore:c})}async processRequest(e){let{message:t,dataStream:n}=await this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,a;if(e.store===!1)a={status:{code:202,detail:"Accepted"}};else if(this._dwn)a=await this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let o;if(n){let s=await Wt.toBytes(n);o=new Blob([s])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:o,subscriptionHandler:i})}return await this.postWriteKeyDelivery(e,t,a),await this.maybeDecryptReply(e,a),{reply:a,message:t,messageCid:await ye.getCid(t)}}async processRawMessage(e,t,n){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await Wt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})}async sendRequest(e){let t=await this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,a,o;if("messageCid"in e)({message:i,data:a}=await this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=await this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");a=e.dataStream,o=e.subscriptionHandler}let s;o!==void 0&&!("messageCid"in e)&&(s=async l=>{let d=l!==void 0?{...e.messageParams,cursor:l}:e.messageParams,u={...e,messageParams:d},{message:f}=await this.constructDwnMessage({request:u});return f});let c=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:a,subscriptionHandler:o,resubscribeFactory:s});return await this.maybeDecryptReply(e,c),n??=await ye.getCid(i),{reply:c,message:i,messageCid:n}}async postWriteKeyDelivery(e,t,n){if(!Fa(e,Re.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==za.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let o=t,s=ut.getSignerDid(o.authorization.signature.signatures[0]),c=s!==e.target,l=!i.parentContextId,d=i.protocolPath.split("/")[0],u=Th(a,d),f=$6({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:c?s:void 0}),p=o.contextId?.split("/")[0]||o.contextId||o.recordId,h=u&&l&&!c&&this.hasEligibleDelegatesForProtocol(i.protocol);if(f.size>0||h){let{keyId:m,keyUri:y}=await na(this.agent,e.target),v=[Pt.ProtocolContext,p],w=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:y,derivationPath:v}),x=await At.bytesToPrivateKey({privateKeyBytes:w}),_={rootKeyId:m,derivationScheme:Pt.ProtocolContext,derivationPath:v,derivedPrivateKey:x};if(f.size>0){let A=o.authorization?.authorKeyDeliveryPublicKey;for(let D of f)try{let N=D===s&&A?A:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:D,contextKeyData:_,sourceProtocol:i.protocol,sourceContextId:p,recipientKeyDeliveryPublicKey:N})}catch(N){console.warn(`AgentDwnApi: Key delivery to '${D}' for context '${p}' failed: ${N.message}. The participant may not be able to decrypt records in this context.`)}}h&&this.deliverContextKeyToDelegates(i.protocol,p,_)}if(u&&l&&!c){let{keyId:m,keyUri:y}=await na(this.agent,e.target),v=[Pt.ProtocolContext,p],w=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:y,derivationPath:v}),x=await At.bytesToPrivateKey({privateKeyBytes:w}),_={rootKeyId:m,derivationScheme:Pt.ProtocolContext,derivationPath:v,derivedPrivateKey:x};await this.deliverContextKeyToDelegatesViaDwn(e.target,i.protocol,p,_)}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:t,message:n,data:i,subscriptionHandler:a,resubscribeFactory:o}){let s=[];if(n.descriptor.method===me.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let c of t)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(c)).webSocketSupport){s.push({url:c,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(c);u.protocol=u.protocol==="http:"?"ws:":"wss:",c=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:c,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:o}:void 0})}catch(l){s.push({url:c,message:l instanceof Error?l.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(s)}`)}async constructDwnMessage({request:e}){if(e.granteeDid&&!this.hasGrantParams(e.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let t=e.rawMessage,n;if(Fa(e,Re.RecordsWrite)){let s=e.messageParams;if(e.dataStream&&!s?.data){let{dataStream:c}=e,l;if(c instanceof Blob){let[d,u]=c.stream().tee();l=d,n=u}else if(c instanceof ReadableStream){let[d,u]=c.tee();l=d,n=u}!t&&s&&(s.dataCid=await mr.computeDagPbCidFromStream(l),s.dataSize===void 0&&c instanceof Blob&&(s.dataSize=c.size))}}if(Fa(e,Re.ProtocolsConfigure)&&e.encryption&&!t){let s=e.messageParams,c=await xb(this.agent,e.author);s.definition=await xd.deriveAndInjectPublicEncryptionKeys(s.definition,c),this._protocolDefinitionCache.delete(`${e.target}~${s.definition.protocol}`)}if(Fa(e,Re.ProtocolsConfigure)&&!e.encryption&&!t){let s=e.messageParams?.definition;s?.protocol&&this._protocolDefinitionCache.set(`${e.target}~${s.protocol}`,s)}let i;if(Fa(e,Re.RecordsWrite)&&e.encryption&&!t){let s=e.messageParams;if(s?.protocol&&s.protocolPath){let c=e.target!==e.author,l;if(c?l=await this.fetchRemoteProtocolDefinition(e.target,s.protocol):l=await this.getProtocolDefinition(e.target,s.protocol,e.granteeDid),!l)throw new Error(`AgentDwnApi: Protocol '${s.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let d=s.protocolPath.split("/"),u=l.structure;for(let L of d)u=u[L];if(!u?.$encryption)throw new Error(`AgentDwnApi: Protocol '${s.protocol}' at path '${s.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let f=s.protocolPath.split("/")[0],h=s.protocol===za.protocol?!1:Th(l,f),m=!s.parentContextId,y;if(s.data)y=s.data instanceof Uint8Array?s.data:new TextEncoder().encode(String(s.data));else if(e.dataStream instanceof Blob)y=new Uint8Array(await e.dataStream.arrayBuffer());else if(e.dataStream instanceof ReadableStream)y=await Wt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let v=di.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),x=crypto.getRandomValues(new Uint8Array(XE(v))),_,A=()=>$h(w,x,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,Pt.ProtocolPath);if(c&&h&&m)_=A();else if(c&&h&&!m){let L=s.parentContextId.split("/")[0]||s.parentContextId,j=await this.extractDerivedPublicKey(e.target,s.protocol,L,e.author);j?_=$h(w,x,j.rootKeyId,j.derivedPublicKey,Pt.ProtocolContext):_=A()}else if(c)_=A();else if(h&&!m){let L=s.parentContextId.split("/")[0]||s.parentContextId,j=this._contextKeyCache.get(L);if(!j){let{keyId:Y,keyUri:R}=await na(this.agent,e.author),C=Ie.constructKeyDerivationPathUsingProtocolContextScheme(L);j={keyId:Y,keyUri:R,contextDerivationPath:C},this._contextKeyCache.set(L,j)}let H=await this.agent.keyManager.derivePublicKey({keyUri:j.keyUri,derivationPath:j.contextDerivationPath});_=$h(w,x,j.keyId,H,Pt.ProtocolContext)}else h&&m?_=void 0:_=A();let{encryptedBytes:D,dataCid:N,dataSize:$,authenticationTag:z}=await QE(y,w,x,v);if(s.dataCid=N,s.dataSize=$,delete s.data,n=Wt.fromBytes(D),e.dataStream=void 0,_?(_.authenticationTag=z,s.encryptionInput=_):i={dataEncryptionKey:w,dataEncryptionIV:x,encryptedBytes:D,authenticationTag:z},c&&h){let{keyId:L,keyUri:j}=await na(this.agent,e.author),H=[Pt.ProtocolPath,za.protocol,"contextKey"],Y=await this.agent.keyManager.derivePublicKey({keyUri:j,derivationPath:H});s.authorKeyDeliveryPublicKey={rootKeyId:L,publicKeyJwk:Y}}}}let a,o=Ah[e.messageType];if(t){if(a=await o.parse(t),jd(a)&&e.signAsOwner){let s=await this.getSigner(e.author);await a.signAsOwner(s)}else if(e.granteeDid&&jd(a)&&e.signAsOwnerDelegate){let s=await this.getSigner(e.granteeDid),c=e.messageParams;await a.signAsOwnerDelegate(s,c.delegatedGrant)}}else{if(e.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let s=e.granteeDid?await this.getSigner(e.granteeDid):await this.getSigner(e.author),c={...e.messageParams};if(e.granteeDid&&c.permissionGrantId&&!c.delegatedGrant&&Fa(e,Re.RecordsWrite)){let{reply:l}=await this.processRequest({author:e.granteeDid,target:e.author,messageType:Re.RecordsRead,messageParams:{filter:{recordId:c.permissionGrantId}}});if(l.status.code===200&&l.entry?.recordsWrite&&l.entry?.data){let d=await Wt.toBytes(l.entry.data);c.delegatedGrant={...l.entry.recordsWrite,encodedData:he.uint8Array(d).toBase64Url()}}}if(a=await o.create({...c,signer:s}),i&&Fa(e,Re.RecordsWrite)){let l=a,d=l.message.recordId,{encryptionInput:u,keyId:f,keyUri:p,contextDerivationPath:h}=await tH(this.agent,e.author,d,i.dataEncryptionKey,i.dataEncryptionIV),m={...u,authenticationTag:i.authenticationTag};await l.encryptSymmetricEncryptionKey(m),await l.sign({signer:s}),this._contextKeyCache.set(d,{keyId:f,keyUri:p,contextDerivationPath:h})}}return{message:a.message,dataStream:n}}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}async getSigner(e){if(e===this.agent.agentDid.uri){let t=await this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:async n=>await t.sign({data:n})}}else try{let t=await this.agent.did.get({didUri:e});if(t){let s=await t.getSigner();return{algorithm:s.algorithm,keyId:s.keyId,sign:async c=>await s.sign({data:c})}}let n=await this.agent.did.getSigningMethod({didUri:e});if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.agent.keyManager.getPublicKey({keyUri:i}),o=this.agent.keyManager;return{algorithm:bn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async s=>await o.sign({data:s,keyUri:i})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}}async getEncryptionKeyDeriver(e){return xb(this.agent,e)}async getEncryptionKeyInfo(e){return na(this.agent,e)}async getKeyDecrypter(e){return j6(this.agent,e)}detectNewParticipants(e){return $6(e)}async getProtocolDefinition(e,t,n){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,t)}catch(a){let o=a instanceof Error?a.message:"";if(o.includes("not found")||o.includes("404")||o.includes("No protocol"))return;throw a}let i;if(n)try{let a=new _s({agent:this.agent}),{grant:o}=await a.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:Re.ProtocolsQuery});i=o.id}catch{}return cH(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)}async fetchRemoteProtocolDefinition(e,t){return dH(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,t,n,i){return lH(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,t){return nH(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)}async getDwnMessage({author:e,messageCid:t}){let n=await this.getSigner(e),i=await Ah[Re.MessagesRead].create({messageCid:t,signer:n}),a;if(this._dwn?a=await this._dwn.processMessage(e,i.message):a=await this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:i.message}),a.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${a.status.code} - ${a.status.detail}`);let o=a.entry,c={message:o.message};if(jd(o)){let l=o.data;if(l){let d=await Wt.toBytes(l);c.data=new Blob([d],{type:o.message.descriptor.dataFormat})}}return c}async ensureKeyDeliveryProtocol(e){return iH(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}set onDelegateContextKeysChanged(e){this._onDelegateContextKeysChanged=e}importDelegateDecryptionKeys(e,t){let n=`ddk~${e}`;this._delegateDecryptionKeyCache.set(n,t)}importDelegateContextKeys(e,t,n){let i=this._delegateContextKeyCacheIndex.get(e);if(i)for(let s of i)this._delegateContextKeyCache.delete(s);let a=[];for(let s of t){let c=`dctx~${e}~${s.protocol}~${s.contextId}`;this._delegateContextKeyCache.set(c,s.derivedPrivateKey),a.push(c)}this._delegateContextKeyCacheIndex.set(e,a);let o=new Set(n??[]);for(let s of t)o.add(s.protocol);o.size>0?this._delegateMultiPartyProtocols.set(e,o):this._delegateMultiPartyProtocols.delete(e)}clearDelegateDecryptionKeys(e){if(e){this._delegateDecryptionKeyCache.delete(`ddk~${e}`);let t=this._delegateContextKeyCacheIndex.get(e);if(t){for(let n of t)this._delegateContextKeyCache.delete(n);this._delegateContextKeyCacheIndex.delete(e)}this._delegateMultiPartyProtocols.delete(e)}else this._delegateDecryptionKeyCache.clear(),this._delegateContextKeyCache.clear(),this._delegateContextKeyCacheIndex.clear(),this._delegateMultiPartyProtocols.clear()}exportDelegateContextKeys(e){let t=this._delegateContextKeyCacheIndex.get(e);if(!t)return[];let n=[],i=`dctx~${e}~`;for(let a of t){let o=this._delegateContextKeyCache.get(a);if(!o||!a.startsWith(i))continue;let s=a.slice(i.length),c=s.lastIndexOf("~");c!==-1&&n.push({protocol:s.slice(0,c),contextId:s.slice(c+1),derivedPrivateKey:o})}return n}exportDelegateMultiPartyProtocols(e){let t=this._delegateMultiPartyProtocols.get(e);return t?[...t]:[]}hasEligibleDelegatesForProtocol(e){for(let[,t]of this._delegateMultiPartyProtocols)if(t.has(e))return!0;return!1}deliverContextKeyToDelegates(e,t,n){for(let[i,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let o=`dctx~${i}~${e}~${t}`;if(this._delegateContextKeyCache.get(o))continue;this._delegateContextKeyCache.set(o,n);let s=this._delegateContextKeyCacheIndex.get(i)??[];s.push(o),this._delegateContextKeyCacheIndex.set(i,s),this._onDelegateContextKeysChanged?.(i)}}async deliverContextKeyToDelegatesViaDwn(e,t,n,i){try{let o=await new _s({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),s=new Set(["Read","Query","Subscribe"]),c=Date.now(),l=new Set;for(let d of o){if(!d.grant.delegated||new Date(d.grant.dateExpires).getTime()<=c)continue;let u=d.grant.scope;if(u.interface!=="Records"||!s.has(u.method)||u.protocolPath||u.contextId)continue;let f=d.grant.grantee,p=d.grant.delegateKeyDelivery;if(!p?.rootKeyId||!p?.publicKeyJwk||l.has(f))continue;let h=p.publicKeyJwk;try{await this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:p.rootKeyId,publicKeyJwk:h}}),l.add(f)}catch(m){console.warn(`AgentDwnApi: Cross-device key delivery to delegate '${f}' for context '${n}' failed: ${m.message}. The delegate may need to reconnect.`)}}}catch(a){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${a.message}`)}}async writeContextKeyRecord(e){return sH(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this))}async eagerSendContextKeyRecord(e,t){return oH(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return aH(this.agent,e,this.processRequest.bind(this))}};g();var fH="dwn",pH="connect";function LVe(r){return`${fH}://${pH}?callback=${encodeURIComponent(r)}`}function Hye(r){let e=JSON.stringify(r);return Jye(e)}function uH(r){try{let e=Zye(r),t=JSON.parse(e);return Vye(t)?t:void 0}catch{return}}function qVe(r){try{let e=`${fH}://`;if(!r.startsWith(e))return;let t=r.slice(e.length),n=t.indexOf("?");if(n===-1||t.slice(0,n)!==pH)return;let a=t.slice(n+1),s=new URLSearchParams(a).get("callback");return!s||s.length===0?void 0:{callback:s}}catch{return}}function zVe(r,e){let t=Hye(e);return`${r.split("#")[0]}#${t}`}function FVe(r){let e=r.indexOf("#");if(e===-1)return uH(r);let t=r.slice(e+1);if(t.length!==0)return uH(t)}function Vye(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Wye(e.endpoint))}function Wye(r){try{let t=new URL(r).hostname.toLowerCase();return!!(t==="127.0.0.1"||t==="::1"||t==="[::1]"||t==="localhost"||t.endsWith(".localhost"))}catch{return!1}}function Jye(r){let e=new TextEncoder().encode(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Zye(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4;t===2?e+="==":t===3&&(e+="=");let n=atob(e),i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new TextDecoder().decode(i)}g();g();pP();Yb();g();n1();Ja();var Yye=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),mH=Uint8Array.from({length:16},(r,e)=>e),Xye=mH.map(r=>(9*r+5)%16),K6=[mH],N6=[Xye];for(let r=0;r<4;r++)for(let e of[K6,N6])e.push(e[r].map(t=>Yye[t]));var yH=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(r=>new Uint8Array(r)),Qye=K6.map((r,e)=>r.map(t=>yH[e][t])),ege=N6.map((r,e)=>r.map(t=>yH[e][t])),tge=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),rge=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),eS=(r,e)=>r<<e|r>>>32-e;function hH(r,e,t,n){return r===0?e^t^n:r===1?e&t|~e&n:r===2?(e|~t)^n:r===3?e&n|t&~n:e^(t|~n)}var tS=new Uint32Array(16),M6=class extends ru{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:n,h3:i,h4:a}=this;return[e,t,n,i,a]}set(e,t,n,i,a){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,t){for(let p=0;p<16;p++,t+=4)tS[p]=e.getUint32(t,!0);let n=this.h0|0,i=n,a=this.h1|0,o=a,s=this.h2|0,c=s,l=this.h3|0,d=l,u=this.h4|0,f=u;for(let p=0;p<5;p++){let h=4-p,m=tge[p],y=rge[p],v=K6[p],w=N6[p],x=Qye[p],_=ege[p];for(let A=0;A<16;A++){let D=eS(n+hH(p,a,s,l)+tS[v[A]]+m,x[A])+u|0;n=u,u=l,l=eS(s,10)|0,s=a,a=D}for(let A=0;A<16;A++){let D=eS(i+hH(h,o,c,d)+tS[w[A]]+y,_[A])+f|0;i=f,f=d,d=eS(c,10)|0,c=o,o=D}}this.set(this.h1+s+d|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+o|0,this.h0+a+c|0)}roundClean(){tS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},gH=rm(()=>new M6);Yg();lP();Ja();em();var nge=Wg("ed25519 seed"),U6=2147483648,wH=new Uint8Array([0]);function vH(r,...e){return typeof r=="string"&&(r=I$(r)),zd(r,...e),r}var ige=r=>gH(su(r)),sge=r=>Gd(r).getUint32(0,!1),L6=r=>{if(!Number.isSafeInteger(r)||r<0||r>2**32-1)throw new Error(`Invalid number=${r}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Gd(e).setUint32(0,r,!1),e},rS=class r{get publicKeyRaw(){return ma.getPublicKey(this.privateKey)}get publicKey(){return Hf(wH,this.publicKeyRaw)}get pubHash(){return ige(this.publicKey)}get fingerprint(){return sge(this.pubHash)}get fingerprintHex(){return GS(L6(this.fingerprint))}get parentFingerprintHex(){return GS(L6(this.parentFingerprint))}static fromMasterSeed(e){if(e=vH(e),8*e.length<128||8*e.length>512)throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);let t=eu(Tu,nge,e);return new r({privateKey:t.slice(0,32),chainCode:t.slice(32)})}constructor(e){if(this.depth=0,this.index=0,this.parentFingerprint=0,!e||typeof e!="object")throw new Error("HDKey.constructor must not be called directly");if(zd(e.privateKey,32),zd(e.chainCode,32),this.depth=e.depth||0,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");this.chainCode=e.chainCode,this.privateKey=e.privateKey}derive(e,t=!1){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;let n=e.replace(/^[mM]'?\//,"").split("/"),i=this;for(let a of n){let o=/^(\d+)('?)$/.exec(a);if(!o||o.length!==3)throw new Error(`Invalid child index: ${a}`);let s=+o[1];if(!Number.isSafeInteger(s)||s>=U6)throw new Error("Invalid index");(t||o[2]==="'")&&(s+=U6),i=i.deriveChild(s)}return i}deriveChild(e){if(e<U6)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Hf(wH,this.privateKey,L6(e)),n=eu(Tu,this.chainCode,t);return new r({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return ma.sign(e,this.privateKey)}verify(e,t){return t=vH(t,64),ma.verify(t,e,this.publicKeyRaw)}};g();var q6=`abandon
11
11
  ability
12
12
  able
13
13
  about
@@ -2057,7 +2057,7 @@ zone
2057
2057
  zoo`.split(`
2058
2058
  `);ea();Sr();g();em();g();em();Yb();Ja();function oge(r,e,t,n){Wb(r);let i=R$({dkLen:32,asyncTick:10},n),{c:a,dkLen:o,asyncTick:s}=i;if(Xl(a),Xl(o),Xl(s),a<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Ql(e),l=Ql(t),d=new Uint8Array(o),u=eu.create(r,c),f=u._cloneInto().update(l);return{c:a,dkLen:o,asyncTick:s,DK:d,PRF:u,PRFSalt:f}}function age(r,e,t,n,i){return r.destroy(),e.destroy(),n&&n.destroy(),i.fill(0),t}async function bH(r,e,t,n){let{c:i,dkLen:a,asyncTick:o,DK:s,PRF:c,PRFSalt:l}=oge(r,e,t,n),d,u=new Uint8Array(4),f=Gd(u),p=new Uint8Array(c.outputLen);for(let h=1,m=0;m<a;h++,m+=c.outputLen){let y=s.subarray(m,m+c.outputLen);f.setInt32(0,h,!1),(d=l._cloneInto(d)).update(u).digestInto(p),y.set(p.subarray(0,y.length)),await D$(i-1,o,()=>{c._cloneInto(d).update(p).digestInto(p);for(let v=0;v<y.length;v++)y[v]^=p[v]})}return age(c,l,s,d,p)}Yg();lP();Ja();g();function Bh(r){if(!Number.isSafeInteger(r))throw new Error(`Wrong integer: ${r}`)}function nS(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function cge(...r){let e=a=>a,t=(a,o)=>s=>a(o(s)),n=r.map(a=>a.encode).reduceRight(t,e),i=r.map(a=>a.decode).reduce(t,e);return{encode:n,decode:i}}function dge(r){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(t=>{if(t<0||t>=r.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${r.length})`);return r[t]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(t=>{if(typeof t!="string")throw new Error(`alphabet.decode: not string element=${t}`);let n=r.indexOf(t);if(n===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${r}`);return n})}}}function lge(r=""){if(typeof r!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let t of e)if(typeof t!="string")throw new Error(`join.encode: non-string input=${t}`);return e.join(r)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(r)}}}function uge(r,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of t)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;t.length*r%8;)t.push(e);return t},decode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of t)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=t.length;if(n*r%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===e;n--)if(!((n-1)*r%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function z6(r,e,t){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(t<2)throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);if(!Array.isArray(r))throw new Error("convertRadix: data should be array");if(!r.length)return[];let n=0,i=[],a=Array.from(r);for(a.forEach(o=>{if(o<0||o>=e)throw new Error(`Wrong integer: ${o}`)});;){let o=0,s=!0;for(let c=n;c<a.length;c++){let l=a[c],d=e*o+l;if(!Number.isSafeInteger(d)||e*o/e!==o||d-l!==e*o)throw new Error("convertRadix: carry overflow");o=d%t;let u=Math.floor(d/t);if(a[c]=u,!Number.isSafeInteger(u)||u*t+o!==d)throw new Error("convertRadix: carry overflow");if(s)u?s=!1:n=c;else continue}if(i.push(o),s)break}for(let o=0;o<r.length-1&&r[o]===0;o++)i.push(0);return i.reverse()}var PH=(r,e)=>e?PH(e,r%e):r,iS=(r,e)=>r+(e-PH(r,e));function F6(r,e,t,n){if(!Array.isArray(r))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(iS(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${iS(e,t)}`);let i=0,a=0,o=2**t-1,s=[];for(let c of r){if(c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(i=i<<e|c,a+e>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${e}`);for(a+=e;a>=t;a-=t)s.push((i>>a-t&o)>>>0);i&=2**a-1}if(i=i<<t-a&o,!n&&a>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&a>0&&s.push(i>>>0),s}function fge(r){return{encode:e=>{if(!nS(e))throw new Error("radix.encode input should be Uint8Array");return z6(Array.from(e),2**8,r)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(z6(e,r,2**8))}}}function pge(r,e=!1){if(r<=0||r>32)throw new Error("radix2: bits should be in (0..32]");if(iS(8,r)>32||iS(r,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!nS(t))throw new Error("radix2.encode input should be Uint8Array");return F6(Array.from(t),8,r,!e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(F6(t,r,8,e))}}}function hge(r,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(t){if(!nS(t))throw new Error("checksum.encode: input should be Uint8Array");let n=e(t).slice(0,r),i=new Uint8Array(t.length+r);return i.set(t),i.set(n,t.length),i},decode(t){if(!nS(t))throw new Error("checksum.decode: input should be Uint8Array");let n=t.slice(0,-r),i=e(n).slice(0,r),a=t.slice(-r);for(let o=0;o<r;o++)if(i[o]!==a[o])throw new Error("Invalid checksum");return n}}}var Eb={alphabet:dge,chain:cge,checksum:hge,convertRadix:z6,convertRadix2:F6,radix:fge,radix2:pge,join:lge,padding:uge};var mge=r=>r[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function xH(r){if(typeof r!="string")throw new TypeError(`Invalid mnemonic type: ${typeof r}`);return r.normalize("NFKD")}function EH(r){let e=xH(r),t=e.split(" ");if(![12,15,18,21,24].includes(t.length))throw new Error("Invalid mnemonic");return{nfkd:e,words:t}}function SH(r){zd(r,16,20,24,28,32)}function kH(r,e=128){if(Xl(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return wge(Vf(e/8),r)}var yge=r=>{let e=8-r.length/4;return new Uint8Array([su(r)[0]>>e<<e])};function _H(r){if(!Array.isArray(r)||r.length!==2048||typeof r[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return r.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),Eb.chain(Eb.checksum(1,yge),Eb.radix2(11,!0),Eb.alphabet(r))}function gge(r,e){let{words:t}=EH(r),n=_H(e).decode(t);return SH(n),n}function wge(r,e){return SH(r),_H(e).encode(r).join(mge(e)?"\u3000":" ")}function AH(r,e){try{gge(r,e)}catch{return!1}return!0}var vge=r=>xH(`mnemonic${r}`);function TH(r,e=""){return bH(Tu,EH(r).nfkd,vge(e),{c:2048,dkLen:64})}g();Pn();g();Sr();Pn();g();Sr();Pn();function kb(r){return typeof r=="object"&&r!==null&&"alg"in r&&r.alg!==void 0&&"enc"in r&&r.enc!==void 0}var Sb=class{static async decrypt({key:e,encryptedKey:t,joseHeader:n,crypto:i},a){let o=a?.minP2cCount??1e3;switch(n.alg){case"dir":{if(t!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');return e}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof n.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(n.p2c<o)throw new Fe(Le.InvalidJwe,`JOSE Header "p2c" (PBES2 Count) is ${n.p2c}, which is below the minimum of ${o}.`);if(typeof n.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');if(t===void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is required when using "PBES2" (Key Encryption Mode).');let s;try{s=new Uint8Array([...he.string(n.alg).toUint8Array(),0,...he.base64Url(n.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let c=await i.deriveKey({algorithm:n.alg,baseKeyBytes:e,iterations:n.p2c,salt:s});if(!(c.alg&&["A128KW","A192KW","A256KW"].includes(c.alg)))throw new Fe(Le.AlgorithmNotSupported,`Unsupported Key Encryption Algorithm (alg) value: ${c.alg}`);return await i.unwrapKey({decryptionKey:c,wrappedKeyBytes:t,wrappedKeyAlgorithm:n.enc})}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${n.alg}`)}}static async encrypt({key:e,joseHeader:t,crypto:n}){let i,a;switch(t.alg){case"dir":{if(a!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');i=e;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof t.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(typeof t.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');i=await n.generateKey({algorithm:t.enc});let o;try{o=new Uint8Array([...he.string(t.alg).toUint8Array(),0,...he.base64Url(t.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let s=await n.deriveKey({algorithm:t.alg,baseKeyBytes:e,iterations:t.p2c,salt:o});a=await n.wrapKey({encryptionKey:s,unwrappedKey:i});break}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${t.alg}`)}return{cek:i,encryptedKey:a}}};function G6(r,e){if(e!==void 0)try{if(typeof e!="string")throw new Error;return he.base64Url(e).toUint8Array()}catch{throw new Fe(Le.InvalidJwe,`Failed to decode the JWE Header parameter '${r}' from Base64 URL format to Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.`)}}var _b=class r{constructor(e){this.ciphertext="";Object.assign(this,e)}static async decrypt({jwe:e,key:t,keyManager:n=new Xc,crypto:i=new xo,options:a={}}){if(!nv(i))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!nv(n))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!e.protected&&!e.header&&!e.unprotected)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protected", "header", or "unprotected"');if(typeof e.ciphertext!="string")throw new Fe(Le.InvalidJwe,"JWE Ciphertext is missing or not a string.");let o;if(e.protected)try{o=he.base64Url(e.protected).toObject()}catch{throw new Error("JWE Protected Header is invalid")}if(IH(o,e.header,e.unprotected))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "header", "protected", and "unprotected" objects.');let s={...o,...e.header,...e.unprotected};if(!kb(s))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');if(Array.isArray(a.allowedAlgValues)&&!a.allowedAlgValues.includes(s.alg))throw new Error(`"alg" (Algorithm) Header Parameter value not allowed: ${s.alg}`);if(Array.isArray(a.allowedEncValues)&&!a.allowedEncValues.includes(s.enc))throw new Error(`"enc" (Encryption Algorithm) Header Parameter value not allowed: ${s.enc}`);let c;try{let h=e.encrypted_key?he.base64Url(e.encrypted_key).toUint8Array():void 0;c=await Sb.decrypt({key:t,encryptedKey:h,joseHeader:s,keyManager:n,crypto:i},{minP2cCount:a.minP2cCount})}catch(h){if(h instanceof Fe&&(h.code===Le.InvalidJwe||h.code===Le.AlgorithmNotSupported))throw h;c=typeof t=="string"?await n.generateKey({algorithm:s.enc}):await i.generateKey({algorithm:s.enc})}let l=G6("iv",e.iv),d=G6("tag",e.tag),u=d!==void 0?new Uint8Array([...he.base64Url(e.ciphertext).toUint8Array(),...d??[]]):he.base64Url(e.ciphertext).toUint8Array(),f=e.aad!==void 0?new Uint8Array([...he.string(e.protected??"").toUint8Array(),...he.string(".").toUint8Array(),...he.string(e.aad).toUint8Array()]):he.string(e.protected??"").toUint8Array();return{plaintext:typeof c=="string"?await n.decrypt({keyUri:c,data:u,iv:l,additionalData:f}):await i.decrypt({key:c,data:u,iv:l,additionalData:f}),protectedHeader:o,additionalAuthenticatedData:G6("aad",e.aad),sharedUnprotectedHeader:e.unprotected,unprotectedHeader:e.header}}static async encrypt({key:e,plaintext:t,additionalAuthenticatedData:n,protectedHeader:i,sharedUnprotectedHeader:a,unprotectedHeader:o,keyManager:s=new Xc,crypto:c=new xo}){if(!nv(c))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!nv(s))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!i&&!a&&!o)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protectedHeader", "sharedUnprotectedHeader", or "unprotectedHeader"');if(!(t instanceof Uint8Array))throw new Fe(Le.InvalidJwe,"Plaintext is missing or not a byte array.");if(IH(i,a,o))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "protectedHeader", "sharedUnprotectedHeader", and "unprotectedHeader" objects.');let l={...i,...a,...o};if(!kb(l))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');let{cek:d,encryptedKey:u}=await Sb.encrypt({key:e,joseHeader:l,keyManager:s,crypto:c}),f;switch(l.enc){case"A128GCM":case"A192GCM":case"A256GCM":f=bn.randomBytes(12);break;default:f=new Uint8Array(0)}let p=i?he.object(i).toBase64Url():"",h,m;n?(m=he.uint8Array(n).toBase64Url(),h=he.string(p+"."+m).toUint8Array()):h=he.string(p).toUint8Array();let y=typeof d=="string"?await s.encrypt({keyUri:d,data:t,iv:f,additionalData:h}):await c.encrypt({key:d,data:t,iv:f,additionalData:h}),v=y.slice(0,-16),w=y.slice(-16),x=new r({ciphertext:he.uint8Array(v).toBase64Url()});return u&&(x.encrypted_key=he.uint8Array(u).toBase64Url()),i&&(x.protected=p),a&&(x.unprotected=a),o&&(x.header=o),f&&(x.iv=he.uint8Array(f).toBase64Url()),m&&(x.aad=m),w&&(x.tag=he.uint8Array(w).toBase64Url()),x}};function IH(...r){let e=new Set,t=r.filter(Boolean);for(let n of t)for(let i in n){if(e.has(i))return!0;e.add(i)}return!1}var Rc=class{static async decrypt({jwe:e,key:t,keyManager:n=new Xc,crypto:i=new xo,options:a={}}){if(typeof e!="string")throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must be a string.");let{0:o,1:s,2:c,3:l,4:d,length:u}=e.split(".");if(u!==5)throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must have 5 parts.");let f=await _b.decrypt({jwe:{ciphertext:l,encrypted_key:s||void 0,iv:c||void 0,protected:o,tag:d||void 0},key:t,keyManager:n,crypto:i,options:a});if(!kb(f.protectedHeader))throw new Fe(Le.InvalidJwe,"Decrypt operation failed due to missing or malformed JWE Protected Header");return{plaintext:f.plaintext,protectedHeader:f.protectedHeader}}static async encrypt({plaintext:e,protectedHeader:t,key:n,keyManager:i=new Xc,crypto:a=new xo,options:o={}}){let s=await _b.encrypt({plaintext:e,protectedHeader:t,key:n,keyManager:i,crypto:a,options:o});return[s.protected,s.encrypted_key,s.iv,s.ciphertext,s.tag].join(".")}};g();Pn();Pn();Xn();g();Sr();Pn();var yg=class extends Of{constructor(){super(...arguments);this.name="DwnKeyStore";this._recordProtocolDefinition=YG;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"privateJwk",schema:this._recordProtocolDefinition.types.privateJwk.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async set(t){await super.set(t)}async list(t){return await super.list(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){let s;if(o.encryption){let{reply:c}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:o.recordId}},encryption:!0}),l=c;if(!l.entry?.data)throw new Error(`${this.name}: Failed to read encrypted key record: ${o.recordId}`);s=await Bm.consumeToJson({readableStream:l.entry.data})}else{if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);s=he.base64Url(o.encodedData).toObject()}if(bp(s)){let c=`${n}${Ri}${vp}${s.kid}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},gg=class extends jf{constructor(){super(...arguments);this.name="InMemoryKeyStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};var H6={"AES-GCM":{implementation:Mm,names:["A128GCM","A192GCM","A256GCM"]},"AES-KW":{implementation:Km,names:["A128KW","A192KW","A256KW"]},Ed25519:{implementation:Yc,names:["Ed25519"]},secp256k1:{implementation:fc,names:["ES256K","secp256k1"]},secp256r1:{implementation:fc,names:["ES256","secp256r1"]},"SHA-256":{implementation:Iu,names:["SHA-256"]},X25519:{implementation:Ru,names:["X25519"]}},As=class{constructor({agent:e,keyStore:t}={}){this._algorithmInstances=new Map;this._agent=e,this._keyStore=t??new gg}get agent(){if(this._agent===void 0)throw new Error("LocalKeyManager: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}async decrypt({keyUri:e,...t}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).decrypt({key:n,...t})}digest(e){throw new Error("Method not implemented.")}async encrypt({keyUri:e,...t}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).encrypt({key:n,...t})}async exportKey({keyUri:e}){return await this.getPrivateKey({keyUri:e})}async generateKey({algorithm:e}){let t=this.getAlgorithmName({key:{alg:e}}),i=await this.getAlgorithm({algorithm:t}).generateKey({algorithm:e});i.kid??=await vt({jwk:i});let a=await this.getKeyUri({key:i});return await this._keyStore.set({id:a,data:i,agent:this.agent,preventDuplicates:!1,useCache:!0}),a}async getKeyUri({key:e}){let t=await vt({jwk:e});return`${vp}${t}`}async getPublicKey({keyUri:e}){let t=await this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:t});return await this.getAlgorithm({algorithm:n}).getPublicKey({key:t})}async derivePublicKey({keyUri:e,derivationPath:t}){let n=await this.getX25519PrivateKeyBytes({keyUri:e}),i=await Ni.derivePrivateKeyBytes(n,t),a=await At.bytesToPrivateKey({privateKeyBytes:i});return await At.getPublicKey({key:a})}async jweKeyUnwrap({keyUri:e,derivationPath:t,encryptedKey:n,ephemeralPublicKey:i}){let a=await this.getX25519PrivateKeyBytes({keyUri:e}),o=await Ni.derivePrivateKeyBytes(a,t),s=await At.bytesToPrivateKey({privateKeyBytes:o});return Ei.ecdhEsUnwrapKey(s,i,n)}async derivePrivateKeyBytes({keyUri:e,derivationPath:t}){let n=await this.getX25519PrivateKeyBytes({keyUri:e});return Ni.derivePrivateKeyBytes(n,t)}async importKey({key:e}){if(!bp(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let t=structuredClone(e);t.kid??=await vt({jwk:t});let n=await this.getKeyUri({key:t});return await this._keyStore.set({id:n,data:t,agent:this.agent,preventDuplicates:!0,useCache:!0}),n}async sign({keyUri:e,data:t}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:t,key:n})}async unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:t,decryptionKeyUri:n}){let i=await this.getPrivateKey({keyUri:n}),a=this.getAlgorithmName({key:i});return await this.getAlgorithm({algorithm:a}).unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:t,decryptionKey:i})}async verify({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})}async wrapKey({unwrappedKey:e,encryptionKeyUri:t}){let n=await this.getPrivateKey({keyUri:t}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).wrapKey({unwrappedKey:e,encryptionKey:n})}async deleteKey({keyUri:e}){if(!await this._keyStore.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`Key not found: ${e}`);await this._keyStore.delete({id:e,agent:this.agent})}getAlgorithm({algorithm:e}){let t=H6[e]?.implementation;if(!t)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({key:e}){let t=e.alg,n=e.crv;for(let i of Object.keys(H6)){let a=H6[i].names;if(t&&a.includes(t))return i;if(n&&a.includes(n))return i}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${t}, crv=${n}. Please check the documentation for the list of supported algorithms.`)}async getX25519PrivateKeyBytes({keyUri:e}){let t=await this.getPrivateKey({keyUri:e});return At.privateKeyToBytes({privateKey:t})}async getPrivateKey({keyUri:e}){try{let n=this.agent?.agentDid?.keyManager;if(n&&typeof n.exportKey=="function"){let i=await n.exportKey({keyUri:e});if(i&&bp(i))return i}}catch{}let t=await this._keyStore.get({id:e,agent:this.agent,useCache:!0});if(!t)throw new Error(`Key not found: ${e}`);return t}};function DH(r){return typeof r!="string"||r.trim().length===0}function bge(r){return typeof r=="object"&&r!==null&&"dateCreated"in r&&typeof r.dateCreated=="string"&&"size"in r&&typeof r.size=="number"&&"data"in r&&typeof r.data=="string"}function Pge(r){return typeof r=="object"&&r!==null&&"initialized"in r&&typeof r.initialized=="boolean"&&"lastBackup"in r&&"lastRestore"in r}var Oh=class{constructor({keyDerivationWorkFactor:e,store:t}={}){this.crypto=new xo;this._keyDerivationWorkFactor=e??21e4,this._store=t??new xu}async backup(){if(this.isLocked()||await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the backup operation because the identity vault has not been initialized and unlocked. Please ensure the vault is properly initialized with a secure password before attempting to backup its contents.");let e={did:await this.getStoredDid(),contentEncryptionKey:await this.getStoredContentEncryptionKey(),status:await this.getStatus()},t=he.object(e).toBase64Url(),n={data:t,dateCreated:new Date().toISOString(),size:t.length};return await this.setStatus({lastBackup:n.dateCreated}),n}async changePassword({oldPassword:e,newPassword:t}){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the change password operation because the identity vault has not been initialized. Please ensure the vault is properly initialized with a secure password before trying again.");await this.lock();let n=await this.getStoredContentEncryptionKey(),i,a;try{let s;({plaintext:s,protectedHeader:i}=await Rc.decrypt({jwe:n,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}})),a=he.uint8Array(s).toObject()}catch{throw new Error("HdIdentityVault: Unable to change the vault password due to an incorrectly entered old password.")}let o=await Rc.encrypt({key:he.string(t).toUint8Array(),protectedHeader:i,plaintext:he.object(a).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",o),this._contentEncryptionKey=a}async getDid(){if(this.isLocked())throw new Error("HdIdentityVault: Vault has not been initialized and unlocked.");let e=await this.getStoredDid(),{plaintext:t}=await Rc.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),n=he.uint8Array(t).toObject();if(!Ph(n))throw new Error("HdIdentityVault: Unable to decode malformed DID in identity vault");return await Ss.import({portableDid:n})}async getStatus(){let e=await this._store.get("vaultStatus");if(!e)return{initialized:!1,lastBackup:null,lastRestore:null};let t=he.string(e).toObject();if(!Pge(t))throw new Error("HdIdentityVault: Invalid IdentityVaultStatus object in store");return t.initialized&&(this._cachedInitialized=!0),t}async initialize({password:e,recoveryPhrase:t,dwnEndpoints:n}){if(await this.isInitialized())throw new Error("HdIdentityVault: Vault has already been initialized.");if(DH(e))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2059
2059
  'valid, non-empty password.`);if(t&&DH(t))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2060
- 'valid, non-empty password.`);if(t??=kH(q6,128),!AH(t,q6))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await TH(t),a=rS.fromMasterSeed(i),o=a.derive("m/44'/0'/0'/0'/0'"),s=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:o.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:o.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await Rc.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(s).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",d);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),p=a.derive("m/44'/0'/1708523827'/0'/1'"),h=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:p.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),v=new VE;await v.addPredefinedKeys({privateKeys:[f,h,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let _=await(await vo.create({keyManager:v,options:w})).export(),A={alg:"dir",enc:"A256GCM",cty:"json"},D=await Rc.encrypt({key:s,plaintext:he.object(_).toUint8Array(),protectedHeader:A,crypto:this.crypto,keyManager:new As});return await this._store.set("did",D),this._contentEncryptionKey=s,await this.setStatus({initialized:!0}),t}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:t}){if(!bge(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let o=he.base64Url(e.data).toObject();await this._store.set("did",o.did),await this._store.set("contentEncryptionKey",o.contentEncryptionKey),await this.setStatus(o.status),await this.unlock({password:t})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let t=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Rc.decrypt({jwe:t,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async encryptData({plaintext:e}){if(this.isLocked()||!this._contentEncryptionKey)throw new Error("HdIdentityVault: Cannot encrypt data \u2014 vault is locked.");return Rc.encrypt({key:this._contentEncryptionKey,plaintext:e,protectedHeader:{alg:"dir",enc:"A256GCM"},crypto:this.crypto,keyManager:new As})}async decryptData({jwe:e}){if(this.isLocked()||!this._contentEncryptionKey)throw new Error("HdIdentityVault: Cannot decrypt data \u2014 vault is locked.");let{plaintext:t}=await Rc.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}});return t}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:t,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=t??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();ea();g();Sr();function xge(r){return!(!r||typeof r!="object"||r===null)&&"name"in r}var wg=class extends Of{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=HE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async set(t){return await super.set(t)}async list(t){return await super.list(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(xge(s)){let c=`${n}${Ri}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},vg=class extends jf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};function PJe(r){return!(!r||typeof r!="object"||r===null)&&"did"in r&&"metadata"in r&&Ph(r.did)}var jh=class{constructor({agent:e,store:t}={}){this._agent=e,this._store=t??new vg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:t="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:t,options:n,tenant:this.tenant,store:i}),o=new lg({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:o.did.uri,data:o.metadata,agent:this.agent,tenant:o.metadata.tenant,preventDuplicates:!1,useCache:!0}),o}async export({didUri:e}){let t=await this.get({didUri:e});if(!t)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await t.export()}async get({didUri:e}){let t=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!t)return;let n=await this.agent.did.get({didUri:e,tenant:t.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new lg({did:n,metadata:t})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let t=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!t)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new lg({did:t,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let t=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(t.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:t}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(o=>o.id.endsWith("dwn"));if(a)a.serviceEndpoint=t;else{let o={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:t};i.document.service?i.document.service.push(o):i.document.service=[o]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:t}){if(!t)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===t)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:t},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let t=await this.list();if(!(t.length<1))return e?t.find(n=>n.metadata.connectedDid===e):t.find(n=>n.metadata.connectedDid!==void 0)}};g();var MH=Tn(JE(),1);Xn();import{Level as Tge}from"level";g();function Ege(r){let e=[],t=[];for(let n of r)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?t.push(n.messageCid):e.push(n):t.push(n.messageCid);return{prefetched:e,needsFetchCids:t}}var sS=class{constructor(e){this._deps=e}async reconcile(e,t){let{did:n,dwnUrl:i,delegateDid:a,protocol:o}=e,s=t?.direction,c=t?.verifyConvergence??!1,l=this._deps.shouldContinue,d=await this._deps.getLocalRoot(n,a,o);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let u=await this._deps.getRemoteRoot(n,i,a,o);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=!1,p=!1,h;if(d!==u){let v=await this._deps.diffWithRemote(e);if(l&&!l())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:d,remoteRoot:u};if((!s||s==="pull")&&v.onlyRemote.length>0){let{prefetched:w,needsFetchCids:x}=Ege(v.onlyRemote);if(await this._deps.pullMessages({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:x,prefetched:w}),l&&!l())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:d,remoteRoot:u};f=!0}if((!s||s==="push")&&v.onlyLocal.length>0){if(h=await this._deps.pushMessages({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:v.onlyLocal}),l&&!l())return{aborted:!0,changed:!0,didPull:f,didPush:!0,localRoot:d,remoteRoot:u,pushResult:h};p=!0}}if(!c)return{changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h};let m=await this._deps.getLocalRoot(n,a,o);if(l&&!l())return{aborted:!0,changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h};let y=await this._deps.getRemoteRoot(n,i,a,o);return l&&!l()?{aborted:!0,changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h}:{changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,postLocalRoot:m,postRemoteRoot:y,converged:m===y,pushResult:h}}};g();Xn();function RH(r){let e=r.descriptor;return e.interface!==ve.Records||e.method!==me.Write?!1:e.dateCreated===e.messageTimestamp}function bg(r){if(r.length<=1)return r;let e=new Map,t=new Map,n=new Map,i=new Map;for(let d=0;d<r.length;d++){let u=r[d];e.set(d,u);let f=u.message.descriptor;if(f.interface===ve.Protocols&&f.method===me.Configure){let p=f.definition?.protocol;p&&t.set(p,d)}if(f.interface===ve.Records&&f.method===me.Write){let p=u.message.recordId;RH(u.message)&&p&&n.set(p,d),f.protocol===rt.uri&&f.protocolPath===rt.grantPath&&p&&i.set(p,d)}}let a=new Map,o=new Array(r.length).fill(0),s=(d,u)=>{if(d===u)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(u)||(f.add(u),o[u]++)};for(let d=0;d<r.length;d++){let u=r[d].message.descriptor;if(u.interface===ve.Records){let p=u.protocol;p&&t.has(p)&&s(t.get(p),d)}if(u.interface===ve.Records&&u.parentId){let p=u.parentId;n.has(p)&&s(n.get(p),d)}if(u.interface===ve.Records&&u.method===me.Write){let p=r[d].message.recordId;p&&!RH(r[d].message)&&n.has(p)&&s(n.get(p),d)}if(u.interface===ve.Records&&u.method===me.Delete){let p=u.recordId;p&&n.has(p)&&s(n.get(p),d)}let f=u.permissionGrantId;f&&i.has(f)&&s(i.get(f),d)}let c=[];for(let d=0;d<r.length;d++)o[d]===0&&c.push(d);let l=[];for(;c.length>0;){let d=c.shift();l.push(e.get(d));let u=a.get(d);if(u)for(let f of u)o[f]--,o[f]===0&&c.push(f)}if(l.length<r.length){let d=new Set(l);for(let u=0;u<r.length;u++){let f=e.get(u);d.has(f)||l.push(f)}}return l}g();var oS="^";function CH(r,e,t){return`${r}${oS}${e}${oS}${t}`}function Ab(r,e,t){let n=`${r}${oS}${e}`;return t?`${n}${oS}${t}`:n}g();Xn();var Sge=1048576;function $H(r){return r.status.code===202||r.status.code===204||r.status.code===409||r.entry?.message.descriptor.interface===ve.Records&&r.entry?.message.descriptor.method===me.Delete&&r.status.code===404}function kge(r){return r.status.code===400||r.status.code===401||r.status.code===403}async function V6(r){try{return await ye.getCid(r)}catch{return"unknown"}}async function BH({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,prefetched:a,agent:o,permissionsApi:s}){let c=[];if(a)for(let m of a){if(!m.message)continue;let y={message:m.message};if(m.encodedData){let v=De.base64UrlToBytes(m.encodedData);y.bufferedData=v,y.dataStream=new ReadableStream({start(w){w.enqueue(v),w.close()}})}c.push(y)}let l=i.length>0?await aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:o,permissionsApi:s}):[],d=[...c,...l],u=bg(d);await _ge(u);let f=3,p=u;for(let m=0;m<=f&&p.length>0;m++){let y=[];for(let v of p){let w=v.bufferedData?new ReadableStream({start(_){_.enqueue(v.bufferedData),_.close()}}):v.dataStream,x=await o.dwn.processRawMessage(r,v.message,{dataStream:w});$H(x)||y.push(v)}if(y.length>0){let v=[],w=[];for(let x of y)if(x.bufferedData||!x.dataStream)w.push(x);else{let _=await V6(x.message);v.push(_)}if(v.length>0){let x=await aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:v,agent:o,permissionsApi:s});w.push(...x)}p=bg(w)}else p=[]}let h=[];for(let m of p){let y=await V6(m.message);h.push(y)}return h}async function _ge(r){for(let e of r){if(!e.dataStream)continue;let t=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)break;if(n+=l.byteLength,n>Sge){i=!0;break}t.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let o=new Uint8Array(n),s=0;for(let c of t)o.set(c,s),s+=c.byteLength;e.bufferedData=o,e.dataStream=new ReadableStream({start(c){c.enqueue(o),c.close()}})}}async function aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c;t&&(c=(await o.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:t,protocol:n,cached:!0})).grant.id);let l=4,d=0;for(;d<i.length;){let u=i.slice(d,d+l);d+=l;let f=await Promise.all(u.map(async p=>{let h=await a.processDwnRequest({store:!1,author:r,target:r,messageType:Re.MessagesRead,granteeDid:t,messageParams:{messageCid:p,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:r,message:h.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,v;return jd(y)&&y.data&&(v=y.data),{message:y.message,dataStream:v}}));for(let p of f)p&&s.push(p)}return s}async function W6({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c=[],l=[],d=[];for(let f of i){let p=await Age({author:r,messageCid:f,delegateDid:t,protocol:n,agent:a,permissionsApi:o});p?d.push(p):c.push(f)}let u=bg(d);for(let f of u){let p=await V6(f.message);try{let h=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:r,data:f.dataStream,message:f.message});$H(h)?s.push(p):kge(h)?(h.status.code===400&&h.status.detail?.includes("record limit")?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${p}`):console.warn(`SyncEngineLevel: push permanently failed for ${p}: ${h.status.code} ${h.status.detail}`),l.push({cid:p,statusCode:h.status.code,detail:h.status.detail??""})):(console.error(`SyncEngineLevel: push failed for ${p}: ${h.status.code} ${h.status.detail}`),c.push(p))}catch(h){console.error(`SyncEngineLevel: push error for ${p}: ${h.message??h}`),c.push(p)}}return{succeeded:s,failed:c,permanentlyFailed:l}}async function Age({author:r,delegateDid:e,protocol:t,messageCid:n,agent:i,permissionsApi:a}){let o;e&&(o=(await a.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:e,protocol:t,cached:!0})).grant.id);let{reply:s}=await i.dwn.processRequest({author:r,target:r,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:o}});if(s.status.code!==200||!s.entry)return;let c=s.entry,l={message:c.message};return jd(c)&&c.data&&(l.dataStream=c.data),l}var Ige=16,OH=8,Dge=100;function jH(r,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let t=r.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=t.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=r.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var jn=class jn{constructor({agent:e,dataPath:t,db:n}){this._syncLock=!1;this._activeLinks=new Map;this._linkRuntimes=new Map;this._syncMode="poll";this._engineGeneration=0;this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._eventListeners=new Set;this._pushRuntimes=new Map;this._recentlyPulledCids=new Map;this._closureContexts=new Map;this._consecutiveFailures=0;this._degradedPollTimers=new Map;this._repairAttempts=new Map;this._activeRepairs=new Map;this._repairRetryTimers=new Map;this._repairContext=new Map;this._reconcileTimers=new Map;this._reconcileInFlight=new Map;this._agent=e,this._permissionsApi=new _s({agent:e}),this._db=n||new Tge(t??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new as(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new _s({agent:e})}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,t=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(t=!0);return e?"online":t?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let t of this._eventListeners)try{t(e)}catch{}}async clear(){await this.teardownLiveSync(),await this._permissionsApi.clear(),await this._db.clear()}async close(){await this.teardownLiveSync(),await this._db.close()}async registerIdentity({did:e,options:t}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);t??={protocols:[]},await n.put(e,JSON.stringify(t))}async unregisterIdentity(e){let t=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await t.del(e)}async getIdentityOptions(e){let t=this._db.sublevel("registeredIdentities");try{let n=await t.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:t}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(t))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let t=await this.getSyncTargets(),n=new Map;for(let s of t){let c=n.get(s.dwnUrl);c||(c=[],n.set(s.dwnUrl,c)),c.push(s)}let i=0,a=0,o=await Promise.allSettled([...n.entries()].map(async([s,c])=>{for(let l of c){let{did:d,delegateDid:u,protocol:f}=l;try{await this.createLinkReconciler().reconcile({did:d,dwnUrl:s,delegateDid:u,protocol:f},{direction:e})}catch(p){a++,console.error(`SyncEngineLevel: Error syncing ${d} with ${s}`,p);return}}i++}));for(let s of o)s.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):t.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}}async startSync(e){let t=e.mode??"poll",n=e.interval??(t==="live"?"5m":"2m"),i=(0,MH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=t,t==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){this._engineGeneration++;let t=0;for(;this._syncLock;){if(t>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);t+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let t=this._engineGeneration,n=async()=>{if(this._engineGeneration!==t||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(o){console.error("SyncEngineLevel: Error during sync operation",o)}let i=Math.min(Math.pow(2,this._consecutiveFailures),jn.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===t&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||await this.sync()}async startLiveSync(e){this.startBrowserConnectivityListeners();try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let t=await this.getSyncTargets();await Promise.allSettled(t.map(async i=>{let a;try{let o=i.protocol?{kind:"protocol",protocol:i.protocol}:{kind:"full"};a=await this.ledger.getOrCreateLink({tenantDid:i.did,remoteEndpoint:i.dwnUrl,scope:o,delegateDid:i.delegateDid,protocol:i.protocol});let s=this.buildLinkKey(i.did,i.dwnUrl,a.scopeId);if(!a.pull.contiguousAppliedToken){let l=Ab(i.did,i.dwnUrl,i.protocol),d=await this.getCursor(l);d&&(as.resetCheckpoint(a.pull,d),await this.ledger.saveLink(a),await this.deleteLegacyCursor(l))}this._activeLinks.set(s,a);let c={...i,linkKey:s};await this.openLivePullSubscription(c);try{await this.openLocalPushSubscription(c)}catch(l){let d=this._liveSubscriptions.find(u=>u.linkKey===s);if(d){try{await d.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(u=>u!==d)}throw l}this.emitEvent({type:"link:status-change",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,from:"initializing",to:"live"}),await this.ledger.setStatus(a,"live"),a.needsReconcile&&this.scheduleReconcile(s,1e3)}catch(o){let s=a?this.buildLinkKey(i.did,i.dwnUrl,a.scopeId):Ab(i.did,i.dwnUrl,i.protocol);if(o.isProgressGap&&a){console.warn(`SyncEngineLevel: ProgressGap detected for ${i.did} -> ${i.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,reason:"ProgressGap"});let c=o.gapInfo;await this.transitionToRepairing(s,a,{resumeToken:c?.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,o),this._activeLinks.delete(s),this._linkRuntimes.delete(s),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}}));let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}getOrCreateRuntime(e){let t=this._linkRuntimes.get(e);return t||(t={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,t)),t}drainCommittedPull(e){let t=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!t||!n)return 0;let i=0;for(;;){let a=t.inflight.get(t.nextCommitOrdinal);if(!a||!a.committed)break;as.commitContiguousToken(n.pull,a.token),as.setReceivedToken(n.pull,a.token),t.inflight.delete(t.nextCommitOrdinal),t.nextCommitOrdinal++,i++}return i}async transitionToRepairing(e,t,n){let i=t.status,a=t.connectivity;t.connectivity="offline",await this.ledger.setStatus(t,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let o=this._linkRuntimes.get(e);o&&(o.inflight.clear(),o.nextCommitOrdinal=o.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})}scheduleRepairRetry(e){let t=this._activeLinks.get(e);if(!t||t.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let n=this._repairAttempts.get(e)??1,i=jn.REPAIR_BACKOFF_MS,a=i[Math.min(n-1,i.length-1)],o=this._engineGeneration,s=setTimeout(async()=>{if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let c=this._activeLinks.get(e);if(!(!c||c.status!=="repairing"))try{await this.repairLink(e)}catch{c.status==="repairing"&&this.scheduleRepairRetry(e)}},a);this._repairRetryTimers.set(e,s)}repairLink(e){let t=this._activeRepairs.get(e);if(t)return t;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}async doRepairLink(e){let t=this._activeLinks.get(e);if(!t)return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:o,protocol:s}=t;this.emitEvent({type:"repair:started",tenantDid:i,remoteEndpoint:a,protocol:s,attempt:(this._repairAttempts.get(e)??0)+1});let c=(this._repairAttempts.get(e)??0)+1;if(this._repairAttempts.set(e,c),await this.closeLinkSubscriptions(t),this._engineGeneration!==n)return;let l=this.getOrCreateRuntime(e);l.inflight.clear(),l.nextDeliveryOrdinal=0,l.nextCommitOrdinal=0;try{if((await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:o,protocol:s})).aborted)return;let f=this._repairContext.get(e)?.resumeToken??t.pull.contiguousAppliedToken;if(as.resetCheckpoint(t.pull,f),await this.ledger.saveLink(t),this._engineGeneration!==n||(t.needsReconcile=!0,await this.ledger.saveLink(t),this._engineGeneration!==n))return;let p={did:i,dwnUrl:a,delegateDid:o,protocol:s,linkKey:e};try{await this.openLivePullSubscription(p)}catch(y){if(y.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${i} -> ${a}, resetting to start fresh`),as.resetCheckpoint(t.pull),await this.ledger.saveLink(t),this._engineGeneration!==n)return;await this.openLivePullSubscription(p)}else throw y}if(this._engineGeneration!==n)return;try{await this.openLocalPushSubscription(p)}catch(y){let v=this._liveSubscriptions.find(w=>w.linkKey===e);if(v){try{await v.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(w=>w!==v)}throw y}if(this._engineGeneration!==n)return;this._repairContext.delete(e),this._repairAttempts.delete(e);let h=this._repairRetryTimers.get(e);h&&(clearTimeout(h),this._repairRetryTimers.delete(e));let m=t.connectivity;t.connectivity="online",await this.ledger.setStatus(t,"live"),this.clearDeadLettersForLink(i,a,s),this.emitEvent({type:"repair:completed",tenantDid:i,remoteEndpoint:a,protocol:s}),m!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:i,remoteEndpoint:a,protocol:s,from:m,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:i,remoteEndpoint:a,protocol:s,from:"repairing",to:"live"})}catch(d){if(this._engineGeneration!==n)return;if(console.error(`SyncEngineLevel: Repair failed for ${i} -> ${a} (attempt ${c})`,d),this.emitEvent({type:"repair:failed",tenantDid:i,remoteEndpoint:a,protocol:s,attempt:c,error:String(d.message??d)}),c>=jn.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${i} -> ${a}, entering degraded_poll`),await this.enterDegradedPoll(e);return}throw d}}async closeLinkSubscriptions(e){let{tenantDid:t,remoteEndpoint:n}=e,i=this.buildLinkKey(t,n,e.scopeId),a=this._liveSubscriptions.find(s=>s.linkKey===i);if(a){try{await a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(s=>s!==a)}let o=this._localSubscriptions.find(s=>s.linkKey===i);if(o){try{await o.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(s=>s!==o)}}async enterDegradedPoll(e){let t=this._activeLinks.get(e);if(!t)return;t.connectivity="offline";let n=t.status;await this.ledger.setStatus(t,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,o=Math.floor(Math.random()*15e3),s=a+o,c=this._engineGeneration,l=setInterval(async()=>{if(this._engineGeneration!==c){clearInterval(l),this._degradedPollTimers.delete(e);return}if(t.status!=="degraded_poll"){clearInterval(l),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),await this.ledger.setStatus(t,"repairing"),await this.repairLink(e),t.status==="live"&&(clearInterval(l),this._degradedPollTimers.delete(e))}catch{await this.ledger.setStatus(t,"degraded_poll")}},s);this._degradedPollTimers.set(e,l)}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(t=>{console.error("SyncEngineLevel: post-online sync failed",t)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let t of this._activeLinks.values()){let n=t.connectivity;n!=="offline"&&(t.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(t=>{console.error("SyncEngineLevel: post-visibility sync failed",t)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}async teardownLiveSync(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()}async openLivePullSubscription(e){let{did:t,delegateDid:n,dwnUrl:i,protocol:a}=e,o=e.linkKey,s=this._activeLinks.get(o),c=s?.pull.contiguousAppliedToken;c&&(!c.streamId||!c.messageCid||!c.epoch||!c.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${t} -> ${i}`),c=void 0,s&&(as.resetCheckpoint(s.pull),await this.ledger.saveLink(s)));let l=s?.scope.kind==="protocol"?s.scope.protocolPathPrefixes?.[0]:void 0,d=a?[{protocol:a,...l?{protocolPathPrefix:l}:{}}]:[],u;n&&(u=(await this._permissionsApi.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let f=this._engineGeneration,p=async A=>{if(this._engineGeneration===f){if(A.type==="eose"){if(s){if(s.status!=="live"&&s.status!=="initializing")return;if(!as.validateTokenDomain(s.pull,A.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s);return}as.setReceivedToken(s.pull,A.cursor),this.drainCommittedPull(o),await this.ledger.saveLink(s)}if(s){let D=s.connectivity;s.connectivity="online",D!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t,remoteEndpoint:i,protocol:a,from:D,to:"online"}),s.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(A.type==="event"){let D=A.event;if(s&&s.status!=="live"&&s.status!=="initializing")return;if(s&&!as.validateTokenDomain(s.pull,A.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s);return}if(s&&!jH(D.message,s.scope)){as.setReceivedToken(s.pull,A.cursor),as.commitContiguousToken(s.pull,A.cursor),await this.ledger.saveLink(s);return}let N=s?this.getOrCreateRuntime(o):void 0,$=N?N.nextDeliveryOrdinal++:-1;N&&N.inflight.set($,{ordinal:$,token:A.cursor,committed:!1});try{let z=this.extractDataStream(D);if(!z&&jd(D)&&D.message.descriptor.dataCid){let H=await ye.getCid(D.message),Y=await aS({did:t,dwnUrl:i,delegateDid:n,protocol:a,messageCids:[H],agent:this.agent,permissionsApi:this._permissionsApi});Y.length>0&&Y[0].dataStream&&(z=Y[0].dataStream)}await this.agent.dwn.processRawMessage(t,D.message,{dataStream:z});let L=this._closureContexts.get(t);if(L&&HG(L,D.message),s&&s.scope.kind==="protocol"){let H=this.agent.dwn.node.storage.messageStore,Y=this._closureContexts.get(t);Y||(Y=wb(t),this._closureContexts.set(t,Y));let R=await GE(D.message,H,s.scope,Y);if(!R.complete){let C=R.failure.code,P=R.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${t} -> ${i}: ${C} \u2014 ${P}`);let S=await ye.getCid(D.message);this.recordDeadLetter({messageCid:S,tenantDid:t,remoteEndpoint:i,protocol:a,category:"closure",errorCode:C,errorDetail:P}),await this.transitionToRepairing(o,s);return}}let j=await ye.getCid(D.message);if(this._recentlyPulledCids.set(`${j}|${i}`,Date.now()+jn.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(j,i).catch(()=>{}),s&&N&&s.status==="live"){let H=N.inflight.get($);H&&(H.committed=!0),as.setReceivedToken(s.pull,A.cursor),this.drainCommittedPull(o)>0&&(await this.ledger.saveLink(s),s.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:s.tenantDid,remoteEndpoint:s.remoteEndpoint,protocol:s.protocol,position:s.pull.contiguousAppliedToken.position,messageCid:s.pull.contiguousAppliedToken.messageCid})),N.inflight.size>I6&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s))}}catch(z){console.error(`SyncEngineLevel: Error processing live-pull event for ${t}`,z);try{let L=await ye.getCid(D.message);this.recordDeadLetter({messageCid:L,tenantDid:t,remoteEndpoint:i,protocol:a,category:"pull-processing",errorDetail:z.message??String(z)})}catch{}s&&await this.transitionToRepairing(o,s)}}}},h={store:!1,author:t,target:t,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:c,permissionGrantId:u}},{message:m}=await this.agent.dwn.processRequest(h);if(!m)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${i}`);let y=async A=>{let D=A??s?.pull.contiguousAppliedToken??c;D&&(!D.streamId||!D.messageCid||!D.epoch||!D.position)&&(D=void 0);let N={...h,messageParams:{...h.messageParams,cursor:D}},{message:$}=await this.agent.dwn.processRequest(N);if(!$)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${i}`);return $},v=new URL(i);v.protocol=v.protocol==="http:"?"ws:":"wss:";let w=v.toString(),x=await this.agent.rpc.sendDwnRequest({dwnUrl:w,targetDid:t,message:m,subscription:{handler:p,resubscribeFactory:y}});if(x.status.code===410){let A=new Error(`SyncEngineLevel: ProgressGap for ${t} -> ${i}: ${x.status.detail}`);throw A.isProgressGap=!0,A.gapInfo=x.error,A}if(x.status.code!==200||!x.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${t} -> ${i}: ${x.status.code} ${x.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:t,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await x.subscription.close()}});let _=this._activeLinks.get(o);if(_){let A=_.connectivity;_.connectivity="online",A!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t,remoteEndpoint:i,protocol:a,from:A,to:"online"})}}async openLocalPushSubscription(e){let{did:t,delegateDid:n,dwnUrl:i,protocol:a}=e,o=a?[{protocol:a}]:[],s;n&&(s=(await this._permissionsApi.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let c=this._engineGeneration,l=async f=>{if(this._engineGeneration!==c||f.type!=="event")return;let p=e.linkKey,h=this._activeLinks.get(p);if(h&&!jH(f.event.message,h.scope))return;let m=p,y=await ye.getCid(f.event.message);if(y===void 0||this.isRecentlyPulled(y,i))return;let v=this.getOrCreatePushRuntime(m,{did:t,dwnUrl:i,delegateDid:n,protocol:a});v.entries.push({cid:y}),!v.flushing&&!v.timer&&this.flushPendingPushesForLink(m)},u=(await this.agent.dwn.processRequest({author:t,target:t,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:o,permissionGrantId:s},subscriptionHandler:l})).reply;if(u.status.code!==200||!u.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${t}: ${u.status.code} ${u.status.detail}`);this._localSubscriptions.push({linkKey:e.linkKey??Ab(t,i,a),did:t,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await u.subscription.close()}})}async flushPendingPushes(){await Promise.all([...this._pushRuntimes.keys()].map(async e=>{await this.flushPendingPushesForLink(e)}))}async flushPendingPushesForLink(e){let t=this._pushRuntimes.get(e);if(!t)return;let{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:s,retryCount:c}=t;if(t.entries=[],s.length===0){!t.timer&&!t.flushing&&c===0&&this._pushRuntimes.delete(e);return}let l=s.map(d=>d.cid);t.flushing=!0;try{let d=await W6({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:l,agent:this.agent,permissionsApi:this._permissionsApi});for(let u of d.succeeded)this.clearFailedMessage(u,i).catch(()=>{});for(let u of d.permanentlyFailed)await this.recordDeadLetter({messageCid:u.cid,tenantDid:n,remoteEndpoint:i,protocol:o,category:"push-permanent",errorCode:String(u.statusCode??""),errorDetail:u.detail??"permanent push failure"});if(d.failed.length>0){let u=new Set(d.failed),f=s.filter(p=>u.has(p.cid));this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:f,retryCount:c+1})}else t.retryCount=0,!t.timer&&t.entries.length===0&&this._pushRuntimes.delete(e)}catch(d){console.error(`SyncEngineLevel: Push batch failed for ${n} -> ${i}`,d),this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:s,retryCount:c+1})}finally{t.flushing=!1;let d=this._pushRuntimes.get(e);d&&d.entries.length>0&&!d.timer&&(d.timer=setTimeout(()=>{d.timer=void 0,this.flushPendingPushesForLink(e)},Dge))}}requeueOrReconcile(e,t){let n=jn.PUSH_RETRY_BACKOFF_MS.length,i=this.getOrCreatePushRuntime(e,t);if(t.retryCount>=n){for(let s of t.entries)this.recordDeadLetter({messageCid:s.cid,tenantDid:t.did,remoteEndpoint:t.dwnUrl,protocol:t.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${n} attempts`});i.timer&&clearTimeout(i.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:t.did,remoteEndpoint:t.dwnUrl,protocol:t.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}i.entries.push(...t.entries),i.retryCount=t.retryCount;let a=jn.PUSH_RETRY_BACKOFF_MS[t.retryCount]??2e3;i.timer&&clearTimeout(i.timer),i.timer=setTimeout(()=>{i.timer=void 0,this.flushPendingPushesForLink(e)},a)}createLinkReconciler(e){return new sS({getLocalRoot:async(t,n,i)=>this.getLocalRoot(t,n,i),getRemoteRoot:async(t,n,i,a)=>this.getRemoteRoot(t,n,i,a),diffWithRemote:async t=>this.diffWithRemote(t),pullMessages:async t=>this.pullMessages(t),pushMessages:async t=>this.pushMessages(t),shouldContinue:e})}scheduleReconcile(e,t=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this.reconcileLink(e)},t);this._reconcileTimers.set(e,i)}async reconcileLink(e){let t=this._reconcileInFlight.get(e);if(t)return t;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n}async doReconcileLink(e){let t=this._activeLinks.get(e);if(!t||t.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:o,protocol:s}=t;try{let c=await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:o,protocol:s},{verifyConvergence:!0});if(c.aborted)return;c.converged?(await this.ledger.clearNeedsReconcile(t),this.clearDeadLettersForLink(i,a,s),this.emitEvent({type:"reconcile:completed",tenantDid:i,remoteEndpoint:a,protocol:s})):this.scheduleReconcile(e,5e3)}catch(c){console.error(`SyncEngineLevel: Reconciliation failed for ${i} -> ${a}`,c),this.scheduleReconcile(e,5e3)}}getOrCreatePushRuntime(e,t){let n=this._pushRuntimes.get(e);return n||(n={...t,entries:[],retryCount:0},this._pushRuntimes.set(e,n)),n}buildLinkKey(e,t,n){return n?CH(e,t,n):Ab(e,t)}async getCursor(e){let t=this._db.sublevel("syncCursors");try{let n=await t.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}await this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async deleteLegacyCursor(e){let t=this._db.sublevel("syncCursors");try{await t.del(e)}catch{}}extractDataStream(e){if(!jd(e))return;let t=e.message.encodedData;if(t){delete e.message.encodedData;let n=De.base64UrlToBytes(t);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let t=await Al(),n=new Map;for(let i=0;i<=Ige;i++)n.set(i,an(t[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,t=>t==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,t,n){let i=this.stateIndex;if(i){let c=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return an(c)}let a=await this.getSyncPermissionGrantId(e,t,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:t,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,t,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:t,targetDid:e,message:o.message})).root??""}async diffWithRemote({did:e,dwnUrl:t,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,OH),o=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:OH,permissionGrantId:o}}),c=await this.agent.rpc.sendDwnRequest({dwnUrl:t,targetDid:e,message:s.message});if(c.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${c.status.code}: ${c.status.detail}`);let l=o,d=[];for(let u of c.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);d.push(...f)}return{onlyRemote:c.onlyRemote??[],onlyLocal:d}}async collectLocalSubtreeHashes(e,t,n){let i={},a=await this.getDefaultHashHex(n),o=this.stateIndex,s=async(c,l)=>{let d;if(o){let u=jn.parseBitPrefix(c),f=t!==void 0?await o.getProtocolSubtreeHash(e,t,u):await o.getSubtreeHash(e,u);d=an(f)}else d=await this.getLocalSubtreeHash(e,c,void 0,t);if(d!==a){if(l>=n){i[c]=d;return}await Promise.all([s(c+"0",l+1),s(c+"1",l+1)])}};return await s("",0),i}async getLocalSubtreeHash(e,t,n,i,a){let o=this.stateIndex;if(o){let l=jn.parseBitPrefix(t),d=i!==void 0?await o.getProtocolSubtreeHash(e,i,l):await o.getSubtreeHash(e,l);return an(d)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:t,protocol:i,permissionGrantId:a}})).reply.hash??""}async getLocalLeaves(e,t,n,i,a){let o=this.stateIndex;if(o){let l=jn.parseBitPrefix(t);return i!==void 0?await o.getProtocolLeaves(e,i,l):await o.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:t,protocol:i,permissionGrantId:a}})).reply.entries??[]}async pullMessages({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,prefetched:o}){let s=await BH({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let c of s)await this.recordDeadLetter({messageCid:c,tenantDid:e,remoteEndpoint:t,protocol:i,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})}evictExpiredEchoEntries(){let e=Date.now();for(let[t,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(t);if(this._recentlyPulledCids.size>jn.ECHO_SUPPRESS_MAX_ENTRIES){let t=this._recentlyPulledCids.size-jn.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=t)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,t){let n=`${e}|${t}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}async pushMessages({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a}){return W6({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return bg(e)}async clearDeadLettersForLink(e,t,n){let i=[];try{for await(let[a,o]of this._deadLetters.iterator()){let s=JSON.parse(o);s.tenantDid===e&&s.remoteEndpoint===t&&s.protocol===n&&i.push({type:"del",key:a})}i.length>0&&await this._deadLetters.batch(i)}catch(a){if(a.code!=="LEVEL_DATABASE_NOT_OPEN")throw a}}static deadLetterKey(e,t){return t?`${e}|${t}`:e}async recordDeadLetter(e){let t={...e,failedAt:new Date().toISOString()},n=jn.deadLetterKey(e.messageCid,e.remoteEndpoint);try{await this._deadLetters.put(n,JSON.stringify(t))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}}async getFailedMessages(e){let t=[];for await(let[,n]of this._deadLetters.iterator()){let i=JSON.parse(n);(!e||i.tenantDid===e)&&t.push(i)}return t.sort((n,i)=>i.failedAt.localeCompare(n.failedAt)),t}async clearFailedMessage(e,t){if(t){let a=jn.deadLetterKey(e,t);try{return await this._deadLetters.get(a),await this._deadLetters.del(a),!0}catch(o){if(o.code==="LEVEL_NOT_FOUND")return!1;throw o}}let n=!1,i=[];for await(let[a,o]of this._deadLetters.iterator())JSON.parse(o).messageCid===e&&(i.push({type:"del",key:a}),n=!0);return i.length>0&&await this._deadLetters.batch(i),n}async clearAllFailedMessages(e){if(!e){await this._deadLetters.clear();return}let t=[];for await(let[n,i]of this._deadLetters.iterator())JSON.parse(i).tenantDid===e&&t.push({type:"del",key:n});t.length>0&&await this._deadLetters.batch(t)}async getSyncHealth(){let e=0;for await(let i of this._deadLetters.iterator())e++;let t=0,n=await this.ledger.getAllLinks();for(let i of n)(i.status==="repairing"||i.status==="degraded_poll")&&t++;return{connectivity:this.connectivityState,failedMessageCount:e,degradedLinkCount:t}}async getSyncTargets(){let e=[];for await(let[t,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch(c){console.warn(`SyncEngineLevel: Corrupt sync options for ${t}, falling back to global sync:`,c),i={protocols:[]}}let{protocols:a,delegateDid:o}=i,s=await this.agent.dwn.getDwnEndpointUrlsForTarget(t);if(s.length!==0)for(let c of s)if(a.length===0)e.push({did:t,delegateDid:o,dwnUrl:c});else for(let l of a)e.push({did:t,delegateDid:o,dwnUrl:c,protocol:l})}return e}async getSyncPermissionGrantId(e,t,n){return t?(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:t,protocol:n,cached:!0})).grant.id:void 0}};jn.ECHO_SUPPRESS_TTL_MS=6e4,jn.ECHO_SUPPRESS_MAX_ENTRIES=1e4,jn.MAX_CONSECUTIVE_FAILURES=5,jn.MAX_BACKOFF_MULTIPLIER=4,jn.MAX_REPAIR_ATTEMPTS=3,jn.REPAIR_BACKOFF_MS=[1e3,3e3,1e4],jn.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];var Pg=jn;g();Xn();ea();Sr();import{Level as Fge}from"level";g();g();g();Sr();Pn();g();g();var KH=Tn(JE(),1);Sr();var xg=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},cS=class{constructor({ttl:e="15m"}={}){this.cache=new xi.default({ttl:(0,KH.default)(e)})}get(e){return xg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,t){return xg(this,void 0,void 0,function*(){this.cache.set(e,t)})}delete(e){return xg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return xg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return xg(this,void 0,void 0,function*(){})}close(){return xg(this,void 0,void 0,function*(){})}};g();Pn();Xn();g();var Eg=class extends Error{constructor(e,t){super(t??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var Sg;(function(r){r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.ParseError=-32700]="ParseError",r[r.TransportError=-32300]="TransportError",r[r.BadRequest=-50400]="BadRequest",r[r.Unauthorized=-50401]="Unauthorized",r[r.Forbidden=-50403]="Forbidden",r[r.Conflict=-50409]="Conflict",r[r.TooManyRequests=-50429]="TooManyRequests"})(Sg||(Sg={}));var kg=(r,e,t)=>({jsonrpc:"2.0",id:r,method:e,params:t}),dS=(r,e,t,n)=>({jsonrpc:"2.0",id:r,method:e,params:t,subscription:{id:n??null}}),NH=(r,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:r}});function Mh(r){try{return JSON.parse(r)}catch{return null}}var J6=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Rge=3,Cge=500,$ge=1e4,Bge=3e4,UH=new Set([408,429,500,502,503,504]);function Oge(r,e){return r instanceof TypeError?!0:e?UH.has(e.status):!1}function jge(r,e,t){let n=Math.min(e*Math.pow(2,r),t),i=.5+Math.random()*.5;return n*i}function Mge(r){let e=r.headers.get("retry-after");if(e===null)return;let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var lS=class r{constructor(e,t){var n,i,a;this.serverInfoCache=e??new cS,this._retryOptions={maxRetries:(n=t?.maxRetries)!==null&&n!==void 0?n:Rge,baseDelayMs:(i=t?.baseDelayMs)!==null&&i!==void 0?i:Cge,maxDelayMs:(a=t?.maxDelayMs)!==null&&a!==void 0?a:$ge}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return J6(this,void 0,void 0,function*(){var t,n,i;let a=bn.randomUuid(),o=kg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),s={"dwn-request":JSON.stringify(o)},c={method:"POST",headers:s};if(e.data){s["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(r.isBunRuntime()){let h=yield Wt.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((t=l.headers.get("retry-after"))!==null&&t!==void 0?t:"1",10);throw new Eg(p)}let d,u=l.headers.has("dwn-response");if(u){let p=Mh(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=Mh(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Sg.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new Eg(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Wt.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return J6(this,void 0,void 0,function*(){var t;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let o=parseInt((t=a.headers.get("retry-after"))!==null&&t!==void 0?t:"1",10);throw new Eg(o)}if(a.ok){let o=yield a.json(),s={maxFileSize:o.maxFileSize,maxInFlight:o.maxInFlight,providerAuth:o.providerAuth,registrationRequirements:o.registrationRequirements,server:o.server,sdkVersion:o.sdkVersion,url:o.url,version:o.version,webSocketSupport:o.webSocketSupport};return this.serverInfoCache.set(e,s),s}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,t){return J6(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,o,s;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Bge),p=Object.assign(Object.assign({},t),{signal:t?.signal?AbortSignal.any([t.signal,f]):f}),h=yield fetch(e,p);if(!UH.has(h.status)||c===n)return h;s=h}catch(f){if(!Oge(f)||c===n)throw f;o=f}let l=s?Mge(s):void 0,d=jge(c,i,a),u=l!==void 0?Math.max(l,d):d;yield new Promise(f=>{setTimeout(f,u)})}if(s)return s;throw o})}};g();Pn();var Tb=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})};function Z6(r){return typeof r=="string"?r:r instanceof ArrayBuffer?new TextDecoder().decode(r):r instanceof Uint8Array?new TextDecoder().decode(r):String(r)}var LH=3e3,Kge=3e4,Nge=1e3,Uge=3e4,Lge=1/0,qge=3e4,zge=1e4,uS=class r{constructor(e,t,n,i){this.socket=e,this.responseTimeout=t,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return Tb(this,arguments,void 0,function*(t,n={}){var i;let{connectTimeout:a=LH,responseTimeout:o=Kge}=n,s;try{s=yield r.createWebSocket(t,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new r(s,o,t,n);return c.wireSocket(s),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return Tb(this,void 0,void 0,function*(){return new Promise((t,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=bn.randomUuid());let a=o=>{let s=Mh(Z6(o.data));if(s.id===e.id)return this.messageHandlers.delete(e.id),t(s)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,t){return Tb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=Mh(Z6(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),t(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let o=yield this.request(e);return o.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:o}):{response:o,close:()=>Tb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let t=bn.randomUuid(),n=dS(t,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,t){return new Promise((n,i)=>{let a=new WebSocket(e),o=()=>{l(),n(a)},s=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},t),l=()=>{clearTimeout(c),a.removeEventListener("open",o),a.removeEventListener("error",s)};a.addEventListener("open",o),a.addEventListener("error",s)})}wireSocket(e){e.addEventListener("message",t=>{let n=Mh(Z6(t.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(t)}),e.addEventListener("close",()=>{var t,n,i,a,o;if(this._isConnected=!1,this.stopHeartbeat(),this.closedByUser){(n=(t=this.options).onclose)===null||n===void 0||n.call(t);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((o=this.options.autoReconnect)!==null&&o!==void 0?o:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",t=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,t)})}rejectPendingRequests(){for(let[e,t]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:Sg.TransportError,message:"WebSocket connection closed unexpectedly"}});t({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,t;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:qge;if(n<=0)return;let i=(t=this.options.heartbeatTimeout)!==null&&t!==void 0?t:zge;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,o={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(o)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,t,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:Nge,o=(t=this.options.maxReconnectDelay)!==null&&t!==void 0?t:Uge,s=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Lge,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:LH,l=0,d=()=>Tb(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>s){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),o)*(.5+Math.random()*.5);if(yield new Promise(v=>setTimeout(v,y)),this.closedByUser){this.reconnecting=!1;return}try{let v=yield r.createWebSocket(this.url,c);this.socket=v,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(v),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};g();g();g();Pn();g();Pn();var _g=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Ib=class r{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return _g(this,void 0,void 0,function*(){let t=new URL(e.dwnUrl);if(t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${t.protocol}`);if(!r.connections.has(t.host))try{let c=yield r.createConnection(t);r.connections.set(t.host,c)}catch(c){throw new Error(`Error connecting to ${t.host}: ${c.message}`)}let i=r.connections.get(t.host),{targetDid:a,message:o,subscription:s}=e;return s?r.subscriptionRequest(i,a,o,s.handler,s.resubscribeFactory):r.processMessage(i,a,o)})}static createConnection(e){return _g(this,void 0,void 0,function*(){let t=e.host,n=new Map,i=yield uS.connect(e.toString(),{onclose:()=>{r.connections.delete(t);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let o of n.values())o.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};r.connections.set(t,a),r.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,t,n){return _g(this,void 0,void 0,function*(){let i=bn.randomUuid(),a=kg(i,"dwn.processMessage",{target:t,message:n}),{socket:o}=e,s=yield o.request(a),{error:c,result:l}=s;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,t,n,i,a){return _g(this,void 0,void 0,function*(){let o=bn.randomUuid(),s=bn.randomUuid(),c=dS(o,"rpc.subscribe.dwn.processMessage",{target:t,message:n},s),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,y=>{let{result:v,error:w}=y;if(w){let _=d.get(s);_&&_.subscription.close(),d.delete(s);return}let x=v.subscription;if(i(x),"cursor"in x&&x.cursor){let _=d.get(s);_&&(_.lastCursor=x.cursor),l.send(NH(s,x.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let y=()=>_g(this,void 0,void 0,function*(){d.delete(s),yield f()}),v={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:t,message:n,handler:i,resubscribeFactory:a};d.set(s,v),m.subscription.close=y}return m})}static resubscribeAll(e){return _g(this,void 0,void 0,function*(){let t=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of t)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield r.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Ib.connections=new Map;var Db=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},qH;(function(r){r.Create="did.create",r.Resolve="did.resolve"})(qH||(qH={}));var Ag=class{constructor(e=[]){this.transportClients=new Map,e=[new Y6,new X6,...e];for(let t of e)for(let n of t.transportProtocols)this.transportClients.set(n,t)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Db(this,void 0,void 0,function*(){let t=new URL(e.url),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let t=new URL(e.dwnUrl),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Db(this,void 0,void 0,function*(){let t=new URL(e),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},Y6=class extends lS{sendDidRequest(e){return Db(this,void 0,void 0,function*(){let t=bn.randomUuid(),n=kg(t,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let o=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(o.ok){if(a=yield o.json(),a.error){let{code:s,message:c}=a.error;throw new Error(`JSON RPC (${s}) - ${c}`)}}else throw new Error(`HTTP (${o.status}) - ${o.statusText}`)}catch(o){throw new Error(`Error encountered while processing response from ${e.url}: ${o.message}`)}return a.result})}},X6=class extends Ib{sendDidRequest(e){return Db(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Db(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var zH=class r{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:t,permissionsApi:n,keyManager:i}=r.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=t,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await vo.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:t}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:t}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:t,testDataLocation:n}){t??="memory",n??="__TESTDATA__";let i=z=>`${n}/${z}`,a=new xo,o=new Ag,s={keyStore:new yg,identityStore:new wg,didStore:new hg,clear:()=>{s.keyStore._protocolInitializedCache?.clear(),s.identityStore._protocolInitializedCache?.clear(),s.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:l,identityApi:d,keyManager:u,didResolverCache:f,vaultStore:p,permissionsApi:h}=t==="memory"?r.useMemoryStores():r.useDiskStores({testDataLocation:n,stores:s}),m=new If({blockstoreLocation:i("DWN_DATASTORE")}),y=new $f({location:i("DWN_STATEINDEX")}),v=new Cf,w=new Rf({location:i("DWN_RESUMABLETASKSTORE")}),x=new Df({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),_=await Vl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:v,messageStore:x,resumableTaskStore:w}),A=new Vl({dwn:_,localDwnStrategy:"off"}),D=new Fge(i("SYNC_STORE")),N=new Pg({db:D}),$=new e({agentVault:c,cryptoApi:a,didApi:l,dwnApi:A,identityApi:d,keyManager:u,permissionsApi:h,rpcClient:o,syncApi:N});return new r({agent:$,agentStores:t,didResolverCache:f,dwn:_,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:x,dwnResumableTaskStore:w,dwnStores:s,syncStore:D,vaultStore:p})}static useDiskStores({agent:e,testDataLocation:t,stores:n}){let i=m=>`${t}/${m}`,a=new $m({location:i("VAULT_STORE")}),o=new Oh({keyDerivationWorkFactor:1,store:a}),{didStore:s,identityStore:c,keyStore:l}=n,d=new Bf({location:i("DID_RESOLVERCACHE")}),u=new Dh({agent:e,didMethods:[vo,bo],resolverCache:d,store:s}),f=new jh({agent:e,store:c}),p=new As({agent:e,keyStore:l}),h=new _s({agent:e});return{agentVault:o,didApi:u,didResolverCache:d,identityApi:f,keyManager:p,permissionsApi:h,vaultStore:a}}static useMemoryStores({agent:e}={}){let t=new xu,n=new Oh({keyDerivationWorkFactor:1,store:t}),i=new mE,a=new Dh({agent:e,didMethods:[vo,bo],resolverCache:i,store:new mg}),o=new As({agent:e,keyStore:new gg}),s=new jh({agent:e,store:new vg}),c=new _s({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:s,keyManager:o,permissionsApi:c,vaultStore:t}}};g();ea();Sr();Pn();Xn();function Gge({baseURL:r,endpoint:e,authParam:t,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return vb(r,"par");case"authorize":if(!t)throw new Error("authParam must be provided when building an authorize URL");return vb(r,`authorize/${t}.jwt`);case"callback":return vb(r,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return vb(r,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function Hge({did:r,data:e}){let t=he.object({alg:"EdDSA",kid:r.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await r.getSigner()).sign({data:he.string(`${t}.${n}`).toUint8Array()}),o=he.uint8Array(a).toBase64Url();return`${t}.${n}.${o}`}async function FH({jwt:r}){let[e,t,n]=r.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await bo.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:o}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!o)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Yc().verify({key:o,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${t}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(t).toObject()}async function Vge({jwt:r,encryptionKey:e}){let t={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=bn.randomBytes(24),i=he.object(t).toUint8Array(),a=he.string(r).toUint8Array(),o=await Qc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),s=o.subarray(0,-16),c=o.subarray(-16);return[he.object(t).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(s).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function GH({jwe:r,encryptionKey:e}){let[t,,n,i,a]=r.split("."),o=he.base64Url(e).toUint8Array(),s=he.base64Url(t).toUint8Array(),c=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),d=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...d]),f=await Qc.decryptRaw({data:u,keyBytes:o,nonce:c,additionalData:s});return he.uint8Array(f).toString()}async function Wge(r,e){let t=await r.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=t.privateKeys?.[0];n.alg="EdDSA";let a=await Un.convertPublicKeyToX25519({publicKey:n}),o=await Un.convertPrivateKeyToX25519({privateKey:i}),s=await At.sharedSecret({privateKeyA:o,publicKeyB:a});return Nm.deriveKeyBytes({baseKeyBytes:new Uint8Array(s),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function Jge({jwt:r,encryptionKey:e,delegateDidKeyId:t,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:t},a=bn.randomBytes(24),o=n?{...i,pin:n}:{...i},s=he.object(o).toUint8Array(),c=he.string(r).toUint8Array(),l=await Qc.encryptRaw({data:c,keyBytes:e,nonce:a,additionalData:s}),d=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(d).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function Zge(r,e,t){let[n,,i,a,o]=e.split("."),s=he.base64Url(n).toObject();if(!s.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let c=await bo.resolve(s.kid.split("#")[0]),l=await Tg.deriveSharedKey(r,c.didDocument),d=t?{...s,pin:t}:{...s},u=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),p=he.base64Url(a).toUint8Array(),h=he.base64Url(o).toUint8Array(),m=new Uint8Array([...p,...h]),y=await Qc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function Yge(r){let e=bn.randomBytes(16),t=bn.randomBytes(16);return{...r,nonce:he.uint8Array(t).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:r.supportedDidMethods??["did:dht","did:jwk"]}}async function Xge(r,e){let n=await(await fetch(r,{signal:AbortSignal.timeout(3e4)})).text(),i=await GH({jwe:n,encryptionKey:e});return await FH({jwt:i})}async function Qge(r){let e=Math.floor(Date.now()/1e3);return{...r,iat:e,exp:e+600}}function ewe(r){return Ch(r)?!0:r.interface===ve.Protocols&&r.method===me.Configure}async function twe(r,e,t,n,i){let a=new _s({agent:t});Ms.log(`Creating permission grants for ${n.length} scopes...`);let o=await Promise.all(n.map(l=>{let d=ewe(l),u=new Set([me.Read,me.Query,me.Subscribe]),p=Ch(l)&&u.has(l.method)&&i?i:void 0;return a.createGrant({delegated:d,store:!0,grantedTo:e.uri,scope:l,dateExpires:"2040-06-25T16:09:16.693356Z",author:r,delegateKeyDelivery:p})})),s=await t.dwn.getDwnEndpointUrlsForTarget(r);Ms.log(`Sending ${o.length} permission grants to ${s.length} DWN endpoint(s)...`);let c=o.map(async l=>{let{encodedData:d,...u}=l.message,f=he.base64Url(d).toUint8Array(),p=!1;for(let h of s)try{let m=await t.rpc.sendDwnRequest({dwnUrl:h,targetDid:r,message:u,data:new Blob([f])});m.status.code===202||m.status.code===409?p=!0:Ms.error(`Grant send to ${h} returned ${m.status.code}: ${m.status.detail}`)}catch(m){Ms.error(`Grant send to ${h} failed: ${m.message}`)}if(!p)throw new Error("Could not send permission grant to any DWN endpoint.");return l.message});try{return await Promise.all(c)}catch(l){throw Ms.error(`Error during batch-send of permission grants: ${l}`),l}}async function rwe(r,e,t){let n=Object.values(t.types??{}).some(a=>a?.encryptionRequired===!0),i=await e.processDwnRequest({author:r,messageType:Re.ProtocolsQuery,target:r,messageParams:{filter:{protocol:t.protocol}}});if(i.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${i.reply.status.detail}`);if(i.reply.entries===void 0||i.reply.entries.length===0){Ms.log(`Protocol does not exist, creating: ${t.protocol}`);let{reply:a,message:o}=await e.sendDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,messageParams:{definition:t},encryption:n||void 0});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`);await e.processDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,rawMessage:o})}else{Ms.log(`Protocol already exists: ${t.protocol}`);let a=i.reply.entries[0],{reply:o}=await e.sendDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,rawMessage:a});if(o.status.code!==202&&o.status.code!==409)throw new Error(`Could not send protocol: ${o.status.detail}`)}}async function HH(r,e,t,n,i){let a=new Set([me.Read,me.Query,me.Subscribe]),o=n.filter(p=>Ch(p)&&a.has(p.method));if(o.length===0)return[];for(let p of o)if("contextId"in p&&p.contextId)throw new Error(`Encrypted delegate access scoped by contextId is not supported yet; use protocol-wide permissions for protocol '${t}'.`);let{multiParty:s}=Q6(i);if(s.length>0)throw new Error(`deriveScopedDecryptionKeys called for protocol with multi-party roots [${s.join(", ")}]. Use deriveContextKeysForDelegate for multi-party protocols.`);let c=o.some(p=>!("protocolPath"in p)||!p.protocolPath),{keyId:l,keyUri:d}=await na(r,e);if(c){let p=[Pt.ProtocolPath,t],h=await r.keyManager.derivePrivateKeyBytes({keyUri:d,derivationPath:p}),m=await At.bytesToPrivateKey({privateKeyBytes:h});return[{protocol:t,scope:{kind:"protocol"},derivedPrivateKey:{rootKeyId:l,derivationScheme:Pt.ProtocolPath,derivationPath:p,derivedPrivateKey:m}}]}let u=new Set;for(let p of o){let h=p.protocolPath;h&&u.add(h)}let f=[];for(let p of u){let h=p.split("/"),m=[Pt.ProtocolPath,t,...h],y=await r.keyManager.derivePrivateKeyBytes({keyUri:d,derivationPath:m}),v=await At.bytesToPrivateKey({privateKeyBytes:y});f.push({protocol:t,scope:{kind:"protocolPath",protocolPath:p,match:"exact"},derivedPrivateKey:{rootKeyId:l,derivationScheme:Pt.ProtocolPath,derivationPath:m,derivedPrivateKey:v}})}return f}function Q6(r){let e=r.structure;if(!e)return{multiParty:[],singleParty:[]};let t=[],n=[];for(let i of Object.keys(e))i.startsWith("$")||(Th(r,i)?t.push(i):n.push(i));return{multiParty:t,singleParty:n}}async function VH(r,e,t,n){let i=new Set([me.Read,me.Query,me.Subscribe]),a=n.filter(f=>Ch(f)&&i.has(f.method));if(a.length===0)return[];for(let f of a)if("contextId"in f&&f.contextId)throw new Error(`Encrypted delegate access scoped by contextId is not supported yet; use protocol-wide permissions for protocol '${t.protocol}'.`);for(let f of a)if("protocolPath"in f&&f.protocolPath)throw new Error(`Encrypted delegate access scoped by protocolPath on multi-party protocols is not supported yet; use protocol-wide permissions for protocol '${t.protocol}'.`);let{keyId:o,keyUri:s}=await na(r,e),c=t.protocol,l=Object.keys(t.structure??{}).filter(f=>!f.startsWith("$")),d=[],u=new Set;for(let f of l){let{reply:p}=await r.processDwnRequest({author:e,target:e,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:c,protocolPath:f}}});for(let h of p.entries??[]){let m=h.contextId?.split("/")[0]||h.recordId;if(!m||u.has(m))continue;u.add(m);let y=[Pt.ProtocolContext,m],v=await r.keyManager.derivePrivateKeyBytes({keyUri:s,derivationPath:y}),w=await At.bytesToPrivateKey({privateKeyBytes:v});d.push({protocol:c,contextId:m,derivedPrivateKey:{rootKeyId:o,derivationScheme:Pt.ProtocolContext,derivationPath:y,derivedPrivateKey:w}})}}return d}async function nwe(r,e,t,n){let i=await bo.create(),a=await i.export(),o=a.privateKeys[0],s=await Un.convertPrivateKeyToX25519({privateKey:o});a.privateKeys.push(s);let c=await At.privateKeyToBytes({privateKey:s}),l=[Pt.ProtocolPath,za.protocol,"contextKey"],d=await Ni.derivePrivateKeyBytes(c,l),u=await At.bytesToPrivateKey({privateKeyBytes:d}),f=await At.getPublicKey({key:u}),h={rootKeyId:i.document.verificationMethod[0].id,publicKeyJwk:f},m=[],y=[],v=[],w=e.permissionRequests.map(async R=>{let{protocolDefinition:C,permissionScopes:P}=R;if(!P.every(k=>"protocol"in k&&k.protocol===C.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");if(await rwe(r,n,C),Object.values(C.types??{}).some(k=>k?.encryptionRequired===!0)){let{multiParty:k,singleParty:I}=Q6(C);if(k.length>0&&I.length>0)throw new Error(`Encrypted delegate access for protocols with mixed single-party and multi-party roots is not supported yet. Protocol '${C.protocol}' has multi-party roots [${k.join(", ")}] and single-party roots [${I.join(", ")}].`);if(k.length>0){let K=await VH(n,r,C,P);y.push(...K);let F=new Set([me.Read,me.Query,me.Subscribe]);P.some(W=>Ch(W)&&F.has(W.method))&&v.push(C.protocol)}else{let K=await HH(n,r,C.protocol,P,C);m.push(...K)}}return Tg.createPermissionGrants(r,i,n,P,h)}),x=(await Promise.all(w)).flat(),_=new _s({agent:n}),A=[],D=[];try{D=await n.dwn.getDwnEndpointUrlsForTarget(r)}catch{}let N=x.length;for(let R=0;R<N;R++){let C=x[R],P=await _.createGrant({delegated:!0,store:!0,grantedTo:i.uri,scope:{interface:ve.Records,method:me.Write,protocol:rt.uri,contextId:C.recordId},dateExpires:"2040-06-25T16:09:16.693356Z",author:r});A.push({grantId:C.recordId,revocationGrantId:P.message.recordId});let{encodedData:S,...E}=P.message,k=he.base64Url(S).toUint8Array();for(let I of D)try{await n.rpc.sendDwnRequest({dwnUrl:I,targetDid:r,message:E,data:new Blob([k])})}catch{}x.push(P.message)}Ms.log("Building connect response...");let $=await Tg.createConnectResponse({providerDid:r,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:x,delegatePortableDid:a,delegateDecryptionKeys:m.length>0?m:void 0,delegateContextKeys:y.length>0?y:void 0,delegateMultiPartyProtocols:v.length>0?v:void 0,sessionRevocations:A.length>0?A:void 0});Ms.log("Signing connect response...");let z=await Tg.signJwt({did:i,data:$}),L=await bo.resolve(e.clientDid),j=await Tg.deriveSharedKey(i,L?.didDocument);Ms.log("Encrypting connect response...");let H=await Tg.encryptResponse({jwt:z,encryptionKey:j,delegateDidKeyId:i.document.verificationMethod[0].id,pin:t}),Y=new URLSearchParams({id_token:H,state:e.state}).toString();Ms.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:Y,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var Tg={buildConnectUrl:Gge,signJwt:Hge,verifyJwt:FH,encryptRequest:Vge,decryptRequest:GH,encryptResponse:Jge,decryptResponse:Zge,deriveSharedKey:Wge,createConnectRequest:Yge,getConnectRequest:Xge,createConnectResponse:Qge,createPermissionGrants:twe,submitConnectResponse:nwe,deriveScopedDecryptionKeys:HH,deriveContextKeysForDelegate:VH,classifyProtocolRoots:Q6};g();Sr();ea();var WH=class r{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:t,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:o,didApi:s,dwnApi:c,identityApi:l,keyManager:d,permissionsApi:u,rpcClient:f,syncApi:p}={}){return a??=new Oh({keyDerivationWorkFactor:21e4,store:new $m({location:`${e}/VAULT_STORE`})}),o??=new xo,s??=new Dh({didMethods:[vo,bo],resolverCache:new Bf({location:`${e}/DID_RESOLVERCACHE`}),store:new hg}),c||(n?c=new Vl({localDwnEndpoint:n,localDwnStrategy:t??"prefer"}):c=new Vl({dwn:await Vl.createDwn({dataPath:e,didResolver:s}),localDwnStrategy:t??"prefer"})),t&&c.setLocalDwnStrategy(t),l??=new jh({store:new wg}),d??=new As({keyStore:new yg}),u??=new _s,f??=new Ag,p??=new Pg({dataPath:e}),new r({agentDid:i,agentVault:a,cryptoApi:o,didApi:s,dwnApi:c,keyManager:d,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:p})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:t,dwnEndpoints:n}){return t=await this.vault.initialize({password:e,recoveryPhrase:t,dwnEndpoints:n}),t}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{xo as AgentCryptoApi,Dh as AgentDidApi,Bf as AgentDidResolverCache,Vl as AgentDwnApi,jh as AgentIdentityApi,_s as AgentPermissionsApi,ZG as AnonymousDwnApi,lg as BearerIdentity,R6 as ClosureFailureCode,Nye as DISCOVERY_DIR,Uye as DISCOVERY_FILENAME,pH as DWN_CONNECT_PATH,fH as DWN_PROTOCOL_SCHEME,jye as DidInterface,lo as DwnConstant,di as DwnContentEncryptionAlgorithm,Of as DwnDataStore,Ut as DwnDateSort,hg as DwnDidStore,YE as DwnDiscoveryFile,wg as DwnIdentityStore,Re as DwnInterface,Pt as DwnKeyDerivationScheme,yg as DwnKeyStore,Ir as DwnPermissionGrant,md as DwnPermissionRequest,rt as DwnPermissionsProtocol,Tg as EnboxConnectProtocol,WH as EnboxUserAgent,Oh as HdIdentityVault,jf as InMemoryDataStore,mg as InMemoryDidStore,vg as InMemoryIdentityStore,gg as InMemoryKeyStore,za as KeyDeliveryProtocolDefinition,Rh as LocalDwnDiscovery,As as LocalKeyManager,I6 as MAX_PENDING_TOKENS,zH as PlatformAgentTestHarness,as as ReplicationLedger,Pg as SyncEngineLevel,Pb as buildContextKeyDecrypter,LVe as buildDwnConnectUrl,zVe as buildDwnDiscoveryRedirectUrl,$h as buildEncryptionInput,Fye as buildExactProtocolPathDecrypter,rH as buildKmsDecryptCallback,T6 as computeScopeId,vb as concatenateUrl,wb as createClosureContext,Kye as createNodeDiscoveryFileFs,uH as decodeDwnDiscoveryPayload,tH as deriveContextEncryptionInput,$6 as detectNewParticipants,Ah as dwnMessageConstructors,oH as eagerSendContextKeyRecord,Hye as encodeDwnDiscoveryPayload,QE as encryptAndComputeCid,iH as ensureKeyDeliveryProtocol,GE as evaluateClosure,Aye as evaluateClosureBatch,aH as fetchContextKeyRecord,dg as getDwnServiceEndpointUrls,xb as getEncryptionKeyDeriver,na as getEncryptionKeyInfo,j6 as getKeyDecrypter,sHe as getPaginationCursor,nHe as getRecordAuthor,Dye as getRecordMessageCid,iHe as getRecordProtocolRole,zGe as getRootContextId,VG as getRuleSetAtPath,C6 as hasRelationalReadAccess,QG as isDidRequest,qye as isDwnMessage,Fa as isDwnRequest,xge as isIdentityMetadata,zye as isMessagesPermissionScope,Th as isMultiPartyContext,PJe as isPortableIdentity,Ch as isRecordPermissionScope,O6 as isRecordsType,jd as isRecordsWrite,XE as ivLength,Mye as localDwnServerName,nH as maybeDecryptReply,ZE as normalizeBaseUrl,qVe as parseDwnConnectUrl,oHe as pollWithTtl,FVe as readDwnDiscoveryPayloadFromUrl,eH as resolveKeyDecrypter,sH as writeContextKeyRecord};
2060
+ 'valid, non-empty password.`);if(t??=kH(q6,128),!AH(t,q6))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await TH(t),a=rS.fromMasterSeed(i),o=a.derive("m/44'/0'/0'/0'/0'"),s=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:o.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:o.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await Rc.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(s).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",d);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),p=a.derive("m/44'/0'/1708523827'/0'/1'"),h=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:p.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),v=new VE;await v.addPredefinedKeys({privateKeys:[f,h,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let _=await(await vo.create({keyManager:v,options:w})).export(),A={alg:"dir",enc:"A256GCM",cty:"json"},D=await Rc.encrypt({key:s,plaintext:he.object(_).toUint8Array(),protectedHeader:A,crypto:this.crypto,keyManager:new As});return await this._store.set("did",D),this._contentEncryptionKey=s,await this.setStatus({initialized:!0}),t}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:t}){if(!bge(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let o=he.base64Url(e.data).toObject();await this._store.set("did",o.did),await this._store.set("contentEncryptionKey",o.contentEncryptionKey),await this.setStatus(o.status),await this.unlock({password:t})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let t=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Rc.decrypt({jwe:t,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async encryptData({plaintext:e}){if(this.isLocked()||!this._contentEncryptionKey)throw new Error("HdIdentityVault: Cannot encrypt data \u2014 vault is locked.");return Rc.encrypt({key:this._contentEncryptionKey,plaintext:e,protectedHeader:{alg:"dir",enc:"A256GCM"},crypto:this.crypto,keyManager:new As})}async decryptData({jwe:e}){if(this.isLocked()||!this._contentEncryptionKey)throw new Error("HdIdentityVault: Cannot decrypt data \u2014 vault is locked.");let{plaintext:t}=await Rc.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}});return t}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:t,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=t??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();ea();g();Sr();function xge(r){return!(!r||typeof r!="object"||r===null)&&"name"in r}var wg=class extends Of{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=HE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async set(t){return await super.set(t)}async list(t){return await super.list(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(xge(s)){let c=`${n}${Ri}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},vg=class extends jf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};function PJe(r){return!(!r||typeof r!="object"||r===null)&&"did"in r&&"metadata"in r&&Ph(r.did)}var jh=class{constructor({agent:e,store:t}={}){this._agent=e,this._store=t??new vg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:t="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:t,options:n,tenant:this.tenant,store:i}),o=new lg({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:o.did.uri,data:o.metadata,agent:this.agent,tenant:o.metadata.tenant,preventDuplicates:!1,useCache:!0}),o}async export({didUri:e}){let t=await this.get({didUri:e});if(!t)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await t.export()}async get({didUri:e}){let t=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!t)return;let n=await this.agent.did.get({didUri:e,tenant:t.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new lg({did:n,metadata:t})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let t=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!t)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new lg({did:t,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let t=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(t.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:t}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(o=>o.id.endsWith("dwn"));if(a)a.serviceEndpoint=t;else{let o={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:t};i.document.service?i.document.service.push(o):i.document.service=[o]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:t}){if(!t)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===t)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:t},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let t=await this.list();if(!(t.length<1))return e?t.find(n=>n.metadata.connectedDid===e):t.find(n=>n.metadata.connectedDid!==void 0)}};g();var MH=Tn(JE(),1);Xn();import{Level as Tge}from"level";g();function Ege(r){let e=[],t=[];for(let n of r)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?t.push(n.messageCid):e.push(n):t.push(n.messageCid);return{prefetched:e,needsFetchCids:t}}var sS=class{constructor(e){this._deps=e}async reconcile(e,t){let{did:n,dwnUrl:i,delegateDid:a,protocol:o}=e,s=t?.direction,c=t?.verifyConvergence??!1,l=this._deps.shouldContinue,d=await this._deps.getLocalRoot(n,a,o);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let u=await this._deps.getRemoteRoot(n,i,a,o);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=!1,p=!1,h;if(d!==u){let v=await this._deps.diffWithRemote(e);if(l&&!l())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:d,remoteRoot:u};if((!s||s==="pull")&&v.onlyRemote.length>0){let{prefetched:w,needsFetchCids:x}=Ege(v.onlyRemote);if(await this._deps.pullMessages({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:x,prefetched:w}),l&&!l())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:d,remoteRoot:u};f=!0}if((!s||s==="push")&&v.onlyLocal.length>0){if(h=await this._deps.pushMessages({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:v.onlyLocal}),l&&!l())return{aborted:!0,changed:!0,didPull:f,didPush:!0,localRoot:d,remoteRoot:u,pushResult:h};p=!0}}if(!c)return{changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h};let m=await this._deps.getLocalRoot(n,a,o);if(l&&!l())return{aborted:!0,changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h};let y=await this._deps.getRemoteRoot(n,i,a,o);return l&&!l()?{aborted:!0,changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,pushResult:h}:{changed:d!==u,didPull:f,didPush:p,localRoot:d,remoteRoot:u,postLocalRoot:m,postRemoteRoot:y,converged:m===y,pushResult:h}}};g();Xn();function RH(r){let e=r.descriptor;return e.interface!==ve.Records||e.method!==me.Write?!1:e.dateCreated===e.messageTimestamp}function bg(r){if(r.length<=1)return r;let e=new Map,t=new Map,n=new Map,i=new Map;for(let d=0;d<r.length;d++){let u=r[d];e.set(d,u);let f=u.message.descriptor;if(f.interface===ve.Protocols&&f.method===me.Configure){let p=f.definition?.protocol;p&&t.set(p,d)}if(f.interface===ve.Records&&f.method===me.Write){let p=u.message.recordId;RH(u.message)&&p&&n.set(p,d),f.protocol===rt.uri&&f.protocolPath===rt.grantPath&&p&&i.set(p,d)}}let a=new Map,o=new Array(r.length).fill(0),s=(d,u)=>{if(d===u)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(u)||(f.add(u),o[u]++)};for(let d=0;d<r.length;d++){let u=r[d].message.descriptor;if(u.interface===ve.Records){let p=u.protocol;p&&t.has(p)&&s(t.get(p),d)}if(u.interface===ve.Records&&u.parentId){let p=u.parentId;n.has(p)&&s(n.get(p),d)}if(u.interface===ve.Records&&u.method===me.Write){let p=r[d].message.recordId;p&&!RH(r[d].message)&&n.has(p)&&s(n.get(p),d)}if(u.interface===ve.Records&&u.method===me.Delete){let p=u.recordId;p&&n.has(p)&&s(n.get(p),d)}let f=u.permissionGrantId;f&&i.has(f)&&s(i.get(f),d)}let c=[];for(let d=0;d<r.length;d++)o[d]===0&&c.push(d);let l=[];for(;c.length>0;){let d=c.shift();l.push(e.get(d));let u=a.get(d);if(u)for(let f of u)o[f]--,o[f]===0&&c.push(f)}if(l.length<r.length){let d=new Set(l);for(let u=0;u<r.length;u++){let f=e.get(u);d.has(f)||l.push(f)}}return l}g();var oS="^";function CH(r,e,t){return`${r}${oS}${e}${oS}${t}`}function Ab(r,e,t){let n=`${r}${oS}${e}`;return t?`${n}${oS}${t}`:n}g();Xn();var Sge=1048576;function $H(r,e){return r.status.code===202||r.status.code===204||r.status.code===409||r.status.code===404&&(e?.descriptor.interface===ve.Records&&e?.descriptor.method===me.Delete||r.entry?.message.descriptor.interface===ve.Records&&r.entry?.message.descriptor.method===me.Delete)}function kge(r){return r.status.code===400||r.status.code===401||r.status.code===403}async function V6(r){try{return await ye.getCid(r)}catch{return"unknown"}}async function BH({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,prefetched:a,agent:o,permissionsApi:s}){let c=[];if(a)for(let m of a){if(!m.message)continue;let y={message:m.message};if(m.encodedData){let v=De.base64UrlToBytes(m.encodedData);y.bufferedData=v,y.dataStream=new ReadableStream({start(w){w.enqueue(v),w.close()}})}c.push(y)}let l=i.length>0?await aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:o,permissionsApi:s}):[],d=[...c,...l],u=bg(d);await _ge(u);let f=3,p=u;for(let m=0;m<=f&&p.length>0;m++){let y=[];for(let v of p){let w=v.bufferedData?new ReadableStream({start(_){_.enqueue(v.bufferedData),_.close()}}):v.dataStream,x=await o.dwn.processRawMessage(r,v.message,{dataStream:w});$H(x)||y.push(v)}if(y.length>0){let v=[],w=[];for(let x of y)if(x.bufferedData||!x.dataStream)w.push(x);else{let _=await V6(x.message);v.push(_)}if(v.length>0){let x=await aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:v,agent:o,permissionsApi:s});w.push(...x)}p=bg(w)}else p=[]}let h=[];for(let m of p){let y=await V6(m.message);h.push(y)}return h}async function _ge(r){for(let e of r){if(!e.dataStream)continue;let t=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)break;if(n+=l.byteLength,n>Sge){i=!0;break}t.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let o=new Uint8Array(n),s=0;for(let c of t)o.set(c,s),s+=c.byteLength;e.bufferedData=o,e.dataStream=new ReadableStream({start(c){c.enqueue(o),c.close()}})}}async function aS({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c;t&&(c=(await o.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:t,protocol:n,cached:!0})).grant.id);let l=4,d=0;for(;d<i.length;){let u=i.slice(d,d+l);d+=l;let f=await Promise.all(u.map(async p=>{let h=await a.processDwnRequest({store:!1,author:r,target:r,messageType:Re.MessagesRead,granteeDid:t,messageParams:{messageCid:p,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:r,message:h.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,v;return jd(y)&&y.data&&(v=y.data),{message:y.message,dataStream:v}}));for(let p of f)p&&s.push(p)}return s}async function W6({did:r,dwnUrl:e,delegateDid:t,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c=[],l=[],d=[];for(let f of i){let p=await Age({author:r,messageCid:f,delegateDid:t,protocol:n,agent:a,permissionsApi:o});p?d.push(p):c.push(f)}let u=bg(d);for(let f of u){let p=await V6(f.message);try{let h=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:r,data:f.dataStream,message:f.message});$H(h,f.message)?s.push(p):kge(h)?(h.status.code===400&&h.status.detail?.includes("record limit")?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${p}`):console.warn(`SyncEngineLevel: push permanently failed for ${p}: ${h.status.code} ${h.status.detail}`),l.push({cid:p,statusCode:h.status.code,detail:h.status.detail??""})):(console.error(`SyncEngineLevel: push failed for ${p}: ${h.status.code} ${h.status.detail}`),c.push(p))}catch(h){console.error(`SyncEngineLevel: push error for ${p}: ${h.message??h}`),c.push(p)}}return{succeeded:s,failed:c,permanentlyFailed:l}}async function Age({author:r,delegateDid:e,protocol:t,messageCid:n,agent:i,permissionsApi:a}){let o;e&&(o=(await a.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:e,protocol:t,cached:!0})).grant.id);let{reply:s}=await i.dwn.processRequest({author:r,target:r,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:o}});if(s.status.code!==200||!s.entry)return;let c=s.entry,l={message:c.message};return jd(c)&&c.data&&(l.dataStream=c.data),l}var Ige=16,OH=8,Dge=100;function jH(r,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let t=r.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=t.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=r.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var jn=class jn{constructor({agent:e,dataPath:t,db:n}){this._syncLock=!1;this._activeLinks=new Map;this._linkRuntimes=new Map;this._syncMode="poll";this._engineGeneration=0;this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._eventListeners=new Set;this._pushRuntimes=new Map;this._recentlyPulledCids=new Map;this._closureContexts=new Map;this._consecutiveFailures=0;this._degradedPollTimers=new Map;this._repairAttempts=new Map;this._activeRepairs=new Map;this._repairRetryTimers=new Map;this._repairContext=new Map;this._reconcileTimers=new Map;this._reconcileInFlight=new Map;this._agent=e,this._permissionsApi=new _s({agent:e}),this._db=n||new Tge(t??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new as(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new _s({agent:e})}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,t=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(t=!0);return e?"online":t?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let t of this._eventListeners)try{t(e)}catch{}}async clear(){await this.teardownLiveSync(),await this._permissionsApi.clear(),await this._db.clear()}async close(){await this.teardownLiveSync(),await this._db.close()}async registerIdentity({did:e,options:t}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);t??={protocols:[]},await n.put(e,JSON.stringify(t))}async unregisterIdentity(e){let t=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await t.del(e)}async getIdentityOptions(e){let t=this._db.sublevel("registeredIdentities");try{let n=await t.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:t}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(t))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let t=await this.getSyncTargets(),n=new Map;for(let s of t){let c=n.get(s.dwnUrl);c||(c=[],n.set(s.dwnUrl,c)),c.push(s)}let i=0,a=0,o=await Promise.allSettled([...n.entries()].map(async([s,c])=>{for(let l of c){let{did:d,delegateDid:u,protocol:f}=l;try{await this.createLinkReconciler().reconcile({did:d,dwnUrl:s,delegateDid:u,protocol:f},{direction:e})}catch(p){a++,console.error(`SyncEngineLevel: Error syncing ${d} with ${s}`,p);return}}i++}));for(let s of o)s.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):t.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}}async startSync(e){let t=e.mode??"poll",n=e.interval??(t==="live"?"5m":"2m"),i=(0,MH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=t,t==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){this._engineGeneration++;let t=0;for(;this._syncLock;){if(t>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);t+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let t=this._engineGeneration,n=async()=>{if(this._engineGeneration!==t||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(o){console.error("SyncEngineLevel: Error during sync operation",o)}let i=Math.min(Math.pow(2,this._consecutiveFailures),jn.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===t&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||await this.sync()}async startLiveSync(e){this.startBrowserConnectivityListeners();try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let t=await this.getSyncTargets();await Promise.allSettled(t.map(async i=>{let a;try{let o=i.protocol?{kind:"protocol",protocol:i.protocol}:{kind:"full"};a=await this.ledger.getOrCreateLink({tenantDid:i.did,remoteEndpoint:i.dwnUrl,scope:o,delegateDid:i.delegateDid,protocol:i.protocol});let s=this.buildLinkKey(i.did,i.dwnUrl,a.scopeId);if(!a.pull.contiguousAppliedToken){let l=Ab(i.did,i.dwnUrl,i.protocol),d=await this.getCursor(l);d&&(as.resetCheckpoint(a.pull,d),await this.ledger.saveLink(a),await this.deleteLegacyCursor(l))}this._activeLinks.set(s,a);let c={...i,linkKey:s};await this.openLivePullSubscription(c);try{await this.openLocalPushSubscription(c)}catch(l){let d=this._liveSubscriptions.find(u=>u.linkKey===s);if(d){try{await d.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(u=>u!==d)}throw l}this.emitEvent({type:"link:status-change",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,from:"initializing",to:"live"}),await this.ledger.setStatus(a,"live"),a.needsReconcile&&this.scheduleReconcile(s,1e3)}catch(o){let s=a?this.buildLinkKey(i.did,i.dwnUrl,a.scopeId):Ab(i.did,i.dwnUrl,i.protocol);if(o.isProgressGap&&a){console.warn(`SyncEngineLevel: ProgressGap detected for ${i.did} -> ${i.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,reason:"ProgressGap"});let c=o.gapInfo;await this.transitionToRepairing(s,a,{resumeToken:c?.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,o),this._activeLinks.delete(s),this._linkRuntimes.delete(s),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}}));let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}getOrCreateRuntime(e){let t=this._linkRuntimes.get(e);return t||(t={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,t)),t}drainCommittedPull(e){let t=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!t||!n)return 0;let i=0;for(;;){let a=t.inflight.get(t.nextCommitOrdinal);if(!a||!a.committed)break;as.commitContiguousToken(n.pull,a.token),as.setReceivedToken(n.pull,a.token),t.inflight.delete(t.nextCommitOrdinal),t.nextCommitOrdinal++,i++}return i}async transitionToRepairing(e,t,n){let i=t.status,a=t.connectivity;t.connectivity="offline",await this.ledger.setStatus(t,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let o=this._linkRuntimes.get(e);o&&(o.inflight.clear(),o.nextCommitOrdinal=o.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})}scheduleRepairRetry(e){let t=this._activeLinks.get(e);if(!t||t.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let n=this._repairAttempts.get(e)??1,i=jn.REPAIR_BACKOFF_MS,a=i[Math.min(n-1,i.length-1)],o=this._engineGeneration,s=setTimeout(async()=>{if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let c=this._activeLinks.get(e);if(!(!c||c.status!=="repairing"))try{await this.repairLink(e)}catch{c.status==="repairing"&&this.scheduleRepairRetry(e)}},a);this._repairRetryTimers.set(e,s)}repairLink(e){let t=this._activeRepairs.get(e);if(t)return t;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}async doRepairLink(e){let t=this._activeLinks.get(e);if(!t)return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:o,protocol:s}=t;this.emitEvent({type:"repair:started",tenantDid:i,remoteEndpoint:a,protocol:s,attempt:(this._repairAttempts.get(e)??0)+1});let c=(this._repairAttempts.get(e)??0)+1;if(this._repairAttempts.set(e,c),await this.closeLinkSubscriptions(t),this._engineGeneration!==n)return;let l=this.getOrCreateRuntime(e);l.inflight.clear(),l.nextDeliveryOrdinal=0,l.nextCommitOrdinal=0;try{if((await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:o,protocol:s})).aborted)return;let f=this._repairContext.get(e)?.resumeToken??t.pull.contiguousAppliedToken;if(as.resetCheckpoint(t.pull,f),await this.ledger.saveLink(t),this._engineGeneration!==n||(t.needsReconcile=!0,await this.ledger.saveLink(t),this._engineGeneration!==n))return;let p={did:i,dwnUrl:a,delegateDid:o,protocol:s,linkKey:e};try{await this.openLivePullSubscription(p)}catch(y){if(y.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${i} -> ${a}, resetting to start fresh`),as.resetCheckpoint(t.pull),await this.ledger.saveLink(t),this._engineGeneration!==n)return;await this.openLivePullSubscription(p)}else throw y}if(this._engineGeneration!==n)return;try{await this.openLocalPushSubscription(p)}catch(y){let v=this._liveSubscriptions.find(w=>w.linkKey===e);if(v){try{await v.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(w=>w!==v)}throw y}if(this._engineGeneration!==n)return;this._repairContext.delete(e),this._repairAttempts.delete(e);let h=this._repairRetryTimers.get(e);h&&(clearTimeout(h),this._repairRetryTimers.delete(e));let m=t.connectivity;t.connectivity="online",await this.ledger.setStatus(t,"live"),this.clearDeadLettersForLink(i,a,s),this.emitEvent({type:"repair:completed",tenantDid:i,remoteEndpoint:a,protocol:s}),m!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:i,remoteEndpoint:a,protocol:s,from:m,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:i,remoteEndpoint:a,protocol:s,from:"repairing",to:"live"})}catch(d){if(this._engineGeneration!==n)return;if(console.error(`SyncEngineLevel: Repair failed for ${i} -> ${a} (attempt ${c})`,d),this.emitEvent({type:"repair:failed",tenantDid:i,remoteEndpoint:a,protocol:s,attempt:c,error:String(d.message??d)}),c>=jn.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${i} -> ${a}, entering degraded_poll`),await this.enterDegradedPoll(e);return}throw d}}async closeLinkSubscriptions(e){let{tenantDid:t,remoteEndpoint:n}=e,i=this.buildLinkKey(t,n,e.scopeId),a=this._liveSubscriptions.find(s=>s.linkKey===i);if(a){try{await a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(s=>s!==a)}let o=this._localSubscriptions.find(s=>s.linkKey===i);if(o){try{await o.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(s=>s!==o)}}async enterDegradedPoll(e){let t=this._activeLinks.get(e);if(!t)return;t.connectivity="offline";let n=t.status;await this.ledger.setStatus(t,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,o=Math.floor(Math.random()*15e3),s=a+o,c=this._engineGeneration,l=setInterval(async()=>{if(this._engineGeneration!==c){clearInterval(l),this._degradedPollTimers.delete(e);return}if(t.status!=="degraded_poll"){clearInterval(l),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),await this.ledger.setStatus(t,"repairing"),await this.repairLink(e),t.status==="live"&&(clearInterval(l),this._degradedPollTimers.delete(e))}catch{await this.ledger.setStatus(t,"degraded_poll")}},s);this._degradedPollTimers.set(e,l)}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(t=>{console.error("SyncEngineLevel: post-online sync failed",t)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let t of this._activeLinks.values()){let n=t.connectivity;n!=="offline"&&(t.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:t.tenantDid,remoteEndpoint:t.remoteEndpoint,protocol:t.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(t=>{console.error("SyncEngineLevel: post-visibility sync failed",t)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}async teardownLiveSync(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()}async openLivePullSubscription(e){let{did:t,delegateDid:n,dwnUrl:i,protocol:a}=e,o=e.linkKey,s=this._activeLinks.get(o),c=s?.pull.contiguousAppliedToken;c&&(!c.streamId||!c.messageCid||!c.epoch||!c.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${t} -> ${i}`),c=void 0,s&&(as.resetCheckpoint(s.pull),await this.ledger.saveLink(s)));let l=s?.scope.kind==="protocol"?s.scope.protocolPathPrefixes?.[0]:void 0,d=a?[{protocol:a,...l?{protocolPathPrefix:l}:{}}]:[],u;n&&(u=(await this._permissionsApi.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let f=this._engineGeneration,p=async A=>{if(this._engineGeneration===f){if(A.type==="eose"){if(s){if(s.status!=="live"&&s.status!=="initializing")return;if(!as.validateTokenDomain(s.pull,A.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s);return}as.setReceivedToken(s.pull,A.cursor),this.drainCommittedPull(o),await this.ledger.saveLink(s)}if(s){let D=s.connectivity;s.connectivity="online",D!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t,remoteEndpoint:i,protocol:a,from:D,to:"online"}),s.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(A.type==="event"){let D=A.event;if(s&&s.status!=="live"&&s.status!=="initializing")return;if(s&&!as.validateTokenDomain(s.pull,A.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s);return}if(s&&!jH(D.message,s.scope)){as.setReceivedToken(s.pull,A.cursor),as.commitContiguousToken(s.pull,A.cursor),await this.ledger.saveLink(s);return}let N=s?this.getOrCreateRuntime(o):void 0,$=N?N.nextDeliveryOrdinal++:-1;N&&N.inflight.set($,{ordinal:$,token:A.cursor,committed:!1});try{let z=this.extractDataStream(D);if(!z&&jd(D)&&D.message.descriptor.dataCid){let H=await ye.getCid(D.message),Y=await aS({did:t,dwnUrl:i,delegateDid:n,protocol:a,messageCids:[H],agent:this.agent,permissionsApi:this._permissionsApi});Y.length>0&&Y[0].dataStream&&(z=Y[0].dataStream)}await this.agent.dwn.processRawMessage(t,D.message,{dataStream:z});let L=this._closureContexts.get(t);if(L&&HG(L,D.message),s&&s.scope.kind==="protocol"){let H=this.agent.dwn.node.storage.messageStore,Y=this._closureContexts.get(t);Y||(Y=wb(t,void 0,{isDelegateSession:!!n}),this._closureContexts.set(t,Y));let R=await GE(D.message,H,s.scope,Y);if(!R.complete){let C=R.failure.code,P=R.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${t} -> ${i}: ${C} \u2014 ${P}`);let S=await ye.getCid(D.message);this.recordDeadLetter({messageCid:S,tenantDid:t,remoteEndpoint:i,protocol:a,category:"closure",errorCode:C,errorDetail:P}),await this.transitionToRepairing(o,s);return}}let j=await ye.getCid(D.message);if(this._recentlyPulledCids.set(`${j}|${i}`,Date.now()+jn.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(j,i).catch(()=>{}),s&&N&&s.status==="live"){let H=N.inflight.get($);H&&(H.committed=!0),as.setReceivedToken(s.pull,A.cursor),this.drainCommittedPull(o)>0&&(await this.ledger.saveLink(s),s.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:s.tenantDid,remoteEndpoint:s.remoteEndpoint,protocol:s.protocol,position:s.pull.contiguousAppliedToken.position,messageCid:s.pull.contiguousAppliedToken.messageCid})),N.inflight.size>I6&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${t} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(o,s))}}catch(z){console.error(`SyncEngineLevel: Error processing live-pull event for ${t}`,z);try{let L=await ye.getCid(D.message);this.recordDeadLetter({messageCid:L,tenantDid:t,remoteEndpoint:i,protocol:a,category:"pull-processing",errorDetail:z.message??String(z)})}catch{}s&&await this.transitionToRepairing(o,s)}}}},h={store:!1,author:t,target:t,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:c,permissionGrantId:u}},{message:m}=await this.agent.dwn.processRequest(h);if(!m)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${i}`);let y=async A=>{let D=A??s?.pull.contiguousAppliedToken??c;D&&(!D.streamId||!D.messageCid||!D.epoch||!D.position)&&(D=void 0);let N={...h,messageParams:{...h.messageParams,cursor:D}},{message:$}=await this.agent.dwn.processRequest(N);if(!$)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${i}`);return $},v=new URL(i);v.protocol=v.protocol==="http:"?"ws:":"wss:";let w=v.toString(),x=await this.agent.rpc.sendDwnRequest({dwnUrl:w,targetDid:t,message:m,subscription:{handler:p,resubscribeFactory:y}});if(x.status.code===410){let A=new Error(`SyncEngineLevel: ProgressGap for ${t} -> ${i}: ${x.status.detail}`);throw A.isProgressGap=!0,A.gapInfo=x.error,A}if(x.status.code!==200||!x.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${t} -> ${i}: ${x.status.code} ${x.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:t,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await x.subscription.close()}});let _=this._activeLinks.get(o);if(_){let A=_.connectivity;_.connectivity="online",A!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:t,remoteEndpoint:i,protocol:a,from:A,to:"online"})}}async openLocalPushSubscription(e){let{did:t,delegateDid:n,dwnUrl:i,protocol:a}=e,o=a?[{protocol:a}]:[],s;n&&(s=(await this._permissionsApi.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let c=this._engineGeneration,l=async f=>{if(this._engineGeneration!==c||f.type!=="event")return;let p=e.linkKey,h=this._activeLinks.get(p);if(h&&!jH(f.event.message,h.scope))return;let m=p,y=await ye.getCid(f.event.message);if(y===void 0||this.isRecentlyPulled(y,i))return;let v=this.getOrCreatePushRuntime(m,{did:t,dwnUrl:i,delegateDid:n,protocol:a});v.entries.push({cid:y}),!v.flushing&&!v.timer&&this.flushPendingPushesForLink(m)},u=(await this.agent.dwn.processRequest({author:t,target:t,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:o,permissionGrantId:s},subscriptionHandler:l})).reply;if(u.status.code!==200||!u.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${t}: ${u.status.code} ${u.status.detail}`);this._localSubscriptions.push({linkKey:e.linkKey??Ab(t,i,a),did:t,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await u.subscription.close()}})}async flushPendingPushes(){await Promise.all([...this._pushRuntimes.keys()].map(async e=>{await this.flushPendingPushesForLink(e)}))}async flushPendingPushesForLink(e){let t=this._pushRuntimes.get(e);if(!t)return;let{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:s,retryCount:c}=t;if(t.entries=[],s.length===0){!t.timer&&!t.flushing&&c===0&&this._pushRuntimes.delete(e);return}let l=s.map(d=>d.cid);t.flushing=!0;try{let d=await W6({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:l,agent:this.agent,permissionsApi:this._permissionsApi});for(let u of d.succeeded)this.clearFailedMessage(u,i).catch(()=>{});for(let u of d.permanentlyFailed)await this.recordDeadLetter({messageCid:u.cid,tenantDid:n,remoteEndpoint:i,protocol:o,category:"push-permanent",errorCode:String(u.statusCode??""),errorDetail:u.detail??"permanent push failure"});if(d.failed.length>0){let u=new Set(d.failed),f=s.filter(p=>u.has(p.cid));this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:f,retryCount:c+1})}else t.retryCount=0,!t.timer&&t.entries.length===0&&this._pushRuntimes.delete(e)}catch(d){console.error(`SyncEngineLevel: Push batch failed for ${n} -> ${i}`,d),this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:o,entries:s,retryCount:c+1})}finally{t.flushing=!1;let d=this._pushRuntimes.get(e);d&&d.entries.length>0&&!d.timer&&(d.timer=setTimeout(()=>{d.timer=void 0,this.flushPendingPushesForLink(e)},Dge))}}requeueOrReconcile(e,t){let n=jn.PUSH_RETRY_BACKOFF_MS.length,i=this.getOrCreatePushRuntime(e,t);if(t.retryCount>=n){for(let s of t.entries)this.recordDeadLetter({messageCid:s.cid,tenantDid:t.did,remoteEndpoint:t.dwnUrl,protocol:t.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${n} attempts`});i.timer&&clearTimeout(i.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:t.did,remoteEndpoint:t.dwnUrl,protocol:t.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}i.entries.push(...t.entries),i.retryCount=t.retryCount;let a=jn.PUSH_RETRY_BACKOFF_MS[t.retryCount]??2e3;i.timer&&clearTimeout(i.timer),i.timer=setTimeout(()=>{i.timer=void 0,this.flushPendingPushesForLink(e)},a)}createLinkReconciler(e){return new sS({getLocalRoot:async(t,n,i)=>this.getLocalRoot(t,n,i),getRemoteRoot:async(t,n,i,a)=>this.getRemoteRoot(t,n,i,a),diffWithRemote:async t=>this.diffWithRemote(t),pullMessages:async t=>this.pullMessages(t),pushMessages:async t=>this.pushMessages(t),shouldContinue:e})}scheduleReconcile(e,t=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this.reconcileLink(e)},t);this._reconcileTimers.set(e,i)}async reconcileLink(e){let t=this._reconcileInFlight.get(e);if(t)return t;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n}async doReconcileLink(e){let t=this._activeLinks.get(e);if(!t||t.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:o,protocol:s}=t;try{let c=await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:o,protocol:s},{verifyConvergence:!0});if(c.aborted)return;c.converged?(await this.ledger.clearNeedsReconcile(t),this.clearDeadLettersForLink(i,a,s),this.emitEvent({type:"reconcile:completed",tenantDid:i,remoteEndpoint:a,protocol:s})):this.scheduleReconcile(e,5e3)}catch(c){console.error(`SyncEngineLevel: Reconciliation failed for ${i} -> ${a}`,c),this.scheduleReconcile(e,5e3)}}getOrCreatePushRuntime(e,t){let n=this._pushRuntimes.get(e);return n||(n={...t,entries:[],retryCount:0},this._pushRuntimes.set(e,n)),n}buildLinkKey(e,t,n){return n?CH(e,t,n):Ab(e,t)}async getCursor(e){let t=this._db.sublevel("syncCursors");try{let n=await t.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}await this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async deleteLegacyCursor(e){let t=this._db.sublevel("syncCursors");try{await t.del(e)}catch{}}extractDataStream(e){if(!jd(e))return;let t=e.message.encodedData;if(t){delete e.message.encodedData;let n=De.base64UrlToBytes(t);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let t=await Al(),n=new Map;for(let i=0;i<=Ige;i++)n.set(i,an(t[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,t=>t==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,t,n){let i=this.stateIndex;if(i){let c=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return an(c)}let a=await this.getSyncPermissionGrantId(e,t,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:t,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,t,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:t,targetDid:e,message:o.message})).root??""}async diffWithRemote({did:e,dwnUrl:t,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,OH),o=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:OH,permissionGrantId:o}}),c=await this.agent.rpc.sendDwnRequest({dwnUrl:t,targetDid:e,message:s.message});if(c.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${c.status.code}: ${c.status.detail}`);let l=o,d=[];for(let u of c.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);d.push(...f)}return{onlyRemote:c.onlyRemote??[],onlyLocal:d}}async collectLocalSubtreeHashes(e,t,n){let i={},a=await this.getDefaultHashHex(n),o=this.stateIndex,s=async(c,l)=>{let d;if(o){let u=jn.parseBitPrefix(c),f=t!==void 0?await o.getProtocolSubtreeHash(e,t,u):await o.getSubtreeHash(e,u);d=an(f)}else d=await this.getLocalSubtreeHash(e,c,void 0,t);if(d!==a){if(l>=n){i[c]=d;return}await Promise.all([s(c+"0",l+1),s(c+"1",l+1)])}};return await s("",0),i}async getLocalSubtreeHash(e,t,n,i,a){let o=this.stateIndex;if(o){let l=jn.parseBitPrefix(t),d=i!==void 0?await o.getProtocolSubtreeHash(e,i,l):await o.getSubtreeHash(e,l);return an(d)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:t,protocol:i,permissionGrantId:a}})).reply.hash??""}async getLocalLeaves(e,t,n,i,a){let o=this.stateIndex;if(o){let l=jn.parseBitPrefix(t);return i!==void 0?await o.getProtocolLeaves(e,i,l):await o.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:t,protocol:i,permissionGrantId:a}})).reply.entries??[]}async pullMessages({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,prefetched:o}){let s=await BH({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let c of s)await this.recordDeadLetter({messageCid:c,tenantDid:e,remoteEndpoint:t,protocol:i,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})}evictExpiredEchoEntries(){let e=Date.now();for(let[t,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(t);if(this._recentlyPulledCids.size>jn.ECHO_SUPPRESS_MAX_ENTRIES){let t=this._recentlyPulledCids.size-jn.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=t)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,t){let n=`${e}|${t}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}async pushMessages({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a}){return W6({did:e,dwnUrl:t,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return bg(e)}async clearDeadLettersForLink(e,t,n){let i=[];try{for await(let[a,o]of this._deadLetters.iterator()){let s=JSON.parse(o);s.tenantDid===e&&s.remoteEndpoint===t&&s.protocol===n&&i.push({type:"del",key:a})}i.length>0&&await this._deadLetters.batch(i)}catch(a){if(a.code!=="LEVEL_DATABASE_NOT_OPEN")throw a}}static deadLetterKey(e,t){return t?`${e}|${t}`:e}async recordDeadLetter(e){let t={...e,failedAt:new Date().toISOString()},n=jn.deadLetterKey(e.messageCid,e.remoteEndpoint);try{await this._deadLetters.put(n,JSON.stringify(t))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}}async getFailedMessages(e){let t=[];for await(let[,n]of this._deadLetters.iterator()){let i=JSON.parse(n);(!e||i.tenantDid===e)&&t.push(i)}return t.sort((n,i)=>i.failedAt.localeCompare(n.failedAt)),t}async clearFailedMessage(e,t){if(t){let a=jn.deadLetterKey(e,t);try{return await this._deadLetters.get(a),await this._deadLetters.del(a),!0}catch(o){if(o.code==="LEVEL_NOT_FOUND")return!1;throw o}}let n=!1,i=[];for await(let[a,o]of this._deadLetters.iterator())JSON.parse(o).messageCid===e&&(i.push({type:"del",key:a}),n=!0);return i.length>0&&await this._deadLetters.batch(i),n}async clearAllFailedMessages(e){if(!e){await this._deadLetters.clear();return}let t=[];for await(let[n,i]of this._deadLetters.iterator())JSON.parse(i).tenantDid===e&&t.push({type:"del",key:n});t.length>0&&await this._deadLetters.batch(t)}async getSyncHealth(){let e=0;for await(let i of this._deadLetters.iterator())e++;let t=0,n=await this.ledger.getAllLinks();for(let i of n)(i.status==="repairing"||i.status==="degraded_poll")&&t++;return{connectivity:this.connectivityState,failedMessageCount:e,degradedLinkCount:t}}async getSyncTargets(){let e=[];for await(let[t,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch(c){console.warn(`SyncEngineLevel: Corrupt sync options for ${t}, falling back to global sync:`,c),i={protocols:[]}}let{protocols:a,delegateDid:o}=i,s=await this.agent.dwn.getDwnEndpointUrlsForTarget(t);if(s.length!==0)for(let c of s)if(a.length===0)e.push({did:t,delegateDid:o,dwnUrl:c});else for(let l of a)e.push({did:t,delegateDid:o,dwnUrl:c,protocol:l})}return e}async getSyncPermissionGrantId(e,t,n){return t?(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:t,protocol:n,cached:!0})).grant.id:void 0}};jn.ECHO_SUPPRESS_TTL_MS=6e4,jn.ECHO_SUPPRESS_MAX_ENTRIES=1e4,jn.MAX_CONSECUTIVE_FAILURES=5,jn.MAX_BACKOFF_MULTIPLIER=4,jn.MAX_REPAIR_ATTEMPTS=3,jn.REPAIR_BACKOFF_MS=[1e3,3e3,1e4],jn.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];var Pg=jn;g();Xn();ea();Sr();import{Level as Fge}from"level";g();g();g();Sr();Pn();g();g();var KH=Tn(JE(),1);Sr();var xg=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},cS=class{constructor({ttl:e="15m"}={}){this.cache=new xi.default({ttl:(0,KH.default)(e)})}get(e){return xg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,t){return xg(this,void 0,void 0,function*(){this.cache.set(e,t)})}delete(e){return xg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return xg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return xg(this,void 0,void 0,function*(){})}close(){return xg(this,void 0,void 0,function*(){})}};g();Pn();Xn();g();var Eg=class extends Error{constructor(e,t){super(t??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var Sg;(function(r){r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.ParseError=-32700]="ParseError",r[r.TransportError=-32300]="TransportError",r[r.BadRequest=-50400]="BadRequest",r[r.Unauthorized=-50401]="Unauthorized",r[r.Forbidden=-50403]="Forbidden",r[r.Conflict=-50409]="Conflict",r[r.TooManyRequests=-50429]="TooManyRequests"})(Sg||(Sg={}));var kg=(r,e,t)=>({jsonrpc:"2.0",id:r,method:e,params:t}),dS=(r,e,t,n)=>({jsonrpc:"2.0",id:r,method:e,params:t,subscription:{id:n??null}}),NH=(r,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:r}});function Mh(r){try{return JSON.parse(r)}catch{return null}}var J6=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Rge=3,Cge=500,$ge=1e4,Bge=3e4,UH=new Set([408,429,500,502,503,504]);function Oge(r,e){return r instanceof TypeError?!0:e?UH.has(e.status):!1}function jge(r,e,t){let n=Math.min(e*Math.pow(2,r),t),i=.5+Math.random()*.5;return n*i}function Mge(r){let e=r.headers.get("retry-after");if(e===null)return;let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var lS=class r{constructor(e,t){var n,i,a;this.serverInfoCache=e??new cS,this._retryOptions={maxRetries:(n=t?.maxRetries)!==null&&n!==void 0?n:Rge,baseDelayMs:(i=t?.baseDelayMs)!==null&&i!==void 0?i:Cge,maxDelayMs:(a=t?.maxDelayMs)!==null&&a!==void 0?a:$ge}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return J6(this,void 0,void 0,function*(){var t,n,i;let a=bn.randomUuid(),o=kg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),s={"dwn-request":JSON.stringify(o)},c={method:"POST",headers:s};if(e.data){s["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(r.isBunRuntime()){let h=yield Wt.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((t=l.headers.get("retry-after"))!==null&&t!==void 0?t:"1",10);throw new Eg(p)}let d,u=l.headers.has("dwn-response");if(u){let p=Mh(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=Mh(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Sg.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new Eg(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Wt.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return J6(this,void 0,void 0,function*(){var t;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let o=parseInt((t=a.headers.get("retry-after"))!==null&&t!==void 0?t:"1",10);throw new Eg(o)}if(a.ok){let o=yield a.json(),s={maxFileSize:o.maxFileSize,maxInFlight:o.maxInFlight,providerAuth:o.providerAuth,registrationRequirements:o.registrationRequirements,server:o.server,sdkVersion:o.sdkVersion,url:o.url,version:o.version,webSocketSupport:o.webSocketSupport};return this.serverInfoCache.set(e,s),s}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,t){return J6(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,o,s;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Bge),p=Object.assign(Object.assign({},t),{signal:t?.signal?AbortSignal.any([t.signal,f]):f}),h=yield fetch(e,p);if(!UH.has(h.status)||c===n)return h;s=h}catch(f){if(!Oge(f)||c===n)throw f;o=f}let l=s?Mge(s):void 0,d=jge(c,i,a),u=l!==void 0?Math.max(l,d):d;yield new Promise(f=>{setTimeout(f,u)})}if(s)return s;throw o})}};g();Pn();var Tb=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})};function Z6(r){return typeof r=="string"?r:r instanceof ArrayBuffer?new TextDecoder().decode(r):r instanceof Uint8Array?new TextDecoder().decode(r):String(r)}var LH=3e3,Kge=3e4,Nge=1e3,Uge=3e4,Lge=1/0,qge=3e4,zge=1e4,uS=class r{constructor(e,t,n,i){this.socket=e,this.responseTimeout=t,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return Tb(this,arguments,void 0,function*(t,n={}){var i;let{connectTimeout:a=LH,responseTimeout:o=Kge}=n,s;try{s=yield r.createWebSocket(t,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new r(s,o,t,n);return c.wireSocket(s),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return Tb(this,void 0,void 0,function*(){return new Promise((t,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=bn.randomUuid());let a=o=>{let s=Mh(Z6(o.data));if(s.id===e.id)return this.messageHandlers.delete(e.id),t(s)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,t){return Tb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=Mh(Z6(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),t(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let o=yield this.request(e);return o.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:o}):{response:o,close:()=>Tb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let t=bn.randomUuid(),n=dS(t,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,t){return new Promise((n,i)=>{let a=new WebSocket(e),o=()=>{l(),n(a)},s=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},t),l=()=>{clearTimeout(c),a.removeEventListener("open",o),a.removeEventListener("error",s)};a.addEventListener("open",o),a.addEventListener("error",s)})}wireSocket(e){e.addEventListener("message",t=>{let n=Mh(Z6(t.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(t)}),e.addEventListener("close",()=>{var t,n,i,a,o;if(this._isConnected=!1,this.stopHeartbeat(),this.closedByUser){(n=(t=this.options).onclose)===null||n===void 0||n.call(t);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((o=this.options.autoReconnect)!==null&&o!==void 0?o:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",t=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,t)})}rejectPendingRequests(){for(let[e,t]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:Sg.TransportError,message:"WebSocket connection closed unexpectedly"}});t({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,t;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:qge;if(n<=0)return;let i=(t=this.options.heartbeatTimeout)!==null&&t!==void 0?t:zge;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,o={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(o)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,t,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:Nge,o=(t=this.options.maxReconnectDelay)!==null&&t!==void 0?t:Uge,s=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Lge,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:LH,l=0,d=()=>Tb(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>s){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),o)*(.5+Math.random()*.5);if(yield new Promise(v=>setTimeout(v,y)),this.closedByUser){this.reconnecting=!1;return}try{let v=yield r.createWebSocket(this.url,c);this.socket=v,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(v),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};g();g();g();Pn();g();Pn();var _g=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Ib=class r{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return _g(this,void 0,void 0,function*(){let t=new URL(e.dwnUrl);if(t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${t.protocol}`);if(!r.connections.has(t.host))try{let c=yield r.createConnection(t);r.connections.set(t.host,c)}catch(c){throw new Error(`Error connecting to ${t.host}: ${c.message}`)}let i=r.connections.get(t.host),{targetDid:a,message:o,subscription:s}=e;return s?r.subscriptionRequest(i,a,o,s.handler,s.resubscribeFactory):r.processMessage(i,a,o)})}static createConnection(e){return _g(this,void 0,void 0,function*(){let t=e.host,n=new Map,i=yield uS.connect(e.toString(),{onclose:()=>{r.connections.delete(t);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let o of n.values())o.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};r.connections.set(t,a),r.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,t,n){return _g(this,void 0,void 0,function*(){let i=bn.randomUuid(),a=kg(i,"dwn.processMessage",{target:t,message:n}),{socket:o}=e,s=yield o.request(a),{error:c,result:l}=s;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,t,n,i,a){return _g(this,void 0,void 0,function*(){let o=bn.randomUuid(),s=bn.randomUuid(),c=dS(o,"rpc.subscribe.dwn.processMessage",{target:t,message:n},s),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,y=>{let{result:v,error:w}=y;if(w){let _=d.get(s);_&&_.subscription.close(),d.delete(s);return}let x=v.subscription;if(i(x),"cursor"in x&&x.cursor){let _=d.get(s);_&&(_.lastCursor=x.cursor),l.send(NH(s,x.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let y=()=>_g(this,void 0,void 0,function*(){d.delete(s),yield f()}),v={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:t,message:n,handler:i,resubscribeFactory:a};d.set(s,v),m.subscription.close=y}return m})}static resubscribeAll(e){return _g(this,void 0,void 0,function*(){let t=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of t)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield r.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Ib.connections=new Map;var Db=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function s(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?a(d.value):i(d.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},qH;(function(r){r.Create="did.create",r.Resolve="did.resolve"})(qH||(qH={}));var Ag=class{constructor(e=[]){this.transportClients=new Map,e=[new Y6,new X6,...e];for(let t of e)for(let n of t.transportProtocols)this.transportClients.set(n,t)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Db(this,void 0,void 0,function*(){let t=new URL(e.url),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let t=new URL(e.dwnUrl),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Db(this,void 0,void 0,function*(){let t=new URL(e),n=this.transportClients.get(t.protocol);if(!n){let i=new Error(`no ${t.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},Y6=class extends lS{sendDidRequest(e){return Db(this,void 0,void 0,function*(){let t=bn.randomUuid(),n=kg(t,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let o=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(o.ok){if(a=yield o.json(),a.error){let{code:s,message:c}=a.error;throw new Error(`JSON RPC (${s}) - ${c}`)}}else throw new Error(`HTTP (${o.status}) - ${o.statusText}`)}catch(o){throw new Error(`Error encountered while processing response from ${e.url}: ${o.message}`)}return a.result})}},X6=class extends Ib{sendDidRequest(e){return Db(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Db(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var zH=class r{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:t,permissionsApi:n,keyManager:i}=r.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=t,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await vo.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:t}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:t}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:t,testDataLocation:n}){t??="memory",n??="__TESTDATA__";let i=z=>`${n}/${z}`,a=new xo,o=new Ag,s={keyStore:new yg,identityStore:new wg,didStore:new hg,clear:()=>{s.keyStore._protocolInitializedCache?.clear(),s.identityStore._protocolInitializedCache?.clear(),s.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:l,identityApi:d,keyManager:u,didResolverCache:f,vaultStore:p,permissionsApi:h}=t==="memory"?r.useMemoryStores():r.useDiskStores({testDataLocation:n,stores:s}),m=new If({blockstoreLocation:i("DWN_DATASTORE")}),y=new $f({location:i("DWN_STATEINDEX")}),v=new Cf,w=new Rf({location:i("DWN_RESUMABLETASKSTORE")}),x=new Df({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),_=await Vl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:v,messageStore:x,resumableTaskStore:w}),A=new Vl({dwn:_,localDwnStrategy:"off"}),D=new Fge(i("SYNC_STORE")),N=new Pg({db:D}),$=new e({agentVault:c,cryptoApi:a,didApi:l,dwnApi:A,identityApi:d,keyManager:u,permissionsApi:h,rpcClient:o,syncApi:N});return new r({agent:$,agentStores:t,didResolverCache:f,dwn:_,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:x,dwnResumableTaskStore:w,dwnStores:s,syncStore:D,vaultStore:p})}static useDiskStores({agent:e,testDataLocation:t,stores:n}){let i=m=>`${t}/${m}`,a=new $m({location:i("VAULT_STORE")}),o=new Oh({keyDerivationWorkFactor:1,store:a}),{didStore:s,identityStore:c,keyStore:l}=n,d=new Bf({location:i("DID_RESOLVERCACHE")}),u=new Dh({agent:e,didMethods:[vo,bo],resolverCache:d,store:s}),f=new jh({agent:e,store:c}),p=new As({agent:e,keyStore:l}),h=new _s({agent:e});return{agentVault:o,didApi:u,didResolverCache:d,identityApi:f,keyManager:p,permissionsApi:h,vaultStore:a}}static useMemoryStores({agent:e}={}){let t=new xu,n=new Oh({keyDerivationWorkFactor:1,store:t}),i=new mE,a=new Dh({agent:e,didMethods:[vo,bo],resolverCache:i,store:new mg}),o=new As({agent:e,keyStore:new gg}),s=new jh({agent:e,store:new vg}),c=new _s({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:s,keyManager:o,permissionsApi:c,vaultStore:t}}};g();ea();Sr();Pn();Xn();function Gge({baseURL:r,endpoint:e,authParam:t,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return vb(r,"par");case"authorize":if(!t)throw new Error("authParam must be provided when building an authorize URL");return vb(r,`authorize/${t}.jwt`);case"callback":return vb(r,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return vb(r,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function Hge({did:r,data:e}){let t=he.object({alg:"EdDSA",kid:r.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await r.getSigner()).sign({data:he.string(`${t}.${n}`).toUint8Array()}),o=he.uint8Array(a).toBase64Url();return`${t}.${n}.${o}`}async function FH({jwt:r}){let[e,t,n]=r.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await bo.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:o}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!o)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Yc().verify({key:o,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${t}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(t).toObject()}async function Vge({jwt:r,encryptionKey:e}){let t={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=bn.randomBytes(24),i=he.object(t).toUint8Array(),a=he.string(r).toUint8Array(),o=await Qc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),s=o.subarray(0,-16),c=o.subarray(-16);return[he.object(t).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(s).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function GH({jwe:r,encryptionKey:e}){let[t,,n,i,a]=r.split("."),o=he.base64Url(e).toUint8Array(),s=he.base64Url(t).toUint8Array(),c=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),d=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...d]),f=await Qc.decryptRaw({data:u,keyBytes:o,nonce:c,additionalData:s});return he.uint8Array(f).toString()}async function Wge(r,e){let t=await r.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=t.privateKeys?.[0];n.alg="EdDSA";let a=await Un.convertPublicKeyToX25519({publicKey:n}),o=await Un.convertPrivateKeyToX25519({privateKey:i}),s=await At.sharedSecret({privateKeyA:o,publicKeyB:a});return Nm.deriveKeyBytes({baseKeyBytes:new Uint8Array(s),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function Jge({jwt:r,encryptionKey:e,delegateDidKeyId:t,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:t},a=bn.randomBytes(24),o=n?{...i,pin:n}:{...i},s=he.object(o).toUint8Array(),c=he.string(r).toUint8Array(),l=await Qc.encryptRaw({data:c,keyBytes:e,nonce:a,additionalData:s}),d=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(d).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function Zge(r,e,t){let[n,,i,a,o]=e.split("."),s=he.base64Url(n).toObject();if(!s.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let c=await bo.resolve(s.kid.split("#")[0]),l=await Tg.deriveSharedKey(r,c.didDocument),d=t?{...s,pin:t}:{...s},u=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),p=he.base64Url(a).toUint8Array(),h=he.base64Url(o).toUint8Array(),m=new Uint8Array([...p,...h]),y=await Qc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function Yge(r){let e=bn.randomBytes(16),t=bn.randomBytes(16);return{...r,nonce:he.uint8Array(t).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:r.supportedDidMethods??["did:dht","did:jwk"]}}async function Xge(r,e){let n=await(await fetch(r,{signal:AbortSignal.timeout(3e4)})).text(),i=await GH({jwe:n,encryptionKey:e});return await FH({jwt:i})}async function Qge(r){let e=Math.floor(Date.now()/1e3);return{...r,iat:e,exp:e+600}}function ewe(r){return Ch(r)?!0:r.interface===ve.Protocols&&r.method===me.Configure}async function twe(r,e,t,n,i){let a=new _s({agent:t});Ms.log(`Creating permission grants for ${n.length} scopes...`);let o=await Promise.all(n.map(l=>{let d=ewe(l),u=new Set([me.Read,me.Query,me.Subscribe]),p=Ch(l)&&u.has(l.method)&&i?i:void 0;return a.createGrant({delegated:d,store:!0,grantedTo:e.uri,scope:l,dateExpires:"2040-06-25T16:09:16.693356Z",author:r,delegateKeyDelivery:p})})),s=await t.dwn.getDwnEndpointUrlsForTarget(r);Ms.log(`Sending ${o.length} permission grants to ${s.length} DWN endpoint(s)...`);let c=o.map(async l=>{let{encodedData:d,...u}=l.message,f=he.base64Url(d).toUint8Array(),p=!1;for(let h of s)try{let m=await t.rpc.sendDwnRequest({dwnUrl:h,targetDid:r,message:u,data:new Blob([f])});m.status.code===202||m.status.code===409?p=!0:Ms.error(`Grant send to ${h} returned ${m.status.code}: ${m.status.detail}`)}catch(m){Ms.error(`Grant send to ${h} failed: ${m.message}`)}if(!p)throw new Error("Could not send permission grant to any DWN endpoint.");return l.message});try{return await Promise.all(c)}catch(l){throw Ms.error(`Error during batch-send of permission grants: ${l}`),l}}async function rwe(r,e,t){let n=Object.values(t.types??{}).some(a=>a?.encryptionRequired===!0),i=await e.processDwnRequest({author:r,messageType:Re.ProtocolsQuery,target:r,messageParams:{filter:{protocol:t.protocol}}});if(i.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${i.reply.status.detail}`);if(i.reply.entries===void 0||i.reply.entries.length===0){Ms.log(`Protocol does not exist, creating: ${t.protocol}`);let{reply:a,message:o}=await e.sendDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,messageParams:{definition:t},encryption:n||void 0});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`);await e.processDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,rawMessage:o})}else{Ms.log(`Protocol already exists: ${t.protocol}`);let a=i.reply.entries[0],{reply:o}=await e.sendDwnRequest({author:r,target:r,messageType:Re.ProtocolsConfigure,rawMessage:a});if(o.status.code!==202&&o.status.code!==409)throw new Error(`Could not send protocol: ${o.status.detail}`)}}async function HH(r,e,t,n,i){let a=new Set([me.Read,me.Query,me.Subscribe]),o=n.filter(p=>Ch(p)&&a.has(p.method));if(o.length===0)return[];for(let p of o)if("contextId"in p&&p.contextId)throw new Error(`Encrypted delegate access scoped by contextId is not supported yet; use protocol-wide permissions for protocol '${t}'.`);let{multiParty:s}=Q6(i);if(s.length>0)throw new Error(`deriveScopedDecryptionKeys called for protocol with multi-party roots [${s.join(", ")}]. Use deriveContextKeysForDelegate for multi-party protocols.`);let c=o.some(p=>!("protocolPath"in p)||!p.protocolPath),{keyId:l,keyUri:d}=await na(r,e);if(c){let p=[Pt.ProtocolPath,t],h=await r.keyManager.derivePrivateKeyBytes({keyUri:d,derivationPath:p}),m=await At.bytesToPrivateKey({privateKeyBytes:h});return[{protocol:t,scope:{kind:"protocol"},derivedPrivateKey:{rootKeyId:l,derivationScheme:Pt.ProtocolPath,derivationPath:p,derivedPrivateKey:m}}]}let u=new Set;for(let p of o){let h=p.protocolPath;h&&u.add(h)}let f=[];for(let p of u){let h=p.split("/"),m=[Pt.ProtocolPath,t,...h],y=await r.keyManager.derivePrivateKeyBytes({keyUri:d,derivationPath:m}),v=await At.bytesToPrivateKey({privateKeyBytes:y});f.push({protocol:t,scope:{kind:"protocolPath",protocolPath:p,match:"exact"},derivedPrivateKey:{rootKeyId:l,derivationScheme:Pt.ProtocolPath,derivationPath:m,derivedPrivateKey:v}})}return f}function Q6(r){let e=r.structure;if(!e)return{multiParty:[],singleParty:[]};let t=[],n=[];for(let i of Object.keys(e))i.startsWith("$")||(Th(r,i)?t.push(i):n.push(i));return{multiParty:t,singleParty:n}}async function VH(r,e,t,n){let i=new Set([me.Read,me.Query,me.Subscribe]),a=n.filter(f=>Ch(f)&&i.has(f.method));if(a.length===0)return[];for(let f of a)if("contextId"in f&&f.contextId)throw new Error(`Encrypted delegate access scoped by contextId is not supported yet; use protocol-wide permissions for protocol '${t.protocol}'.`);for(let f of a)if("protocolPath"in f&&f.protocolPath)throw new Error(`Encrypted delegate access scoped by protocolPath on multi-party protocols is not supported yet; use protocol-wide permissions for protocol '${t.protocol}'.`);let{keyId:o,keyUri:s}=await na(r,e),c=t.protocol,l=Object.keys(t.structure??{}).filter(f=>!f.startsWith("$")),d=[],u=new Set;for(let f of l){let{reply:p}=await r.processDwnRequest({author:e,target:e,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:c,protocolPath:f}}});for(let h of p.entries??[]){let m=h.contextId?.split("/")[0]||h.recordId;if(!m||u.has(m))continue;u.add(m);let y=[Pt.ProtocolContext,m],v=await r.keyManager.derivePrivateKeyBytes({keyUri:s,derivationPath:y}),w=await At.bytesToPrivateKey({privateKeyBytes:v});d.push({protocol:c,contextId:m,derivedPrivateKey:{rootKeyId:o,derivationScheme:Pt.ProtocolContext,derivationPath:y,derivedPrivateKey:w}})}}return d}async function nwe(r,e,t,n){let i=await bo.create(),a=await i.export(),o=a.privateKeys[0],s=await Un.convertPrivateKeyToX25519({privateKey:o});a.privateKeys.push(s);let c=await At.privateKeyToBytes({privateKey:s}),l=[Pt.ProtocolPath,za.protocol,"contextKey"],d=await Ni.derivePrivateKeyBytes(c,l),u=await At.bytesToPrivateKey({privateKeyBytes:d}),f=await At.getPublicKey({key:u}),h={rootKeyId:i.document.verificationMethod[0].id,publicKeyJwk:f},m=[],y=[],v=[],w=e.permissionRequests.map(async R=>{let{protocolDefinition:C,permissionScopes:P}=R;if(!P.every(k=>"protocol"in k&&k.protocol===C.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");if(await rwe(r,n,C),Object.values(C.types??{}).some(k=>k?.encryptionRequired===!0)){let{multiParty:k,singleParty:I}=Q6(C);if(k.length>0&&I.length>0)throw new Error(`Encrypted delegate access for protocols with mixed single-party and multi-party roots is not supported yet. Protocol '${C.protocol}' has multi-party roots [${k.join(", ")}] and single-party roots [${I.join(", ")}].`);if(k.length>0){let K=await VH(n,r,C,P);y.push(...K);let F=new Set([me.Read,me.Query,me.Subscribe]);P.some(W=>Ch(W)&&F.has(W.method))&&v.push(C.protocol)}else{let K=await HH(n,r,C.protocol,P,C);m.push(...K)}}return Tg.createPermissionGrants(r,i,n,P,h)}),x=(await Promise.all(w)).flat(),_=new _s({agent:n}),A=[],D=[];try{D=await n.dwn.getDwnEndpointUrlsForTarget(r)}catch{}let N=x.length;for(let R=0;R<N;R++){let C=x[R],P=await _.createGrant({delegated:!0,store:!0,grantedTo:i.uri,scope:{interface:ve.Records,method:me.Write,protocol:rt.uri,contextId:C.recordId},dateExpires:"2040-06-25T16:09:16.693356Z",author:r});A.push({grantId:C.recordId,revocationGrantId:P.message.recordId});let{encodedData:S,...E}=P.message,k=he.base64Url(S).toUint8Array();for(let I of D)try{await n.rpc.sendDwnRequest({dwnUrl:I,targetDid:r,message:E,data:new Blob([k])})}catch{}x.push(P.message)}Ms.log("Building connect response...");let $=await Tg.createConnectResponse({providerDid:r,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:x,delegatePortableDid:a,delegateDecryptionKeys:m.length>0?m:void 0,delegateContextKeys:y.length>0?y:void 0,delegateMultiPartyProtocols:v.length>0?v:void 0,sessionRevocations:A.length>0?A:void 0});Ms.log("Signing connect response...");let z=await Tg.signJwt({did:i,data:$}),L=await bo.resolve(e.clientDid),j=await Tg.deriveSharedKey(i,L?.didDocument);Ms.log("Encrypting connect response...");let H=await Tg.encryptResponse({jwt:z,encryptionKey:j,delegateDidKeyId:i.document.verificationMethod[0].id,pin:t}),Y=new URLSearchParams({id_token:H,state:e.state}).toString();Ms.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:Y,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var Tg={buildConnectUrl:Gge,signJwt:Hge,verifyJwt:FH,encryptRequest:Vge,decryptRequest:GH,encryptResponse:Jge,decryptResponse:Zge,deriveSharedKey:Wge,createConnectRequest:Yge,getConnectRequest:Xge,createConnectResponse:Qge,createPermissionGrants:twe,submitConnectResponse:nwe,deriveScopedDecryptionKeys:HH,deriveContextKeysForDelegate:VH,classifyProtocolRoots:Q6};g();Sr();ea();var WH=class r{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:t,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:o,didApi:s,dwnApi:c,identityApi:l,keyManager:d,permissionsApi:u,rpcClient:f,syncApi:p}={}){return a??=new Oh({keyDerivationWorkFactor:21e4,store:new $m({location:`${e}/VAULT_STORE`})}),o??=new xo,s??=new Dh({didMethods:[vo,bo],resolverCache:new Bf({location:`${e}/DID_RESOLVERCACHE`}),store:new hg}),c||(n?c=new Vl({localDwnEndpoint:n,localDwnStrategy:t??"prefer"}):c=new Vl({dwn:await Vl.createDwn({dataPath:e,didResolver:s}),localDwnStrategy:t??"prefer"})),t&&c.setLocalDwnStrategy(t),l??=new jh({store:new wg}),d??=new As({keyStore:new yg}),u??=new _s,f??=new Ag,p??=new Pg({dataPath:e}),new r({agentDid:i,agentVault:a,cryptoApi:o,didApi:s,dwnApi:c,keyManager:d,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:p})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:t,dwnEndpoints:n}){return t=await this.vault.initialize({password:e,recoveryPhrase:t,dwnEndpoints:n}),t}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{xo as AgentCryptoApi,Dh as AgentDidApi,Bf as AgentDidResolverCache,Vl as AgentDwnApi,jh as AgentIdentityApi,_s as AgentPermissionsApi,ZG as AnonymousDwnApi,lg as BearerIdentity,R6 as ClosureFailureCode,Nye as DISCOVERY_DIR,Uye as DISCOVERY_FILENAME,pH as DWN_CONNECT_PATH,fH as DWN_PROTOCOL_SCHEME,jye as DidInterface,lo as DwnConstant,di as DwnContentEncryptionAlgorithm,Of as DwnDataStore,Ut as DwnDateSort,hg as DwnDidStore,YE as DwnDiscoveryFile,wg as DwnIdentityStore,Re as DwnInterface,Pt as DwnKeyDerivationScheme,yg as DwnKeyStore,Ir as DwnPermissionGrant,md as DwnPermissionRequest,rt as DwnPermissionsProtocol,Tg as EnboxConnectProtocol,WH as EnboxUserAgent,Oh as HdIdentityVault,jf as InMemoryDataStore,mg as InMemoryDidStore,vg as InMemoryIdentityStore,gg as InMemoryKeyStore,za as KeyDeliveryProtocolDefinition,Rh as LocalDwnDiscovery,As as LocalKeyManager,I6 as MAX_PENDING_TOKENS,zH as PlatformAgentTestHarness,as as ReplicationLedger,Pg as SyncEngineLevel,Pb as buildContextKeyDecrypter,LVe as buildDwnConnectUrl,zVe as buildDwnDiscoveryRedirectUrl,$h as buildEncryptionInput,Fye as buildExactProtocolPathDecrypter,rH as buildKmsDecryptCallback,T6 as computeScopeId,vb as concatenateUrl,wb as createClosureContext,Kye as createNodeDiscoveryFileFs,uH as decodeDwnDiscoveryPayload,tH as deriveContextEncryptionInput,$6 as detectNewParticipants,Ah as dwnMessageConstructors,oH as eagerSendContextKeyRecord,Hye as encodeDwnDiscoveryPayload,QE as encryptAndComputeCid,iH as ensureKeyDeliveryProtocol,GE as evaluateClosure,Aye as evaluateClosureBatch,aH as fetchContextKeyRecord,dg as getDwnServiceEndpointUrls,xb as getEncryptionKeyDeriver,na as getEncryptionKeyInfo,j6 as getKeyDecrypter,sHe as getPaginationCursor,nHe as getRecordAuthor,Dye as getRecordMessageCid,iHe as getRecordProtocolRole,zGe as getRootContextId,VG as getRuleSetAtPath,C6 as hasRelationalReadAccess,QG as isDidRequest,qye as isDwnMessage,Fa as isDwnRequest,xge as isIdentityMetadata,zye as isMessagesPermissionScope,Th as isMultiPartyContext,PJe as isPortableIdentity,Ch as isRecordPermissionScope,O6 as isRecordsType,jd as isRecordsWrite,XE as ivLength,Mye as localDwnServerName,nH as maybeDecryptReply,ZE as normalizeBaseUrl,qVe as parseDwnConnectUrl,oHe as pollWithTtl,FVe as readDwnDiscoveryPayloadFromUrl,eH as resolveKeyDecrypter,sH as writeContextKeyRecord};
2061
2061
  /*! Bundled license information:
2062
2062
 
2063
2063
  ieee754/index.js: