@enbox/api 0.6.27 → 0.6.28
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 +1 -1
- package/dist/browser.mjs.map +2 -2
- package/package.json +3 -3
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(a,(0,jt._)`[${i}]`)}}}function gse({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,jt._)`${e} !== undefined`,()=>r.assign((0,jt._)`${e}[${t}]`,n))}function JR(r,e,t,n=gg.Correct){let i=n===gg.Correct?jt.operators.EQ:jt.operators.NEQ,s;switch(r){case"null":return(0,jt._)`${e} ${i} null`;case"array":s=(0,jt._)`Array.isArray(${e})`;break;case"object":s=(0,jt._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,jt._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,jt._)`typeof ${e} ${i} ${r}`}return n===gg.Correct?s:(0,jt.not)(s);function o(a=jt.nil){return(0,jt.and)((0,jt._)`typeof ${e} == "number"`,a,t?(0,jt._)`isFinite(${e})`:jt.nil)}}To.checkDataType=JR;function YR(r,e,t,n){if(r.length===1)return JR(r[0],e,t,n);let i,s=(0,zL.toHash)(r);if(s.array&&s.object){let o=(0,jt._)`typeof ${e} != "object"`;i=s.null?o:(0,jt._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=jt.nil;s.number&&delete s.integer;for(let o in s)i=(0,jt.and)(i,JR(o,e,t,n));return i}To.checkDataTypes=YR;var wse={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,jt._)`{type: ${r}}`:(0,jt._)`{type: ${e}}`};function ZR(r){let e=vse(r);(0,fse.reportError)(e,wse)}To.reportTypeError=ZR;function vse(r){let{gen:e,data:t,schema:n}=r,i=(0,zL.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var HL=Te(M_=>{"use strict";g();Object.defineProperty(M_,"__esModule",{value:!0});M_.assignDefaults=void 0;var wg=$t(),bse=Zt();function xse(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)WL(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>WL(r,s,i.default))}M_.assignDefaults=xse;function WL(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,wg._)`${s}${(0,wg.getProperty)(e)}`;if(i){(0,bse.checkStrictMode)(r,`default is ignored for: ${a}`);return}let d=(0,wg._)`${a} === undefined`;o.useDefaults==="empty"&&(d=(0,wg._)`${d} || ${a} === null || ${a} === ""`),n.if(d,(0,wg._)`${a} = ${(0,wg.stringify)(t)}`)}});var Na=Te(Kr=>{"use strict";g();Object.defineProperty(Kr,"__esModule",{value:!0});Kr.validateUnion=Kr.validateArray=Kr.usePattern=Kr.callValidateCode=Kr.schemaProperties=Kr.allSchemaProperties=Kr.noPropertyInData=Kr.propertyInData=Kr.isOwnProperty=Kr.hasPropFunc=Kr.reportMissingProp=Kr.checkMissingProp=Kr.checkReportMissingProp=void 0;var ln=$t(),QR=Zt(),Bf=ja(),Pse=Zt();function _se(r,e){let{gen:t,data:n,it:i}=r;t.if(eC(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ln._)`${e}`},!0),r.error()})}Kr.checkReportMissingProp=_se;function Ese({gen:r,data:e,it:{opts:t}},n,i){return(0,ln.or)(...n.map(s=>(0,ln.and)(eC(r,e,s,t.ownProperties),(0,ln._)`${i} = ${s}`)))}Kr.checkMissingProp=Ese;function Sse(r,e){r.setParams({missingProperty:e},!0),r.error()}Kr.reportMissingProp=Sse;function VL(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ln._)`Object.prototype.hasOwnProperty`})}Kr.hasPropFunc=VL;function XR(r,e,t){return(0,ln._)`${VL(r)}.call(${e}, ${t})`}Kr.isOwnProperty=XR;function Tse(r,e,t,n){let i=(0,ln._)`${e}${(0,ln.getProperty)(t)} !== undefined`;return n?(0,ln._)`${i} && ${XR(r,e,t)}`:i}Kr.propertyInData=Tse;function eC(r,e,t,n){let i=(0,ln._)`${e}${(0,ln.getProperty)(t)} === undefined`;return n?(0,ln.or)(i,(0,ln.not)(XR(r,e,t))):i}Kr.noPropertyInData=eC;function JL(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}Kr.allSchemaProperties=JL;function Dse(r,e){return JL(e).filter(t=>!(0,QR.alwaysValidSchema)(r,e[t]))}Kr.schemaProperties=Dse;function kse({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,d,l){let c=l?(0,ln._)`${r}, ${e}, ${n}${i}`:e,u=[[Bf.default.instancePath,(0,ln.strConcat)(Bf.default.instancePath,s)],[Bf.default.parentData,o.parentData],[Bf.default.parentDataProperty,o.parentDataProperty],[Bf.default.rootData,Bf.default.rootData]];o.opts.dynamicRef&&u.push([Bf.default.dynamicAnchors,Bf.default.dynamicAnchors]);let f=(0,ln._)`${c}, ${t.object(...u)}`;return d!==ln.nil?(0,ln._)`${a}.call(${d}, ${f})`:(0,ln._)`${a}(${f})`}Kr.callValidateCode=kse;var Ase=(0,ln._)`new RegExp`;function Ise({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ln._)`${i.code==="new RegExp"?Ase:(0,Pse.useFunc)(r,i)}(${t}, ${n})`})}Kr.usePattern=Ise;function Rse(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let d=e.const("len",(0,ln._)`${t}.length`);e.forRange("i",0,d,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:QR.Type.Num},s),e.if((0,ln.not)(s),a)})}}Kr.validateArray=Rse;function Cse(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(d=>(0,QR.alwaysValidSchema)(i,d))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((d,l)=>{let c=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ln._)`${o} || ${a}`),r.mergeValidEvaluated(c,a)||e.if((0,ln.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}Kr.validateUnion=Cse});var QL=Te(Ld=>{"use strict";g();Object.defineProperty(Ld,"__esModule",{value:!0});Ld.validateKeywordUsage=Ld.validSchemaType=Ld.funcKeywordCode=Ld.macroKeywordCode=void 0;var Xo=$t(),Rp=ja(),$se=Na(),Ose=Lv();function Bse(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),d=ZL(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Xo.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Ld.macroKeywordCode=Bse;function jse(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:d}=r;Mse(d,e);let l=!a&&e.compile?e.compile.call(d.self,s,o,d):e.validate,c=ZL(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&&YL(r),y(()=>r.error());else{let v=e.async?h():p();e.modifying&&YL(r),y(()=>Nse(r,v))}}function h(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,Xo._)`await `),w=>n.assign(u,!1).if((0,Xo._)`${w} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Xo._)`${w}.errors`),()=>n.throw(w))),v}function p(){let v=(0,Xo._)`${c}.errors`;return n.assign(v,null),m(Xo.nil),v}function m(v=e.async?(0,Xo._)`await `:Xo.nil){let w=d.opts.passContext?Rp.default.this:Rp.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Xo._)`${v}${(0,$se.callValidateCode)(r,c,w,b)}`,e.modifying)}function y(v){var w;n.if((0,Xo.not)((w=e.valid)!==null&&w!==void 0?w:u),v)}}Ld.funcKeywordCode=jse;function YL(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Xo._)`${n.parentData}[${n.parentDataProperty}]`))}function Nse(r,e){let{gen:t}=r;t.if((0,Xo._)`Array.isArray(${e})`,()=>{t.assign(Rp.default.vErrors,(0,Xo._)`${Rp.default.vErrors} === null ? ${e} : ${Rp.default.vErrors}.concat(${e})`).assign(Rp.default.errors,(0,Xo._)`${Rp.default.vErrors}.length`),(0,Ose.extendErrors)(r)},()=>r.error())}function Mse({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function ZL(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,Xo.stringify)(t)})}function Use(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")}Ld.validSchemaType=Use;function Kse({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let d=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(d);else throw new Error(d)}}Ld.validateKeywordUsage=Kse});var eq=Te(jf=>{"use strict";g();Object.defineProperty(jf,"__esModule",{value:!0});jf.extendSubschemaMode=jf.extendSubschemaData=jf.getSubschema=void 0;var qd=$t(),XL=Zt();function Lse(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,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 a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,qd._)`${r.schemaPath}${(0,qd.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,qd._)`${r.schemaPath}${(0,qd.getProperty)(e)}${(0,qd.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,XL.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}jf.getSubschema=Lse;function qse(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:c,opts:u}=e,f=a.let("data",(0,qd._)`${e.data}${(0,qd.getProperty)(t)}`,!0);d(f),r.errorPath=(0,qd.str)`${l}${(0,XL.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,qd._)`${t}`,r.dataPathArr=[...c,r.parentDataProperty]}if(i!==void 0){let l=i instanceof qd.Name?i:a.let("data",i,!0);d(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function d(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}jf.extendSubschemaData=qse;function zse(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}jf.extendSubschemaMode=zse});var tC=Te((nNe,tq)=>{"use strict";g();tq.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,s;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(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var nq=Te((oNe,rq)=>{"use strict";g();var Nf=rq.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(){};U_(e,n,i,r,"",r)};Nf.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nf.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nf.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nf.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 U_(r,e,t,n,i,s,o,a,d,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,d,l);for(var c in n){var u=n[c];if(Array.isArray(u)){if(c in Nf.arrayKeywords)for(var f=0;f<u.length;f++)U_(r,e,t,u[f],i+"/"+c+"/"+f,s,i,c,n,f)}else if(c in Nf.propsKeywords){if(u&&typeof u=="object")for(var h in u)U_(r,e,t,u[h],i+"/"+c+"/"+Fse(h),s,i,c,n,h)}else(c in Nf.keywords||r.allKeys&&!(c in Nf.skipKeywords))&&U_(r,e,t,u,i+"/"+c,s,i,c,n)}t(n,i,s,o,a,d,l)}}function Fse(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var zv=Te(Es=>{"use strict";g();Object.defineProperty(Es,"__esModule",{value:!0});Es.getSchemaRefs=Es.resolveUrl=Es.normalizeId=Es._getFullPath=Es.getFullPath=Es.inlineRef=void 0;var Gse=Zt(),Wse=tC(),Hse=nq(),Vse=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Jse(r,e=!0){return typeof r=="boolean"?!0:e===!0?!rC(r):e?iq(r)<=e:!1}Es.inlineRef=Jse;var Yse=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function rC(r){for(let e in r){if(Yse.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(rC)||typeof t=="object"&&rC(t))return!0}return!1}function iq(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!Vse.has(t)&&(typeof r[t]=="object"&&(0,Gse.eachItem)(r[t],n=>e+=iq(n)),e===1/0))return 1/0}return e}function oq(r,e="",t){t!==!1&&(e=vg(e));let n=r.parse(e);return sq(r,n)}Es.getFullPath=oq;function sq(r,e){return r.serialize(e).split("#")[0]+"#"}Es._getFullPath=sq;var Zse=/#\/?$/;function vg(r){return r?r.replace(Zse,""):""}Es.normalizeId=vg;function Qse(r,e,t){return t=vg(t),r.resolve(e,t)}Es.resolveUrl=Qse;var Xse=/^[a-z_][-a-z0-9._]*$/i;function eae(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=vg(r[t]||e),s={"":i},o=oq(n,i,!1),a={},d=new Set;return Hse(r,{allKeys:!0},(u,f,h,p)=>{if(p===void 0)return;let m=o+f,y=s[p];typeof u[t]=="string"&&(y=v.call(this,u[t])),w.call(this,u.$anchor),w.call(this,u.$dynamicAnchor),s[f]=y;function v(b){let T=this.opts.uriResolver.resolve;if(b=vg(y?T(y,b):b),d.has(b))throw c(b);d.add(b);let D=this.refs[b];return typeof D=="string"&&(D=this.refs[D]),typeof D=="object"?l(u,D.schema,b):b!==vg(m)&&(b[0]==="#"?(l(u,a[b],b),a[b]=u):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!Xse.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function l(u,f,h){if(f!==void 0&&!Wse(u,f))throw c(h)}function c(u){return new Error(`reference "${u}" resolves to more than one schema`)}}Es.getSchemaRefs=eae});var Wv=Te(Mf=>{"use strict";g();Object.defineProperty(Mf,"__esModule",{value:!0});Mf.getData=Mf.KeywordCxt=Mf.validateFunctionCode=void 0;var uq=KL(),aq=qv(),iC=VR(),K_=qv(),tae=HL(),Gv=QL(),nC=eq(),et=$t(),Tt=ja(),rae=zv(),ou=Zt(),Fv=Lv();function nae(r){if(pq(r)&&(mq(r),hq(r))){sae(r);return}fq(r,()=>(0,uq.topBoolOrEmptySchema)(r))}Mf.validateFunctionCode=nae;function fq({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,et._)`${Tt.default.data}, ${Tt.default.valCxt}`,n.$async,()=>{r.code((0,et._)`"use strict"; ${cq(t,i)}`),oae(r,i),r.code(s)}):r.func(e,(0,et._)`${Tt.default.data}, ${iae(i)}`,n.$async,()=>r.code(cq(t,i)).code(s))}function iae(r){return(0,et._)`{${Tt.default.instancePath}="", ${Tt.default.parentData}, ${Tt.default.parentDataProperty}, ${Tt.default.rootData}=${Tt.default.data}${r.dynamicRef?(0,et._)`, ${Tt.default.dynamicAnchors}={}`:et.nil}}={}`}function oae(r,e){r.if(Tt.default.valCxt,()=>{r.var(Tt.default.instancePath,(0,et._)`${Tt.default.valCxt}.${Tt.default.instancePath}`),r.var(Tt.default.parentData,(0,et._)`${Tt.default.valCxt}.${Tt.default.parentData}`),r.var(Tt.default.parentDataProperty,(0,et._)`${Tt.default.valCxt}.${Tt.default.parentDataProperty}`),r.var(Tt.default.rootData,(0,et._)`${Tt.default.valCxt}.${Tt.default.rootData}`),e.dynamicRef&&r.var(Tt.default.dynamicAnchors,(0,et._)`${Tt.default.valCxt}.${Tt.default.dynamicAnchors}`)},()=>{r.var(Tt.default.instancePath,(0,et._)`""`),r.var(Tt.default.parentData,(0,et._)`undefined`),r.var(Tt.default.parentDataProperty,(0,et._)`undefined`),r.var(Tt.default.rootData,Tt.default.data),e.dynamicRef&&r.var(Tt.default.dynamicAnchors,(0,et._)`{}`)})}function sae(r){let{schema:e,opts:t,gen:n}=r;fq(r,()=>{t.$comment&&e.$comment&&gq(r),uae(r),n.let(Tt.default.vErrors,null),n.let(Tt.default.errors,0),t.unevaluated&&aae(r),yq(r),pae(r)})}function aae(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,et._)`${t}.evaluated`),e.if((0,et._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,et._)`${r.evaluated}.props`,(0,et._)`undefined`)),e.if((0,et._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,et._)`${r.evaluated}.items`,(0,et._)`undefined`))}function cq(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,et._)`/*# sourceURL=${t} */`:et.nil}function cae(r,e){if(pq(r)&&(mq(r),hq(r))){dae(r,e);return}(0,uq.boolOrEmptySchema)(r,e)}function hq({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 pq(r){return typeof r.schema!="boolean"}function dae(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&gq(r),fae(r),hae(r);let s=n.const("_errs",Tt.default.errors);yq(r,s),n.var(e,(0,et._)`${s} === ${Tt.default.errors}`)}function mq(r){(0,ou.checkUnknownRules)(r),lae(r)}function yq(r,e){if(r.opts.jtd)return dq(r,[],!1,e);let t=(0,aq.getSchemaTypes)(r.schema),n=(0,aq.coerceAndCheckDataType)(r,t);dq(r,t,!n,e)}function lae(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,ou.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function uae(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,ou.checkStrictMode)(r,"default is ignored in the schema root")}function fae(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,rae.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function hae(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function gq({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,et._)`${Tt.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,et.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,et._)`${Tt.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function pae(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,et._)`${Tt.default.errors} === 0`,()=>e.return(Tt.default.data),()=>e.throw((0,et._)`new ${i}(${Tt.default.vErrors})`)):(e.assign((0,et._)`${n}.errors`,Tt.default.vErrors),s.unevaluated&&mae(r),e.return((0,et._)`${Tt.default.errors} === 0`))}function mae({gen:r,evaluated:e,props:t,items:n}){t instanceof et.Name&&r.assign((0,et._)`${e}.props`,t),n instanceof et.Name&&r.assign((0,et._)`${e}.items`,n)}function dq(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:d,self:l}=r,{RULES:c}=l;if(s.$ref&&(d.ignoreKeywordsWithRef||!(0,ou.schemaHasRulesButRef)(s,c))){i.block(()=>vq(r,"$ref",c.all.$ref.definition));return}d.jtd||yae(r,e),i.block(()=>{for(let f of c.rules)u(f);u(c.post)});function u(f){(0,iC.shouldUseGroup)(s,f)&&(f.type?(i.if((0,K_.checkDataType)(f.type,o,d.strictNumbers)),lq(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,K_.reportTypeError)(r)),i.endIf()):lq(r,f),a||i.if((0,et._)`${Tt.default.errors} === ${n||0}`))}}function lq(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,tae.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,iC.shouldUseRule)(n,s)&&vq(r,s.keyword,s.definition,e.type)})}function yae(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(gae(r,e),r.opts.allowUnionTypes||wae(r,e),vae(r,r.dataTypes))}function gae(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{wq(r.dataTypes,t)||oC(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),xae(r,e)}}function wae(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&oC(r,"use allowUnionTypes to allow union type keyword")}function vae(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,iC.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>bae(e,o))&&oC(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function bae(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function wq(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function xae(r,e){let t=[];for(let n of r.dataTypes)wq(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function oC(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,ou.checkStrictMode)(r,e,r.opts.strictTypes)}var L_=class{constructor(e,t,n){if((0,Gv.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,ou.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",bq(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Gv.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,et.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,et.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,et._)`${t} !== undefined && (${(0,et.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?Fv.reportExtraError:Fv.reportError)(this,this.def.error,t)}$dataError(){(0,Fv.reportError)(this,this.def.$dataError||Fv.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Fv.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=et.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=et.nil,t=et.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,et.or)((0,et._)`${i} === undefined`,t)),e!==et.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==et.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,et.or)(o(),a());function o(){if(n.length){if(!(t instanceof et.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,et._)`${(0,K_.checkDataTypes)(d,t,s.opts.strictNumbers,K_.DataType.Wrong)}`}return et.nil}function a(){if(i.validateSchema){let d=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,et._)`!${d}(${t})`}return et.nil}}subschema(e,t){let n=(0,nC.getSubschema)(this.it,e);(0,nC.extendSubschemaData)(n,this.it,e),(0,nC.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return cae(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ou.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=ou.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,et.Name)),!0}};Mf.KeywordCxt=L_;function vq(r,e,t,n){let i=new L_(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Gv.funcKeywordCode)(i,t):"macro"in t?(0,Gv.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Gv.funcKeywordCode)(i,t)}var Pae=/^\/(?:[^~]|~0|~1)*$/,_ae=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function bq(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return Tt.default.rootData;if(r[0]==="/"){if(!Pae.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=Tt.default.rootData}else{let l=_ae.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(d("property/index",c));return n[e-c]}if(c>e)throw new Error(d("data",c));if(s=t[e-c],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,et._)`${s}${(0,et.getProperty)((0,ou.unescapeJsonPointer)(l))}`,o=(0,et._)`${o} && ${s}`);return o;function d(l,c){return`Cannot access ${l} ${c} levels up, current level is ${e}`}}Mf.getData=bq});var q_=Te(aC=>{"use strict";g();Object.defineProperty(aC,"__esModule",{value:!0});var sC=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};aC.default=sC});var Hv=Te(lC=>{"use strict";g();Object.defineProperty(lC,"__esModule",{value:!0});var cC=zv(),dC=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,cC.resolveUrl)(e,t,n),this.missingSchema=(0,cC.normalizeId)((0,cC.getFullPath)(e,this.missingRef))}};lC.default=dC});var Vv=Te(Ma=>{"use strict";g();Object.defineProperty(Ma,"__esModule",{value:!0});Ma.resolveSchema=Ma.getCompilingSchema=Ma.resolveRef=Ma.compileSchema=Ma.SchemaEnv=void 0;var Kc=$t(),Eae=q_(),Cp=ja(),Lc=zv(),xq=Zt(),Sae=Wv(),bg=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,Lc.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ma.SchemaEnv=bg;function fC(r){let e=Pq.call(this,r);if(e)return e;let t=(0,Lc.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Kc.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:Eae.default,code:(0,Kc._)`require("ajv/dist/runtime/validation_error").default`}));let d=o.scopeName("validate");r.validateName=d;let l={gen:o,allErrors:this.opts.allErrors,data:Cp.default.data,parentData:Cp.default.parentData,parentDataProperty:Cp.default.parentDataProperty,dataNames:[Cp.default.data],dataPathArr:[Kc.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Kc.stringify)(r.schema)}:{ref:r.schema}),validateName:d,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Kc.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Kc._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(r),(0,Sae.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();c=`${o.scopeRefs(Cp.default.scope)}return ${u}`,this.opts.code.process&&(c=this.opts.code.process(c,r));let h=new Function(`${Cp.default.self}`,`${Cp.default.scope}`,c)(this,this.scope.get());if(this.scope.value(d,{ref:h}),h.errors=null,h.schema=r.schema,h.schemaEnv=r,r.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:d,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){let{props:p,items:m}=l;h.evaluated={props:p instanceof Kc.Name?void 0:p,items:m instanceof Kc.Name?void 0:m,dynamicProps:p instanceof Kc.Name,dynamicItems:m instanceof Kc.Name},h.source&&(h.source.evaluated=(0,Kc.stringify)(h.evaluated))}return r.validate=h,r}catch(u){throw delete r.validate,delete r.validateName,c&&this.logger.error("Error compiling schema, function code:",c),u}finally{this._compilations.delete(r)}}Ma.compileSchema=fC;function Tae(r,e,t){var n;t=(0,Lc.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=Aae.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new bg({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=Dae.call(this,s)}Ma.resolveRef=Tae;function Dae(r){return(0,Lc.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:fC.call(this,r)}function Pq(r){for(let e of this._compilations)if(kae(e,r))return e}Ma.getCompilingSchema=Pq;function kae(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Aae(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||z_.call(this,r,e)}function z_(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Lc._getFullPath)(this.opts.uriResolver,t),i=(0,Lc.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return uC.call(this,t,r);let s=(0,Lc.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=z_.call(this,r,o);return typeof a?.schema!="object"?void 0:uC.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||fC.call(this,o),s===(0,Lc.normalizeId)(e)){let{schema:a}=o,{schemaId:d}=this.opts,l=a[d];return l&&(i=(0,Lc.resolveUrl)(this.opts.uriResolver,i,l)),new bg({schema:a,schemaId:d,root:r,baseId:i})}return uC.call(this,t,o)}}Ma.resolveSchema=z_;var Iae=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function uC(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let d=t[(0,xq.unescapeFragment)(a)];if(d===void 0)return;t=d;let l=typeof t=="object"&&t[this.opts.schemaId];!Iae.has(a)&&l&&(e=(0,Lc.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,xq.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Lc.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=z_.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new bg({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var _q=Te((gNe,Rae)=>{Rae.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 pC=Te((wNe,Dq)=>{"use strict";g();var Cae=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Sq=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 hC(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 $ae=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Eq(r){return r.length=0,!0}function Oae(r,e,t){if(r.length){let n=hC(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function Bae(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=Oae;for(let d=0;d<r.length;d++){let l=r[d];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(o=!0),!a(i,n,t))break;if(++e>7){t.error=!0;break}d>0&&r[d-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=Eq}else{i.push(l);continue}}return i.length&&(a===Eq?t.zone=i.join(""):o?n.push(i.join("")):n.push(hC(i))),t.address=n.join(""),t}function Tq(r){if(jae(r,":")<2)return{host:r,isIPV6:!1};let e=Bae(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 jae(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}function Nae(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 Mae(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 Uae(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host);if(!Sq(t)){let n=Tq(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}Dq.exports={nonSimpleDomain:$ae,recomposeAuthority:Uae,normalizeComponentEncoding:Mae,removeDotSegments:Nae,isIPv4:Sq,isUUID:Cae,normalizeIPv6:Tq,stringArrayToHexStripped:hC}});var Cq=Te((bNe,Rq)=>{"use strict";g();var{isUUID:Kae}=pC(),Lae=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,qae=["http","https","ws","wss","urn","urn:uuid"];function zae(r){return qae.indexOf(r)!==-1}function mC(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 kq(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Aq(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 Fae(r){return r.secure=mC(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Gae(r){if((r.port===(mC(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 Wae(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Lae);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}`,s=yC(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Hae(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}`,s=yC(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Vae(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Kae(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function Jae(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Iq={scheme:"http",domainHost:!0,parse:kq,serialize:Aq},Yae={scheme:"https",domainHost:Iq.domainHost,parse:kq,serialize:Aq},F_={scheme:"ws",domainHost:!0,parse:Fae,serialize:Gae},Zae={scheme:"wss",domainHost:F_.domainHost,parse:F_.parse,serialize:F_.serialize},Qae={scheme:"urn",parse:Wae,serialize:Hae,skipNormalize:!0},Xae={scheme:"urn:uuid",parse:Vae,serialize:Jae,skipNormalize:!0},G_={http:Iq,https:Yae,ws:F_,wss:Zae,urn:Qae,"urn:uuid":Xae};Object.setPrototypeOf(G_,null);function yC(r){return r&&(G_[r]||G_[r.toLowerCase()])||void 0}Rq.exports={wsIsSecure:mC,SCHEMES:G_,isValidSchemeName:zae,getSchemeHandler:yC}});var Bq=Te((PNe,H_)=>{"use strict";g();var{normalizeIPv6:ece,removeDotSegments:Jv,recomposeAuthority:tce,normalizeComponentEncoding:W_,isIPv4:rce,nonSimpleDomain:nce}=pC(),{SCHEMES:ice,getSchemeHandler:$q}=Cq();function oce(r,e){return typeof r=="string"?r=zd(su(r,e),e):typeof r=="object"&&(r=su(zd(r,e),e)),r}function sce(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},i=Oq(su(r,n),su(e,n),n,!0);return n.skipEscape=!0,zd(i,n)}function Oq(r,e,t,n){let i={};return n||(r=su(zd(r,t),t),e=su(zd(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=Jv(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=Jv(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Jv(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=Jv(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 ace(r,e,t){return typeof r=="string"?(r=unescape(r),r=zd(W_(su(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=zd(W_(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zd(W_(su(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=zd(W_(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function zd(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=[],s=$q(n.scheme||t.scheme);s&&s.serialize&&s.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=tce(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 a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Jv(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var cce=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function su(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 s=r.match(cce);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(rce(n.host)===!1){let d=ece(n.host);n.host=d.host.toLowerCase(),i=d.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=$q(t.scheme||n.scheme);if(!t.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(t.domainHost||o&&o.domainHost)&&i===!1&&nce(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!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 gC={SCHEMES:ice,normalize:oce,resolve:sce,resolveComponent:Oq,equal:ace,serialize:zd,parse:su};H_.exports=gC;H_.exports.default=gC;H_.exports.fastUri=gC});var Nq=Te(wC=>{"use strict";g();Object.defineProperty(wC,"__esModule",{value:!0});var jq=Bq();jq.code='require("ajv/dist/runtime/uri").default';wC.default=jq});var Gq=Te(to=>{"use strict";g();Object.defineProperty(to,"__esModule",{value:!0});to.CodeGen=to.Name=to.nil=to.stringify=to.str=to._=to.KeywordCxt=void 0;var dce=Wv();Object.defineProperty(to,"KeywordCxt",{enumerable:!0,get:function(){return dce.KeywordCxt}});var xg=$t();Object.defineProperty(to,"_",{enumerable:!0,get:function(){return xg._}});Object.defineProperty(to,"str",{enumerable:!0,get:function(){return xg.str}});Object.defineProperty(to,"stringify",{enumerable:!0,get:function(){return xg.stringify}});Object.defineProperty(to,"nil",{enumerable:!0,get:function(){return xg.nil}});Object.defineProperty(to,"Name",{enumerable:!0,get:function(){return xg.Name}});Object.defineProperty(to,"CodeGen",{enumerable:!0,get:function(){return xg.CodeGen}});var lce=q_(),qq=Hv(),uce=HR(),Yv=Vv(),fce=$t(),Zv=zv(),V_=qv(),bC=Zt(),Mq=_q(),hce=Nq(),zq=(r,e)=>new RegExp(r,e);zq.code="new RegExp";var pce=["removeAdditional","useDefaults","coerceTypes"],mce=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yce={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."},gce={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Uq=200;function wce(r){var e,t,n,i,s,o,a,d,l,c,u,f,h,p,m,y,v,w,b,T,D,I,M,C,z;let L=r.strict,B=(e=r.code)===null||e===void 0?void 0:e.optimize,H=B===!0||B===void 0?1:B||0,ee=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zq,R=(i=r.uriResolver)!==null&&i!==void 0?i:hce.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:L)!==null&&o!==void 0?o:!0,strictNumbers:(d=(a=r.strictNumbers)!==null&&a!==void 0?a:L)!==null&&d!==void 0?d:!0,strictTypes:(c=(l=r.strictTypes)!==null&&l!==void 0?l:L)!==null&&c!==void 0?c:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:L)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=r.strictRequired)!==null&&h!==void 0?h:L)!==null&&p!==void 0?p:!1,code:r.code?{...r.code,optimize:H,regExp:ee}:{optimize:H,regExp:ee},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:Uq,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Uq,meta:(v=r.meta)!==null&&v!==void 0?v:!0,messages:(w=r.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=r.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(T=r.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(D=r.addUsedSchema)!==null&&D!==void 0?D:!0,validateSchema:(I=r.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(M=r.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(C=r.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(z=r.int32range)!==null&&z!==void 0?z:!0,uriResolver:R}}var Qv=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...wce(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new fce.ValueScope({scope:{},prefixes:mce,es5:t,lines:n}),this.logger=Ece(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uce.getRules)(),Kq.call(this,yce,e,"NOT SUPPORTED"),Kq.call(this,gce,e,"DEPRECATED","warn"),this._metaOpts=Pce.call(this),e.formats&&bce.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&xce.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),vce.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Mq;n==="id"&&(i={...Mq},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(c,u){await s.call(this,c.$schema);let f=this._addSchema(c,u);return f.validate||o.call(this,f)}async function s(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},!0)}async function o(c){try{return this._compileSchemaEnv(c)}catch(u){if(!(u instanceof qq.default))throw u;return a.call(this,u),await d.call(this,u.missingSchema),o.call(this,c)}}function a({missingSchema:c,missingRef:u}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${u} cannot be resolved`)}async function d(c){let u=await l.call(this,c);this.refs[c]||await s.call(this,u.$schema),this.refs[c]||this.addSchema(u,c,t)}async function l(c){let u=this._loading[c];if(u)return u;try{return await(this._loading[c]=n(c))}finally{delete this._loading[c]}}}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 s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return t=(0,Zv.normalizeId)(t||s),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 s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=Lq.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new Yv.SchemaEnv({schema:{},schemaId:n});if(t=Yv.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=Lq.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,Zv.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(Tce.call(this,n,t),!t)return(0,bC.eachItem)(n,s=>vC.call(this,s)),this;kce.call(this,t);let i={...t,type:(0,V_.getJSONTypes)(t.type),schemaType:(0,V_.getJSONTypes)(t.schemaType)};return(0,bC.eachItem)(n,i.type.length===0?s=>vC.call(this,s,i):s=>i.type.forEach(o=>vC.call(this,s,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(s=>s.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,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in n){let d=n[a];if(typeof d!="object")continue;let{$data:l}=d.definition,c=o[a];l&&c&&(o[a]=Fq(c))}}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,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];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 d=this._cache.get(e);if(d!==void 0)return d;n=(0,Zv.normalizeId)(o||n);let l=Zv.getSchemaRefs.call(this,e,n);return d=new Yv.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(d.schema,d),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),i&&this.validateSchema(e,!0),d}_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):Yv.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{Yv.compileSchema.call(this,e)}finally{this.opts=t}}};Qv.ValidationError=lce.default;Qv.MissingRefError=qq.default;to.default=Qv;function Kq(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function Lq(r){return r=(0,Zv.normalizeId)(r),this.schemas[r]||this.refs[r]}function vce(){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 bce(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function xce(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 Pce(){let r={...this.opts};for(let e of pce)delete r[e];return r}var _ce={log(){},warn(){},error(){}};function Ece(r){if(r===!1)return _ce;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 Sce=/^[a-z_$][a-z0-9_$:-]*$/i;function Tce(r,e){let{RULES:t}=this;if((0,bC.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Sce.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 vC(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:d})=>d===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,V_.getJSONTypes)(e.type),schemaType:(0,V_.getJSONTypes)(e.schemaType)}};e.before?Dce.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}function Dce(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 kce(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Fq(e)),r.validateSchema=this.compile(e,!0))}var Ace={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Fq(r){return{anyOf:[r,Ace]}}});var Wq=Te(xC=>{"use strict";g();Object.defineProperty(xC,"__esModule",{value:!0});var Ice={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};xC.default=Ice});var Z_=Te($p=>{"use strict";g();Object.defineProperty($p,"__esModule",{value:!0});$p.callRef=$p.getValidate=void 0;var Rce=Hv(),Hq=Na(),Ss=$t(),Pg=ja(),Vq=Vv(),J_=Zt(),Cce={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:d}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return u();let c=Vq.resolveRef.call(d,l,i,t);if(c===void 0)throw new Rce.default(n.opts.uriResolver,i,t);if(c instanceof Vq.SchemaEnv)return f(c);return h(c);function u(){if(s===l)return Y_(r,o,s,s.$async);let p=e.scopeValue("root",{ref:l});return Y_(r,(0,Ss._)`${p}.validate`,l,l.$async)}function f(p){let m=Jq(r,p);Y_(r,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Ss.stringify)(p)}:{ref:p}),y=e.name("valid"),v=r.subschema({schema:p,dataTypes:[],schemaPath:Ss.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(v),r.ok(y)}}};function Jq(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ss._)`${t.scopeValue("wrapper",{ref:e})}.validate`}$p.getValidate=Jq;function Y_(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:d}=s,l=d.passContext?Pg.default.this:Ss.nil;n?c():u();function c(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=i.let("valid");i.try(()=>{i.code((0,Ss._)`await ${(0,Hq.callValidateCode)(r,e,l)}`),h(e),o||i.assign(p,!0)},m=>{i.if((0,Ss._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(p,!1)}),r.ok(p)}function u(){r.result((0,Hq.callValidateCode)(r,e,l),()=>h(e),()=>f(e))}function f(p){let m=(0,Ss._)`${p}.errors`;i.assign(Pg.default.vErrors,(0,Ss._)`${Pg.default.vErrors} === null ? ${m} : ${Pg.default.vErrors}.concat(${m})`),i.assign(Pg.default.errors,(0,Ss._)`${Pg.default.vErrors}.length`)}function h(p){var m;if(!s.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=J_.mergeEvaluated.props(i,y.props,s.props));else{let v=i.var("props",(0,Ss._)`${p}.evaluated.props`);s.props=J_.mergeEvaluated.props(i,v,s.props,Ss.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=J_.mergeEvaluated.items(i,y.items,s.items));else{let v=i.var("items",(0,Ss._)`${p}.evaluated.items`);s.items=J_.mergeEvaluated.items(i,v,s.items,Ss.Name)}}}$p.callRef=Y_;$p.default=Cce});var Yq=Te(PC=>{"use strict";g();Object.defineProperty(PC,"__esModule",{value:!0});var $ce=Wq(),Oce=Z_(),Bce=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",$ce.default,Oce.default];PC.default=Bce});var Zq=Te(_C=>{"use strict";g();Object.defineProperty(_C,"__esModule",{value:!0});var Q_=$t(),Uf=Q_.operators,X_={maximum:{okStr:"<=",ok:Uf.LTE,fail:Uf.GT},minimum:{okStr:">=",ok:Uf.GTE,fail:Uf.LT},exclusiveMaximum:{okStr:"<",ok:Uf.LT,fail:Uf.GTE},exclusiveMinimum:{okStr:">",ok:Uf.GT,fail:Uf.LTE}},jce={message:({keyword:r,schemaCode:e})=>(0,Q_.str)`must be ${X_[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Q_._)`{comparison: ${X_[r].okStr}, limit: ${e}}`},Nce={keyword:Object.keys(X_),type:"number",schemaType:"number",$data:!0,error:jce,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Q_._)`${t} ${X_[e].fail} ${n} || isNaN(${t})`)}};_C.default=Nce});var Qq=Te(EC=>{"use strict";g();Object.defineProperty(EC,"__esModule",{value:!0});var Xv=$t(),Mce={message:({schemaCode:r})=>(0,Xv.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,Xv._)`{multipleOf: ${r}}`},Uce={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Mce,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,Xv._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Xv._)`${o} !== parseInt(${o})`;r.fail$data((0,Xv._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};EC.default=Uce});var Xq=Te(SC=>{"use strict";g();Object.defineProperty(SC,"__esModule",{value:!0});var Op=$t(),Kce=Zt(),Lce=ED(),qce={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,Op.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,Op._)`{limit: ${r}}`},zce={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qce,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?Op.operators.GT:Op.operators.LT,o=i.opts.unicode===!1?(0,Op._)`${t}.length`:(0,Op._)`${(0,Kce.useFunc)(r.gen,Lce.default)}(${t})`;r.fail$data((0,Op._)`${o} ${s} ${n}`)}};SC.default=zce});var e9=Te(TC=>{"use strict";g();Object.defineProperty(TC,"__esModule",{value:!0});var Fce=Na(),Gce=Zt(),_g=$t(),Wce={message:({schemaCode:r})=>(0,_g.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,_g._)`{pattern: ${r}}`},Hce={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Wce,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:d}=o.opts.code,l=d.code==="new RegExp"?(0,_g._)`new RegExp`:(0,Gce.useFunc)(e,d),c=e.let("valid");e.try(()=>e.assign(c,(0,_g._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(c,!1)),r.fail$data((0,_g._)`!${c}`)}else{let d=(0,Fce.usePattern)(r,i);r.fail$data((0,_g._)`!${d}.test(${t})`)}}};TC.default=Hce});var t9=Te(DC=>{"use strict";g();Object.defineProperty(DC,"__esModule",{value:!0});var eb=$t(),Vce={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,eb.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,eb._)`{limit: ${r}}`},Jce={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Vce,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?eb.operators.GT:eb.operators.LT;r.fail$data((0,eb._)`Object.keys(${t}).length ${i} ${n}`)}};DC.default=Jce});var r9=Te(kC=>{"use strict";g();Object.defineProperty(kC,"__esModule",{value:!0});var tb=Na(),rb=$t(),Yce=Zt(),Zce={message:({params:{missingProperty:r}})=>(0,rb.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,rb._)`{missingProperty: ${r}}`},Qce={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Zce,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let d=t.length>=a.loopRequired;if(o.allErrors?l():c(),a.strictRequired){let h=r.parentSchema.properties,{definedProperties:p}=r.it;for(let m of t)if(h?.[m]===void 0&&!p.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Yce.checkStrictMode)(o,v,o.opts.strictRequired)}}function l(){if(d||s)r.block$data(rb.nil,u);else for(let h of t)(0,tb.checkReportMissingProp)(r,h)}function c(){let h=e.let("missing");if(d||s){let p=e.let("valid",!0);r.block$data(p,()=>f(h,p)),r.ok(p)}else e.if((0,tb.checkMissingProp)(r,t,h)),(0,tb.reportMissingProp)(r,h),e.else()}function u(){e.forOf("prop",n,h=>{r.setParams({missingProperty:h}),e.if((0,tb.noPropertyInData)(e,i,h,a.ownProperties),()=>r.error())})}function f(h,p){r.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,tb.propertyInData)(e,i,h,a.ownProperties)),e.if((0,rb.not)(p),()=>{r.error(),e.break()})},rb.nil)}}};kC.default=Qce});var n9=Te(AC=>{"use strict";g();Object.defineProperty(AC,"__esModule",{value:!0});var nb=$t(),Xce={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,nb.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,nb._)`{limit: ${r}}`},ede={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Xce,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?nb.operators.GT:nb.operators.LT;r.fail$data((0,nb._)`${t}.length ${i} ${n}`)}};AC.default=ede});var e2=Te(IC=>{"use strict";g();Object.defineProperty(IC,"__esModule",{value:!0});var i9=tC();i9.code='require("ajv/dist/runtime/equal").default';IC.default=i9});var o9=Te(CC=>{"use strict";g();Object.defineProperty(CC,"__esModule",{value:!0});var RC=qv(),ro=$t(),tde=Zt(),rde=e2(),nde={message:({params:{i:r,j:e}})=>(0,ro.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,ro._)`{i: ${r}, j: ${e}}`},ide={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:nde,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let d=e.let("valid"),l=s.items?(0,RC.getSchemaTypes)(s.items):[];r.block$data(d,c,(0,ro._)`${o} === false`),r.ok(d);function c(){let p=e.let("i",(0,ro._)`${t}.length`),m=e.let("j");r.setParams({i:p,j:m}),e.assign(d,!0),e.if((0,ro._)`${p} > 1`,()=>(u()?f:h)(p,m))}function u(){return l.length>0&&!l.some(p=>p==="object"||p==="array")}function f(p,m){let y=e.name("item"),v=(0,RC.checkDataTypes)(l,y,a.opts.strictNumbers,RC.DataType.Wrong),w=e.const("indices",(0,ro._)`{}`);e.for((0,ro._)`;${p}--;`,()=>{e.let(y,(0,ro._)`${t}[${p}]`),e.if(v,(0,ro._)`continue`),l.length>1&&e.if((0,ro._)`typeof ${y} == "string"`,(0,ro._)`${y} += "_"`),e.if((0,ro._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,ro._)`${w}[${y}]`),r.error(),e.assign(d,!1).break()}).code((0,ro._)`${w}[${y}] = ${p}`)})}function h(p,m){let y=(0,tde.useFunc)(e,rde.default),v=e.name("outer");e.label(v).for((0,ro._)`;${p}--;`,()=>e.for((0,ro._)`${m} = ${p}; ${m}--;`,()=>e.if((0,ro._)`${y}(${t}[${p}], ${t}[${m}])`,()=>{r.error(),e.assign(d,!1).break(v)})))}}};CC.default=ide});var s9=Te(OC=>{"use strict";g();Object.defineProperty(OC,"__esModule",{value:!0});var $C=$t(),ode=Zt(),sde=e2(),ade={message:"must be equal to constant",params:({schemaCode:r})=>(0,$C._)`{allowedValue: ${r}}`},cde={keyword:"const",$data:!0,error:ade,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,$C._)`!${(0,ode.useFunc)(e,sde.default)}(${t}, ${i})`):r.fail((0,$C._)`${s} !== ${t}`)}};OC.default=cde});var a9=Te(BC=>{"use strict";g();Object.defineProperty(BC,"__esModule",{value:!0});var ib=$t(),dde=Zt(),lde=e2(),ude={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,ib._)`{allowedValues: ${r}}`},fde={keyword:"enum",schemaType:"array",$data:!0,error:ude,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,d,l=()=>d??(d=(0,dde.useFunc)(e,lde.default)),c;if(a||n)c=e.let("valid"),r.block$data(c,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let h=e.const("vSchema",s);c=(0,ib.or)(...i.map((p,m)=>f(h,m)))}r.pass(c);function u(){e.assign(c,!1),e.forOf("v",s,h=>e.if((0,ib._)`${l()}(${t}, ${h})`,()=>e.assign(c,!0).break()))}function f(h,p){let m=i[p];return typeof m=="object"&&m!==null?(0,ib._)`${l()}(${t}, ${h}[${p}])`:(0,ib._)`${t} === ${m}`}}};BC.default=fde});var c9=Te(jC=>{"use strict";g();Object.defineProperty(jC,"__esModule",{value:!0});var hde=Zq(),pde=Qq(),mde=Xq(),yde=e9(),gde=t9(),wde=r9(),vde=n9(),bde=o9(),xde=s9(),Pde=a9(),_de=[hde.default,pde.default,mde.default,yde.default,gde.default,wde.default,vde.default,bde.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},xde.default,Pde.default];jC.default=_de});var MC=Te(ob=>{"use strict";g();Object.defineProperty(ob,"__esModule",{value:!0});ob.validateAdditionalItems=void 0;var Bp=$t(),NC=Zt(),Ede={message:({params:{len:r}})=>(0,Bp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Bp._)`{limit: ${r}}`},Sde={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ede,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,NC.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}d9(r,n)}};function d9(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,Bp._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Bp._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,NC.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Bp._)`${a} <= ${e.length}`);t.if((0,Bp.not)(l),()=>d(l)),r.ok(l)}function d(l){t.forRange("i",e.length,a,c=>{r.subschema({keyword:s,dataProp:c,dataPropType:NC.Type.Num},l),o.allErrors||t.if((0,Bp.not)(l),()=>t.break())})}}ob.validateAdditionalItems=d9;ob.default=Sde});var UC=Te(sb=>{"use strict";g();Object.defineProperty(sb,"__esModule",{value:!0});sb.validateTuple=void 0;var l9=$t(),t2=Zt(),Tde=Na(),Dde={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return u9(r,"additionalItems",e);t.items=!0,!(0,t2.alwaysValidSchema)(t,e)&&r.ok((0,Tde.validateArray)(r))}};function u9(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;c(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=t2.mergeEvaluated.items(n,t.length,a.items));let d=n.name("valid"),l=n.const("len",(0,l9._)`${s}.length`);t.forEach((u,f)=>{(0,t2.alwaysValidSchema)(a,u)||(n.if((0,l9._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},d)),r.ok(d))});function c(u){let{opts:f,errSchemaPath:h}=a,p=t.length,m=p===u.minItems&&(p===u.maxItems||u[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,t2.checkStrictMode)(a,y,f.strictTuples)}}}sb.validateTuple=u9;sb.default=Dde});var f9=Te(KC=>{"use strict";g();Object.defineProperty(KC,"__esModule",{value:!0});var kde=UC(),Ade={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,kde.validateTuple)(r,"items")};KC.default=Ade});var p9=Te(LC=>{"use strict";g();Object.defineProperty(LC,"__esModule",{value:!0});var h9=$t(),Ide=Zt(),Rde=Na(),Cde=MC(),$de={message:({params:{len:r}})=>(0,h9.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,h9._)`{limit: ${r}}`},Ode={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:$de,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,Ide.alwaysValidSchema)(n,e)&&(i?(0,Cde.validateAdditionalItems)(r,i):r.ok((0,Rde.validateArray)(r)))}};LC.default=Ode});var m9=Te(qC=>{"use strict";g();Object.defineProperty(qC,"__esModule",{value:!0});var Ua=$t(),r2=Zt(),Bde={message:({params:{min:r,max:e}})=>e===void 0?(0,Ua.str)`must contain at least ${r} valid item(s)`:(0,Ua.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ua._)`{minContains: ${r}}`:(0,Ua._)`{minContains: ${r}, maxContains: ${e}}`},jde={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Bde,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:d,maxContains:l}=n;s.opts.next?(o=d===void 0?1:d,a=l):o=1;let c=e.const("len",(0,Ua._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,r2.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,r2.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,r2.alwaysValidSchema)(s,t)){let m=(0,Ua._)`${c} >= ${o}`;a!==void 0&&(m=(0,Ua._)`${m} && ${c} <= ${a}`),r.pass(m);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?h(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,Ua._)`${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);h(m,()=>e.if(m,()=>p(y)))}function h(m,y){e.forRange("i",0,c,v=>{r.subschema({keyword:"contains",dataProp:v,dataPropType:r2.Type.Num,compositeRule:!0},m),y()})}function p(m){e.code((0,Ua._)`${m}++`),a===void 0?e.if((0,Ua._)`${m} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,Ua._)`${m} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,Ua._)`${m} >= ${o}`,()=>e.assign(u,!0)))}}};qC.default=jde});var n2=Te(Fd=>{"use strict";g();Object.defineProperty(Fd,"__esModule",{value:!0});Fd.validateSchemaDeps=Fd.validatePropertyDeps=Fd.error=void 0;var zC=$t(),Nde=Zt(),ab=Na();Fd.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,zC.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,zC._)`{property: ${r},
|
|
8
8
|
missingProperty: ${n},
|
|
9
9
|
depsCount: ${e},
|
|
10
|
-
deps: ${t}}`};var Mde={keyword:"dependencies",type:"object",schemaType:"object",error:Fd.error,code(r){let[e,t]=Ude(r);y9(r,e),g9(r,t)}};function Ude({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 y9(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let d=(0,ab.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(d,()=>{for(let l of a)(0,ab.checkReportMissingProp)(r,l)}):(t.if((0,zC._)`${d} && (${(0,ab.checkMissingProp)(r,a,s)})`),(0,ab.reportMissingProp)(r,s),t.else())}}Fd.validatePropertyDeps=y9;function g9(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,Nde.alwaysValidSchema)(s,e[a])||(t.if((0,ab.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let d=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(d,o)},()=>t.var(o,!0)),r.ok(o))}Fd.validateSchemaDeps=g9;Fd.default=Mde});var v9=Te(FC=>{"use strict";g();Object.defineProperty(FC,"__esModule",{value:!0});var w9=$t(),Kde=Zt(),Lde={message:"property name must be valid",params:({params:r})=>(0,w9._)`{propertyName: ${r.propertyName}}`},qde={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Lde,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Kde.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,w9.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};FC.default=qde});var WC=Te(GC=>{"use strict";g();Object.defineProperty(GC,"__esModule",{value:!0});var i2=Na(),qc=$t(),zde=ja(),o2=Zt(),Fde={message:"must NOT have additional properties",params:({params:r})=>(0,qc._)`{additionalProperty: ${r.additionalProperty}}`},Gde={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Fde,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:d}=o;if(o.props=!0,d.removeAdditional!=="all"&&(0,o2.alwaysValidSchema)(o,t))return;let l=(0,i2.allSchemaProperties)(n.properties),c=(0,i2.allSchemaProperties)(n.patternProperties);u(),r.ok((0,qc._)`${s} === ${zde.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!c.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let v;if(l.length>8){let w=(0,o2.schemaRefOrVal)(o,n.properties,"properties");v=(0,i2.isOwnProperty)(e,w,y)}else l.length?v=(0,qc.or)(...l.map(w=>(0,qc._)`${y} === ${w}`)):v=qc.nil;return c.length&&(v=(0,qc.or)(v,...c.map(w=>(0,qc._)`${(0,i2.usePattern)(r,w)}.test(${y})`))),(0,qc.not)(v)}function h(y){e.code((0,qc._)`delete ${i}[${y}]`)}function p(y){if(d.removeAdditional==="all"||d.removeAdditional&&t===!1){h(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,o2.alwaysValidSchema)(o,t)){let v=e.name("valid");d.removeAdditional==="failing"?(m(y,v,!1),e.if((0,qc.not)(v),()=>{r.reset(),h(y)})):(m(y,v),a||e.if((0,qc.not)(v),()=>e.break()))}}function m(y,v,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:o2.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(b,v)}}};GC.default=Gde});var P9=Te(VC=>{"use strict";g();Object.defineProperty(VC,"__esModule",{value:!0});var Wde=Wv(),b9=Na(),HC=Zt(),x9=WC(),Hde={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&x9.default.code(new Wde.KeywordCxt(s,x9.default,"additionalProperties"));let o=(0,b9.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=HC.mergeEvaluated.props(e,(0,HC.toHash)(o),s.props));let a=o.filter(u=>!(0,HC.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let d=e.name("valid");for(let u of a)l(u)?c(u):(e.if((0,b9.propertyInData)(e,i,u,s.opts.ownProperties)),c(u),s.allErrors||e.else().var(d,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(d);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function c(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},d)}}};VC.default=Hde});var T9=Te(JC=>{"use strict";g();Object.defineProperty(JC,"__esModule",{value:!0});var _9=Na(),s2=$t(),E9=Zt(),S9=Zt(),Vde={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,_9.allSchemaProperties)(t),d=a.filter(m=>(0,E9.alwaysValidSchema)(s,t[m]));if(a.length===0||d.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,c=e.name("valid");s.props!==!0&&!(s.props instanceof s2.Name)&&(s.props=(0,S9.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let m of a)l&&h(m),s.allErrors?p(m):(e.var(c,!0),p(m),e.if(c))}function h(m){for(let y in l)new RegExp(m).test(y)&&(0,E9.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,s2._)`${(0,_9.usePattern)(r,m)}.test(${y})`,()=>{let v=d.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:S9.Type.Str},c),s.opts.unevaluated&&u!==!0?e.assign((0,s2._)`${u}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,s2.not)(c),()=>e.break())})})}}};JC.default=Vde});var D9=Te(YC=>{"use strict";g();Object.defineProperty(YC,"__esModule",{value:!0});var Jde=Zt(),Yde={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,Jde.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"}};YC.default=Yde});var k9=Te(ZC=>{"use strict";g();Object.defineProperty(ZC,"__esModule",{value:!0});var Zde=Na(),Qde={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Zde.validateUnion,error:{message:"must match a schema in anyOf"}};ZC.default=Qde});var A9=Te(QC=>{"use strict";g();Object.defineProperty(QC,"__esModule",{value:!0});var a2=$t(),Xde=Zt(),ele={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,a2._)`{passingSchemas: ${r.passing}}`},tle={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ele,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 s=t,o=e.let("valid",!1),a=e.let("passing",null),d=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((c,u)=>{let f;(0,Xde.alwaysValidSchema)(i,c)?e.var(d,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},d),u>0&&e.if((0,a2._)`${d} && ${o}`).assign(o,!1).assign(a,(0,a2._)`[${a}, ${u}]`).else(),e.if(d,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,a2.Name)})})}}};QC.default=tle});var I9=Te(XC=>{"use strict";g();Object.defineProperty(XC,"__esModule",{value:!0});var rle=Zt(),nle={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((s,o)=>{if((0,rle.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};XC.default=nle});var $9=Te(e6=>{"use strict";g();Object.defineProperty(e6,"__esModule",{value:!0});var c2=$t(),C9=Zt(),ile={message:({params:r})=>(0,c2.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,c2._)`{failingKeyword: ${r.ifClause}}`},ole={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ile,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,C9.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=R9(n,"then"),s=R9(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(d(),r.reset(),i&&s){let c=e.let("ifClause");r.setParams({ifClause:c}),e.if(a,l("then",c),l("else",c))}else i?e.if(a,l("then")):e.if((0,c2.not)(a),l("else"));r.pass(o,()=>r.error(!0));function d(){let c=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(c)}function l(c,u){return()=>{let f=r.subschema({keyword:c},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,c2._)`${c}`):r.setParams({ifClause:c})}}}};function R9(r,e){let t=r.schema[e];return t!==void 0&&!(0,C9.alwaysValidSchema)(r,t)}e6.default=ole});var O9=Te(t6=>{"use strict";g();Object.defineProperty(t6,"__esModule",{value:!0});var sle=Zt(),ale={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,sle.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};t6.default=ale});var B9=Te(r6=>{"use strict";g();Object.defineProperty(r6,"__esModule",{value:!0});var cle=MC(),dle=f9(),lle=UC(),ule=p9(),fle=m9(),hle=n2(),ple=v9(),mle=WC(),yle=P9(),gle=T9(),wle=D9(),vle=k9(),ble=A9(),xle=I9(),Ple=$9(),_le=O9();function Ele(r=!1){let e=[wle.default,vle.default,ble.default,xle.default,Ple.default,_le.default,ple.default,mle.default,hle.default,yle.default,gle.default];return r?e.push(dle.default,ule.default):e.push(cle.default,lle.default),e.push(fle.default),e}r6.default=Ele});var i6=Te(cb=>{"use strict";g();Object.defineProperty(cb,"__esModule",{value:!0});cb.dynamicAnchor=void 0;var n6=$t(),Sle=ja(),j9=Vv(),Tle=Z_(),Dle={keyword:"$dynamicAnchor",schemaType:"string",code:r=>N9(r,r.schema)};function N9(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,n6._)`${Sle.default.dynamicAnchors}${(0,n6.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:kle(r);t.if((0,n6._)`!${i}`,()=>t.assign(i,s))}cb.dynamicAnchor=N9;function kle(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:d}=n.opts,l=new j9.SchemaEnv({schema:t,schemaId:d,root:i,baseId:s,localRefs:o,meta:a});return j9.compileSchema.call(n,l),(0,Tle.getValidate)(r,l)}cb.default=Dle});var o6=Te(db=>{"use strict";g();Object.defineProperty(db,"__esModule",{value:!0});db.dynamicRef=void 0;var M9=$t(),Ale=ja(),U9=Z_(),Ile={keyword:"$dynamicRef",schemaType:"string",code:r=>K9(r,r.schema)};function K9(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let d=t.let("valid",!1);o(d),r.ok(d)}function o(d){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,M9._)`${Ale.default.dynamicAnchors}${(0,M9.getProperty)(s)}`);t.if(l,a(l,d),a(i.validateName,d))}else a(i.validateName,d)()}function a(d,l){return l?()=>t.block(()=>{(0,U9.callRef)(r,d),t.let(l,!0)}):()=>(0,U9.callRef)(r,d)}}db.dynamicRef=K9;db.default=Ile});var L9=Te(s6=>{"use strict";g();Object.defineProperty(s6,"__esModule",{value:!0});var Rle=i6(),Cle=Zt(),$le={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,Rle.dynamicAnchor)(r,""):(0,Cle.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};s6.default=$le});var q9=Te(a6=>{"use strict";g();Object.defineProperty(a6,"__esModule",{value:!0});var Ole=o6(),Ble={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Ole.dynamicRef)(r,r.schema)};a6.default=Ble});var z9=Te(c6=>{"use strict";g();Object.defineProperty(c6,"__esModule",{value:!0});var jle=i6(),Nle=o6(),Mle=L9(),Ule=q9(),Kle=[jle.default,Nle.default,Mle.default,Ule.default];c6.default=Kle});var G9=Te(d6=>{"use strict";g();Object.defineProperty(d6,"__esModule",{value:!0});var F9=n2(),Lle={keyword:"dependentRequired",type:"object",schemaType:"object",error:F9.error,code:r=>(0,F9.validatePropertyDeps)(r)};d6.default=Lle});var W9=Te(l6=>{"use strict";g();Object.defineProperty(l6,"__esModule",{value:!0});var qle=n2(),zle={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,qle.validateSchemaDeps)(r)};l6.default=zle});var H9=Te(u6=>{"use strict";g();Object.defineProperty(u6,"__esModule",{value:!0});var Fle=Zt(),Gle={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Fle.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};u6.default=Gle});var V9=Te(f6=>{"use strict";g();Object.defineProperty(f6,"__esModule",{value:!0});var Wle=G9(),Hle=W9(),Vle=H9(),Jle=[Wle.default,Hle.default,Vle.default];f6.default=Jle});var Y9=Te(h6=>{"use strict";g();Object.defineProperty(h6,"__esModule",{value:!0});var Kf=$t(),J9=Zt(),Yle=ja(),Zle={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Kf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},Qle={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Zle,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof Kf.Name?e.if((0,Kf._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>d(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?d(u):e.if(c(a,u),()=>d(u))),s.props=!0,r.ok((0,Kf._)`${i} === ${Yle.default.errors}`);function d(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,J9.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:J9.Type.Str},f),o||e.if((0,Kf.not)(f),()=>e.break())}}function l(u,f){return(0,Kf._)`!${u} || !${u}[${f}]`}function c(u,f){let h=[];for(let p in u)u[p]===!0&&h.push((0,Kf._)`${f} !== ${p}`);return(0,Kf.and)(...h)}}};h6.default=Qle});var Q9=Te(p6=>{"use strict";g();Object.defineProperty(p6,"__esModule",{value:!0});var jp=$t(),Z9=Zt(),Xle={message:({params:{len:r}})=>(0,jp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,jp._)`{limit: ${r}}`},eue={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Xle,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,jp._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,jp._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Z9.alwaysValidSchema)(i,t)){let d=e.var("valid",(0,jp._)`${o} <= ${s}`);e.if((0,jp.not)(d),()=>a(d,s)),r.ok(d)}i.items=!0;function a(d,l){e.forRange("i",l,o,c=>{r.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:Z9.Type.Num},d),i.allErrors||e.if((0,jp.not)(d),()=>e.break())})}}};p6.default=eue});var X9=Te(m6=>{"use strict";g();Object.defineProperty(m6,"__esModule",{value:!0});var tue=Y9(),rue=Q9(),nue=[tue.default,rue.default];m6.default=nue});var ez=Te(y6=>{"use strict";g();Object.defineProperty(y6,"__esModule",{value:!0});var Vn=$t(),iue={message:({schemaCode:r})=>(0,Vn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Vn._)`{format: ${r}}`},oue={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iue,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:d,errSchemaPath:l,schemaEnv:c,self:u}=a;if(!d.validateFormats)return;i?f():h();function f(){let p=t.scopeValue("formats",{ref:u.formats,code:d.code.formats}),m=t.const("fDef",(0,Vn._)`${p}[${o}]`),y=t.let("fType"),v=t.let("format");t.if((0,Vn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,Vn._)`${m}.type || "string"`).assign(v,(0,Vn._)`${m}.validate`),()=>t.assign(y,(0,Vn._)`"string"`).assign(v,m)),r.fail$data((0,Vn.or)(w(),b()));function w(){return d.strictSchema===!1?Vn.nil:(0,Vn._)`${o} && !${v}`}function b(){let T=c.$async?(0,Vn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Vn._)`${v}(${n})`,D=(0,Vn._)`(typeof ${v} == "function" ? ${T} : ${v}.test(${n}))`;return(0,Vn._)`${v} && ${v} !== true && ${y} === ${e} && !${D}`}}function h(){let p=u.formats[s];if(!p){w();return}if(p===!0)return;let[m,y,v]=b(p);m===e&&r.pass(T());function w(){if(d.strictSchema===!1){u.logger.warn(D());return}throw new Error(D());function D(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function b(D){let I=D instanceof RegExp?(0,Vn.regexpCode)(D):d.code.formats?(0,Vn._)`${d.code.formats}${(0,Vn.getProperty)(s)}`:void 0,M=t.scopeValue("formats",{key:s,ref:D,code:I});return typeof D=="object"&&!(D instanceof RegExp)?[D.type||"string",D.validate,(0,Vn._)`${M}.validate`]:["string",D,M]}function T(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!c.$async)throw new Error("async format in sync schema");return(0,Vn._)`await ${v}(${n})`}return typeof y=="function"?(0,Vn._)`${v}(${n})`:(0,Vn._)`${v}.test(${n})`}}}};y6.default=oue});var tz=Te(g6=>{"use strict";g();Object.defineProperty(g6,"__esModule",{value:!0});var sue=ez(),aue=[sue.default];g6.default=aue});var rz=Te(Eg=>{"use strict";g();Object.defineProperty(Eg,"__esModule",{value:!0});Eg.contentVocabulary=Eg.metadataVocabulary=void 0;Eg.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Eg.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var iz=Te(w6=>{"use strict";g();Object.defineProperty(w6,"__esModule",{value:!0});var cue=Yq(),due=c9(),lue=B9(),uue=z9(),fue=V9(),hue=X9(),pue=tz(),nz=rz(),mue=[uue.default,cue.default,due.default,(0,lue.default)(!0),pue.default,nz.metadataVocabulary,nz.contentVocabulary,fue.default,hue.default];w6.default=mue});var sz=Te(d2=>{"use strict";g();Object.defineProperty(d2,"__esModule",{value:!0});d2.DiscrError=void 0;var oz;(function(r){r.Tag="tag",r.Mapping="mapping"})(oz||(d2.DiscrError=oz={}))});var cz=Te(b6=>{"use strict";g();Object.defineProperty(b6,"__esModule",{value:!0});var Sg=$t(),v6=sz(),az=Vv(),yue=Hv(),gue=Zt(),wue={message:({params:{discrError:r,tagName:e}})=>r===v6.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Sg._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},vue={keyword:"discriminator",type:"object",schemaType:"object",error:wue,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="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 d=e.let("valid",!1),l=e.const("tag",(0,Sg._)`${t}${(0,Sg.getProperty)(a)}`);e.if((0,Sg._)`typeof ${l} == "string"`,()=>c(),()=>r.error(!1,{discrError:v6.DiscrError.Tag,tag:l,tagName:a})),r.ok(d);function c(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Sg._)`${l} === ${p}`),e.assign(d,u(h[p]));e.else(),r.error(!1,{discrError:v6.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(h){let p=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:h},p);return r.mergeEvaluated(m,Sg.Name),p}function f(){var h;let p={},m=v(i),y=!0;for(let T=0;T<o.length;T++){let D=o[T];if(D?.$ref&&!(0,gue.schemaHasRulesButRef)(D,s.self.RULES)){let M=D.$ref;if(D=az.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,M),D instanceof az.SchemaEnv&&(D=D.schema),D===void 0)throw new yue.default(s.opts.uriResolver,s.baseId,M)}let I=(h=D?.properties)===null||h===void 0?void 0:h[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||v(D)),w(I,T)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return p;function v({required:T}){return Array.isArray(T)&&T.includes(a)}function w(T,D){if(T.const)b(T.const,D);else if(T.enum)for(let I of T.enum)b(I,D);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(T,D){if(typeof T!="string"||T in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[T]=D}}}};b6.default=vue});var dz=Te((bUe,bue)=>{bue.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 lz=Te((xUe,xue)=>{xue.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 uz=Te((PUe,Pue)=>{Pue.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 fz=Te((_Ue,_ue)=>{_ue.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 hz=Te((EUe,Eue)=>{Eue.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 pz=Te((SUe,Sue)=>{Sue.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 mz=Te((TUe,Tue)=>{Tue.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 yz=Te((DUe,Due)=>{Due.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 gz=Te(x6=>{"use strict";g();Object.defineProperty(x6,"__esModule",{value:!0});var kue=dz(),Aue=lz(),Iue=uz(),Rue=fz(),Cue=hz(),$ue=pz(),Oue=mz(),Bue=yz(),jue=["/properties"];function Nue(r){return[kue,Aue,Iue,Rue,Cue,e(this,$ue),Oue,e(this,Bue)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,jue):n}}x6.default=Nue});var E6=Te((un,_6)=>{"use strict";g();Object.defineProperty(un,"__esModule",{value:!0});un.MissingRefError=un.ValidationError=un.CodeGen=un.Name=un.nil=un.stringify=un.str=un._=un.KeywordCxt=un.Ajv2020=void 0;var Mue=Gq(),Uue=iz(),Kue=cz(),Lue=gz(),P6="https://json-schema.org/draft/2020-12/schema",Tg=class extends Mue.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Uue.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Kue.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Lue.default.call(this,e),this.refs["http://json-schema.org/schema"]=P6)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(P6)?P6:void 0)}};un.Ajv2020=Tg;_6.exports=un=Tg;_6.exports.Ajv2020=Tg;Object.defineProperty(un,"__esModule",{value:!0});un.default=Tg;var que=Wv();Object.defineProperty(un,"KeywordCxt",{enumerable:!0,get:function(){return que.KeywordCxt}});var Dg=$t();Object.defineProperty(un,"_",{enumerable:!0,get:function(){return Dg._}});Object.defineProperty(un,"str",{enumerable:!0,get:function(){return Dg.str}});Object.defineProperty(un,"stringify",{enumerable:!0,get:function(){return Dg.stringify}});Object.defineProperty(un,"nil",{enumerable:!0,get:function(){return Dg.nil}});Object.defineProperty(un,"Name",{enumerable:!0,get:function(){return Dg.Name}});Object.defineProperty(un,"CodeGen",{enumerable:!0,get:function(){return Dg.CodeGen}});var zue=q_();Object.defineProperty(un,"ValidationError",{enumerable:!0,get:function(){return zue.default}});var Fue=Hv();Object.defineProperty(un,"MissingRefError",{enumerable:!0,get:function(){return Fue.default}})});var Lf,l2=G(()=>{"use strict";g();BP();xt();Lf=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:s,messageStore:o}=e;await Ys.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:s,messageStore:o}),r.verifyScope(t,s.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:s,messageStore:o}=e;await Ys.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:s,messageStore:o});let d=s.scope.protocol,l=i.descriptor.filter?.protocol;if(d!==void 0&&l!==d)throw new ne(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${d} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ne(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function es(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 qf(r){return r.includes(":")}function u2(r){return r.split("/").slice(-1)[0]}function Wd(r,e){let t=r.split("/"),n,i=e;for(let s of t){if(!Object.hasOwn(i,s))return;n=i[s],i=n}return n}var Gd,Np=G(()=>{"use strict";g();gn();jy();Gd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,c=[St.ProtocolPath,e.protocol];async function u(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];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,c),i}let s=t;async function o(l,c){for(let u in l)if(!u.startsWith("$")){let f=await zi.derivePrivateKey(c,[u]),h=l[u];if(h.$ref!==void 0){await o(h,f);continue}let p=await kt.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:s,publicKeyJwk:p},await o(h,f)}}let a={derivationScheme:St.ProtocolPath,derivedPrivateKey:n,rootKeyId:s},d=await zi.derivePrivateKey(a,[St.ProtocolPath,e.protocol]);return await o(i.structure,d),i}}});var wz,Ka,f2=G(()=>{"use strict";g();Mc();wz=Rn(E6(),1);vr();Tc();l2();Yo();xt();lr();Np();Ia();kw();Ka=class r extends Mn{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??At.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=Ht.parse(this.message.authorization.authorDelegatedGrant);await Lf.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;mi(t);for(let s in n){let o=n[s].schema;o!==void 0&&Sd(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 ne(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{mi(e[i])}catch{throw new ne(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ne(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 ne(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let s=t[i],o;e===""?o=i:o=`${e}/${i}`,s.$role?n.push(o):r.fetchAllRolePathsRecursively(o,s,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:s,uses:o,types:a}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ne(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:c}=t.$size;if(c!==void 0&&c<l)throw new ne(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${c} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:c}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Cu);if(!u.includes(c))throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${c}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new wz.default.default,{$allowUndefinedTags:c,$requiredTags:u,...f}=t.$tags;for(let h in f){let p=f[h];if(!l.validateSchema(p)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${h}`});throw new ne(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let d=t.$actions??[];for(let l=0;l<d.length;l++){let c=d[l];if(c.role!==void 0){if(qf(c.role))r.validateCrossProtocolAlias(c.role,o,n,"role");else if(!s.includes(c.role))throw new ne(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(c)} for rule set ${n} does not exist.`)}if(c.who==="anyone"&&c.of)throw new ne(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(c.who===td.Recipient&&c.of===void 0&&c.can.some(f=>![_r.CoUpdate,_r.CoDelete,_r.CoPrune].includes(f)))throw new ne(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(c.who===td.Author&&!c.of)throw new ne(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(c.of!==void 0&&n!==""){if(qf(c.of))r.validateCrossProtocolAlias(c.of,o,n,"of");else if(!(n===c.of||n.startsWith(c.of+"/")))throw new ne(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${c.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(c)}.`)}if(c.can!==void 0){if(c.can.includes(_r.Update)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'update' action but missing the required 'create' action.`);if(c.can.includes(_r.Delete)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'delete' action but missing the required 'create' action.`);if(c.can.includes(_r.Prune)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<d.length;u++){let f=d[u];if(c.who===void 0){if(c.role===f.role)throw new ne(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${c.role} not allowed within a rule set: ${JSON.stringify(c)}`)}else if(c.who===f.who&&c.of===f.of)throw new ne(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${c.who} of ${c.of} not allowed within a rule set: ${JSON.stringify(c)}`)}}if(n!==""){let l=n.split("/").pop();a[l]?.encryptionRequired===!0&&d.some(f=>f.who===td.Anyone&&f.can.includes(_r.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&&d.length>0&&d.some(c=>c.can.includes(_r.Update)||c.can.includes(_r.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 c=t[l];if(c.$ref===void 0&&!i.includes(l))throw new ne(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:c,ruleSetProtocolPath:u,recordTypes:i,roles:s,uses:o,types:a})}}static validateRefNode(e,t,n){let i=e.$ref,s=es(i);if(s===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n?.[s.alias]===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${s.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 a of o)if(e[a]!==void 0)throw new ne(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${a}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let s=es(e);if(s===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(o,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t?.[s.alias]===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(o,`cross-protocol '${i}' alias '${s.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 s=t[i].schema;s!==void 0&&(t[i].schema=cp(s))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Fo(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Fo(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var h2,vz=G(()=>{"use strict";g();ra();vr();na();ia();f2();l2();xt();lr();Np();h2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Ka.parse(t)}catch(c){return gt(c,400)}try{await bn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(c){return gt(c,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(c){return gt(c,400)}let i={interface:xe.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:s}=await this.deps.messageStore.query(e,[i]),o=await ye.getCid(t);for(let c of s)if(await ye.getCid(c)===o)return{status:{code:409,detail:"Conflict"}};let a=await ye.getNewestMessage(s),d=!1;(a===void 0||await ye.isNewer(t,a))&&(d=!0,a=t);let l;if(d){let c=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,c);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,c),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},c,u),l={status:{code:202,detail:"Accepted"}}}else{let c=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,c);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,c),l={status:{code:202,detail:"Accepted"}}}for(let c of s)if(c!==a){let u=await Ka.parse(c),f=r.constructIndexes(u,!1),h=await ye.getCid(c);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,c,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:s}=e;return{...i,author:s,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 Qe.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Lf.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ne(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let s=new Map;for(let o in i){let a=i[o],d=await r.fetchInstalledProtocolDefinition(e,a,n);if(d===void 0)throw new ne(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${a}' (alias '${o}') is not installed for tenant '${e}'.`);s.set(o,d)}r.validateRefsAndRolesRecursively(t.structure,"",s)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:xe.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:s}=await n.query(e,[i]);if(s.length!==0)return s[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let s=e[i],o=t===""?i:`${t}/${i}`;if(s.$ref!==void 0){let d=es(s.$ref);if(d!==void 0){let l=n.get(d.alias);if(l===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${d.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let c=d.protocolPath.split("/"),u=l.structure;for(let f=0;f<c.length;f++){let h=c[f],p=u[h];if(p===void 0)throw new ne(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${o}' references type path '${d.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(p.$ref!==void 0){let m=c.slice(0,f+1).join("/");throw new ne(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${o}' references type path '${d.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=p}}}let a=s.$actions??[];for(let d of a){if(d.role!==void 0){let l=es(d.role);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${d.role}' at protocol path '${o}' was not found in the referenced definitions map.`);if(!Wd(l.protocolPath,c.structure)?.$role)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${d.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${c.protocol}'.`)}}if(d.of!==void 0){let l=es(d.of);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${d.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(Wd(l.protocolPath,c.structure)===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${d.of}' at protocol path '${o}' does not point to a valid type path in protocol '${c.protocol}'.`)}}}r.validateRefsAndRolesRecursively(s,o,n)}}}});var La,p2=G(()=>{"use strict";g();Mc();vr();ia();l2();He();Yo();xt();lr();Ia();La=class r extends Mn{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&mi(e.descriptor.filter.protocol),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??At.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Mt(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:Fo(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Qe.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await Lf.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ne(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var m2,bz=G(()=>{"use strict";g();ra();xt();na();p2();He();lr();m2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await La.parse(t)}catch(o){return gt(o,400)}try{await bn(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 a=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:a}}else return gt(o,401)}let i={...t.descriptor.filter,interface:xe.Protocols,method:me.Configure,isLatestBaseState:!0};Mt(i);let{messages:s}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:s}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:xe.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function lb(r,e,t,n,i,s,o,a){let d=e.signaturePayload?.protocolRole;if(d===void 0)return;let l=t,c=d;if(qf(d)){let p=es(d);if(p===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${d}' could not be parsed as a valid 'alias:path' format.`);if(i.uses?.[p.alias]===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${p.alias}' in '${d}' does not exist in the protocol's 'uses' map.`);l=i.uses[p.alias],c=p.protocolPath;let m=await o(r,l,s,a);if(!Wd(c,m.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${d} does not match role record type.`)}else if(!Wd(d,i.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Protocol path ${d} does not match role record type.`);let u={interface:xe.Records,method:me.Write,protocol:l,protocolPath:c,recipient:e.author,isLatestBaseState:!0},f=c.split("/").length-1;if(n===void 0&&f>0)throw new ne(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=tr.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:h}=await s.query(r,[u]);if(h.length===0)throw new ne(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${c}`)}async function Gue(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,s=await _t.fetchInitialRecordsWrite(t,r,i);if(s===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push(_r.CoPrune),e.author===s.author&&o.push(_r.Prune)):(o.push(_r.CoDelete),e.author===s.author&&o.push(_r.Delete)),o;case me.Count:return[_r.Read];case me.Query:return[_r.Read];case me.Read:return[_r.Read];case me.Subscribe:return[_r.Read];case me.Write:let d=e;if(await d.isInitialWrite())return d.message.descriptor.squash===!0?[_r.Squash,_r.Create]:[_r.Create];{let l=e.message.recordId,c=await _t.fetchInitialRecordsWrite(t,r,l);return c===void 0?[]:e.author===c.author?[_r.CoUpdate,_r.Update]:[_r.CoUpdate]}}return[]}async function ub(r,e,t,n,i,s){let o=e.message.descriptor.method,a=await Gue(r,e,i),d=e.author,l=t.$actions;if(l===void 0)throw new ne(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${o}, ${d} is unauthorized`);let c=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(p=>a.includes(p)))continue;if(u.who===td.Anyone)return;if(d===void 0)continue;if(c!==void 0){if(u.role===c)return;continue}if(u.who===td.Recipient&&u.of===void 0){let p;if(e.message.descriptor.method===me.Write?p=e.message:p=n[n.length-1],p.descriptor.recipient===d)return;continue}if(await Wue(d,u,n,s))return}throw new ne(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Wue(r,e,t,n){let i=e.of;if(i===void 0)return!1;let s;if(qf(i)&&n?.uses!==void 0){let o=es(i);if(o!==void 0){let a=n.uses[o.alias];a!==void 0&&(s=t.find(d=>d.descriptor.protocol===a&&d.descriptor.protocolPath===o.protocolPath))}}else s=t.find(o=>o.descriptor.protocolPath===i);if(s===void 0)return!1;if(e.who===td.Recipient)return r===s.descriptor.recipient;{let o=(await _t.parse(s)).author;return r===o}}var xz=G(()=>{"use strict";g();$c();Zo();xt();lr();Np();kw()});async function kg(r,e,t){let n={interface:xe.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 fb(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let s=await kg(r,i,t);if(s===void 0)throw new ne(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(s),i=s.descriptor.parentId}return n.reverse()}async function S6(r,e,t){let n=await kg(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var Pz=G(()=>{"use strict";g();Zo();xt();lr()});async function Ez(r,e,t,n,i){let s=e.message.descriptor.protocolPath,o=u2(s),a=e.message.descriptor.parentId;if(a===void 0){if(s!==o)throw new ne(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${s}' is not valid for records with no parent'.`);return}let d=e.message.descriptor.protocol,l=await Hue(r,d,s,t,n,i),c={isLatestBaseState:!0,interface:xe.Records,method:me.Write,protocol:l,recordId:a},{messages:u}=await t.query(r,[c]),f=u[0];if(f===void 0)throw l!==d?new ne(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${a}' in protocol '${l}' for cross-protocol child at path '${s}'.`):new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${s}'.`);if(`${f.descriptor.protocolPath}/${o}`!==s)throw new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${s}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Hue(r,e,t,n,i,s){let o=t.split("/");if(o.length<=1)return e;let a=await i(r,e,n,s),d=a.structure[o[0]];if(d?.$ref!==void 0){let l=es(d.$ref);if(l!==void 0&&a.uses!==void 0){let c=a.uses[l.alias];if(c!==void 0)return o.length===2?c:e}}return e}async function Sz(r,e,t,n,i,s){let o=e.descriptor.protocolPath,a=u2(o),d=await Vue(r,o,t,n,i,s);Jue(e,d,a)}async function Vue(r,e,t,n,i,s){let o=e.split("/"),a=t.structure[o[0]];if(a?.$ref!==void 0&&o.length===1){let d=es(a.$ref);if(d!==void 0&&t.uses!==void 0){let l=t.uses[d.alias];if(l!==void 0)return(await i(r,l,n,s)).types}}return t.types}function Jue(r,e,t){let n=t??u2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let s=e[n],{schema:o}=r.descriptor;if(s.schema!==void 0&&s.schema!==o)throw new ne(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${s.schema}', instead has '${o}'`);let{dataFormat:a}=r.descriptor;if(s.dataFormats!==void 0&&!s.dataFormats.includes(a))throw new ne(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${s.dataFormats}), instead has '${a}'`);if(s.encryptionRequired===!0&&r.encryption===void 0)throw new ne(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function Tz(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ne(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ne(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function Dz(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:s,$requiredTags:o,...a}=e.$tags,d=s||!1,l=o||[],c=new _z.default.default,u=c.compile({type:"object",properties:a,required:l,additionalProperties:d});if(!u(t)){let h=c.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ne(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${h}`)}}}async function kz(r,e,t,n){if(!t.$role)return;let i=e,s=i.message.descriptor.recipient;if(s===void 0)throw new ne(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let o=i.message.descriptor.protocolPath,a={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:o,recipient:s},d=ke.getParentContextFromOfContextId(i.message.contextId);if(d!==""){let f=tr.constructPrefixFilterAsRangeFilter(d);a.contextId=f}let{messages:l}=await n.query(r,[a]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ne(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${s}' is already recipient of a role record at protocol path '${o} under the parent context ${d}.`)}async function Az(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:s,strategy:o}=t.$recordLimit,a=e.message.descriptor.protocolPath,d={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:a},l=ke.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=tr.constructPrefixFilterAsRangeFilter(l);d.contextId=u}if(await n.count(r,[d])>=s)throw o===Cu.Reject?new ne(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${s} reached at protocol path '${a}'${l===""?"":` under parent context '${l}'`}: new records are rejected until existing records are deleted.`):new ne(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${o}' is not yet implemented.`)}async function Iz(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne(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 ne(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function Rz(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ne(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var _z,Cz=G(()=>{"use strict";g();kw();_z=Rn(E6(),1);$c();ni();xt();lr();Np()});var Do,Mp=G(()=>{"use strict";g();Np();Ed();xt();lr();xz();Pz();Cz();Do=class r{static async validateReferentialIntegrity(e,t,n,i){let s=await S6(e,t,n),o=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,s,i),a=r.createBoundFetchDefinition(i);await Sz(e,t.message,o,n,a,s),await Ez(e,t,n,a,s);let d=r.getRuleSet(t.message.descriptor.protocolPath,o);await kz(e,t,d,n),Tz(t,d),Dz(t,d),await Rz(t,d),await Iz(t,d),await Az(e,t,d,n)}static async authorizeWrite(e,t,n,i){let s=await kg(e,t.message.recordId,n),o;s===void 0?o=await fb(e,t.message.descriptor.parentId,n):o=await fb(e,t.message.recordId,n);let a=await S6(e,t,n),d=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),l=r.getRuleSet(t.message.descriptor.protocolPath,d),c=r.createBoundFetchDefinition(i);await lb(e,t,t.message.descriptor.protocol,t.message.contextId,d,n,c,a),await ub(e,t,l,o,n,d)}static async authorizeRead(e,t,n,i,s){let o=await fb(e,n.message.recordId,i),a=await kg(e,n.message.recordId,i),d=a===void 0?n.message.descriptor.messageTimestamp:a.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,s),c=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(s);await lb(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await ub(e,t,c,o,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:s,protocolPath:o,contextId:a}=t.message.descriptor.filter,d=await r.fetchProtocolDefinition(e,s,n,void 0,i),l=r.getRuleSet(o,d),c=r.createBoundFetchDefinition(i);await lb(e,t,s,a,d,n,c),await ub(e,t,l,[],n,d)}static async authorizeDelete(e,t,n,i,s){let o=await fb(e,t.message.descriptor.recordId,i),a=await kg(e,t.message.descriptor.recordId,i),d=a===void 0?n.message.descriptor.messageTimestamp:a.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,s),c=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(s);await lb(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await ub(e,t,c,o,i,l)}static async fetchProtocolDefinition(e,t,n,i,s){if(s!==void 0){let l=s.getDefinition(t);if(l!==void 0)return l}let o={interface:xe.Protocols,method:me.Configure,protocol:t};i===void 0?o.isLatestBaseState=!0:o.messageTimestamp={lte:i};let{messages:a}=await n.query(e,[o],{messageTimestamp:It.Descending},{limit:1});if(a.length===0)throw new ne(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return a[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,s)=>r.fetchProtocolDefinition(t,n,i,s,e)}static getRuleSet(e,t){let n=Wd(e,t.structure);if(n===void 0)throw new ne(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var y2,$z=G(()=>{"use strict";g();ra();vr();na();Mp();ni();b_();lr();y2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Md.parse(t)}catch(s){return gt(s,400)}let i;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return gt(s,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={...ke.convertFilter(n),interface:xe.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 ke.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),ke.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),ke.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{...ke.convertFilter(t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var qa,hb=G(()=>{"use strict";g();Mc();vr();Tc();ni();Td();He();Yo();lr();qa=class r extends Mn{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,t),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=At.getCurrentTimestamp(),i={interface:xe.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},s=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:i,authorization:s};return ye.validateJsonSchema(o),new r(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:s,recipient:o,schema:a,parentId:d,dateCreated:l}=e.descriptor,c={isLatestBaseState:!0,protocol:i,protocolPath:s,recipient:o,schema:a,parentId:d,dateCreated:l,contextId:e.contextId,author:this.author,...n};return Mt(c),c}async authorizeDelegate(e,t){let n=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var zf,g2,w2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(zf||(zf={}));g2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[zf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[zf.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(s){console.error("Error while running resumable task:",s),console.error("Resumable task:",i),t.push(i)}}}}});var v2,Oz=G(()=>{"use strict";g();ra();lr();vr();na();ia();Mp();ni();hb();Td();Zo();w2();v2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await qa.parse(t)}catch(l){return gt(l,400)}try{await bn(t.authorization,this.deps.didResolver)}catch(l){return gt(l,401)}let i={interface:xe.Records,recordId:t.descriptor.recordId},{messages:s}=await this.deps.messageStore.query(e,[i]),o=await ye.getNewestMessage(s);if(!ke.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 gt(l,401)}return await this.deps.resumableTaskManager.run({name:zf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,s){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 Qe.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Fn.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await Do.authorizeDelete(e,t,n,i,s)}}});var b2,Bz=G(()=>{"use strict";g();ra();rp();vr();na();Mp();ni();x_();Zo();Ed();lr();b2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await $a.parse(t)}catch(o){return gt(o,400)}let i,s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);i=o.messages,s=o.cursor}else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return gt(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);i=o.messages,s=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);i=o.messages,s=o.cursor}}for(let o of i)if(!await _t.isInitialWrite(o)){let d=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete d.encodedData,o.initialWrite=d}return{status:{code:200,detail:"OK"},entries:i,cursor:s}}convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:It.Ascending};case Ut.CreatedDescending:return{dateCreated:It.Descending};case Ut.PublishedAscending:return{datePublished:It.Ascending};case Ut.PublishedDescending:return{datePublished:It.Descending};case Ut.UpdatedAscending:return{messageTimestamp:It.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:s}=t.message.descriptor,o={...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,isLatestBaseState:!0},a=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],a,s)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:s}=t.message.descriptor,o=[];ke.filterIncludesPublishedRecords(s)&&o.push(r.buildPublishedRecordsFilter(t)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,t.author)&&o.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),ke.shouldProtocolAuthorize(t.signaturePayload)&&o.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),ke.shouldBuildUnpublishedRecipientFilter(s,t.author)&&o.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let a=this.convertDateSort(n);return this.deps.messageStore.query(e,o,a,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,s=r.buildPublishedRecordsFilter(t),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var Hd,T6=G(()=>{"use strict";g();Mc();rp();vr();Tc();ni();Td();He();Yo();xt();lr();Hd=class r extends Mn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ut.PublishedAscending||e.descriptor.dateSort===Ut.PublishedDescending))throw new ne(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 ke.validateDelegatedGrantReferentialIntegrity(e,t),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:s,dateSort:o}=e,a=At.getCurrentTimestamp();if(e.filter.published===!1&&(o===Ut.PublishedAscending||o===Ut.PublishedDescending))throw new ne(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${o}`);let d={interface:xe.Records,method:me.Read,filter:ke.normalizeFilter(t),messageTimestamp:e.messageTimestamp??a,permissionGrantId:i,dateSort:o};Mt(d);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:d,signer:n,permissionGrantId:i,protocolRole:s,delegatedGrant:e.delegatedGrant}));let c={descriptor:d,authorization:l};return ye.validateJsonSchema(c),new r(c)}async authorizeDelegate(e,t){let n=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var x2,jz=G(()=>{"use strict";g();ra();ef();Cn();vr();na();ia();Mp();ni();Td();T6();Zo();xt();lr();x2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Hd.parse(t)}catch(u){return gt(u,400)}try{n.author!==void 0&&await bn(t.authorization,this.deps.didResolver)}catch(u){return gt(u,401)}let i={interface:xe.Records,isLatestBaseState:!0,...ke.convertFilter(t.descriptor.filter)},s=ke.convertDateSort(t.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[i],s,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let a=o[0];if(a.descriptor.method===me.Delete){let u=a,f=u.descriptor.recordId,h=await _t.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return gt(new ne(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let p;try{p=await _t.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await _t.parse(p);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return gt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:h}}}let d=a;try{let u=await _t.parse(d);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return gt(u,401)}let l;if(d.encodedData===void 0){let u=await this.deps.dataStore.get(e,d.recordId,d.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:d}};l=u.dataStream}else{let u=Ie.base64UrlToBytes(d.encodedData);l=Et.fromBytes(u),delete d.encodedData}let c={status:{code:200,detail:"OK"},entry:{recordsWrite:d,data:l}};if(!await _t.isInitialWrite(d)){let f=(await this.deps.messageStore.query(e,[{recordId:d.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,c.entry.initialWrite=f}return c}static async authorizeRecordsRead(e,t,n,i,s){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 a=await Qe.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Fn.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:a,messageStore:i})}else await Do.authorizeRead(e,t,n,i,s)}}}});var za,P2=G(()=>{"use strict";g();Mc();vr();Tc();ni();Td();He();Yo();xt();lr();Ia();za=class r extends Mn{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&mi(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Sd(e.descriptor.filter.schema),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??At.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Mt(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let s={descriptor:t,authorization:i};return ye.validateJsonSchema(s),new r(s)}async authorizeDelegate(e){let t=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var _2,Nz=G(()=>{"use strict";g();ra();rp();vr();na();Mp();ni();P2();Zo();Ed();xt();lr();_2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return gt(new ne(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await za.parse(t)}catch(f){return gt(f,400)}let s=[],o=[];if(ke.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)s=[r.buildPublishedEventFilter(i)],o=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return gt(f,401)}i.author===e?(s=r.buildOwnerEventFilters(i),o=r.buildOwnerQueryFilters(i)):(s=r.buildNonOwnerEventFilters(i),o=r.buildNonOwnerQueryFilters(i))}let a=await ye.getCid(t),{cursor:d}=i.message.descriptor;if(d!==void 0)try{let f=await this.deps.eventLog.subscribe(e,a,n,{cursor:d,filters:s});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code===re.EventLogProgressGap){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h===void 0?void 0:{code:"ProgressGap",...h}}}return gt(f,500)}let l=await this.deps.eventLog.subscribe(e,a,n,{filters:s}),c,u;try{let{dateSort:f,pagination:h}=i.message.descriptor,p=r.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);c=m.messages,u=m.cursor;for(let y of c)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(),gt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:c,cursor:u}}static convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:It.Ascending};case Ut.CreatedDescending:return{dateCreated:It.Descending};case Ut.PublishedAscending:return{datePublished:It.Ascending};case Ut.PublishedDescending:return{datePublished:It.Descending};case Ut.UpdatedAscending:return{messageTimestamp:It.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...ke.convertFilter(t),interface:xe.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...ke.convertFilter(n),author:e.author,interface:xe.Records,method:[me.Write,me.Delete],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...ke.convertFilter(n),interface:xe.Records,method:[me.Write,me.Delete],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...ke.convertFilter(n),interface:xe.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:xe.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return ke.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(i)&&(ke.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...ke.convertFilter(i,n),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var Ag,D6=G(()=>{"use strict";g();ug();$c();vr();ni();hb();Zo();lr();Ag=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:xe.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),s=await ye.getNewestMessage(i);if(!ke.canPerformDeleteAgainstRecord(t,s))return;let o=await qa.parse(t),a=await _t.getInitialWrite(i),d=o.constructIndexes(a),l=await ye.getCid(t);await this.messageStore.put(e,t,d),await this.stateIndex.insert(e,l,d),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:a},d,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:s}=t.descriptor,o={interface:xe.Records,protocol:n,protocolPath:i},a=ke.getParentContextFromOfContextId(t.contextId);if(a!==void 0&&a!==""){let c=tr.constructPrefixFilterAsRangeFilter(a);o.contextId=c}let{messages:d}=await this.messageStore.query(e,[o]),l=new Map;for(let c of d){let u;ke.isRecordsWrite(c)?u=c.recordId:u=c.descriptor.recordId;let f=l.get(u);f===void 0?l.set(u,[c]):f.push(c)}for(let[c,u]of l){if(c===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<s&&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 s=n;s.descriptor.dataSize<=bs.maxDataSizeAllowedToBeEncoded||s.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,s.recordId,s.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,s){let o={interface:xe.Records,parentId:t},{messages:a}=await n.query(e,[o]),d=new Map;for(let l of a){let c;ke.isRecordsWrite(l)?c=l.recordId:c=l.descriptor.recordId;let u=d.get(c);u?u.push(l):d.set(c,[l])}for(let l of d.keys())await r.purgeRecordDescendants(e,l,n,i,s);for(let l of d.keys())await r.purgeRecordMessages(e,d.get(l),n,i,s)}static async purgeRecordMessages(e,t,n,i,s){let o=t.filter(l=>l.descriptor.method===me.Write),a=await ye.getNewestMessage(o);await i.delete(e,a.recordId,a.descriptor.dataCid);let d=await Promise.all(t.map(l=>ye.getCid(l)));await s.delete(e,d),await Promise.all(d.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,s,o){let a=[];for(let d of t){if(await ye.isOlder(d,n)){await r.deleteFromDataStoreIfNeeded(s,e,d,n);let c=await ye.getCid(d);if(await i.delete(e,c),await _t.isInitialWrite(d)){let p=await(await _t.parse(d)).constructIndexes(!1),m=d;delete m.encodedData,await i.put(e,m,p)}else{let f=await ye.getCid(d);a.push(f)}}await o.delete(e,a)}}}});var E2,Mz=G(()=>{"use strict";g();ra();Nl();ef();ug();Cn();$c();vr();na();ia();Mp();ni();Td();Zo();w2();Ed();D6();xt();lr();E2=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 Do.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return gt(p,400)}try{await bn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(p){return gt(p,401)}let s={interface:xe.Records,recordId:t.recordId},{messages:o}=await this.deps.messageStore.query(e,[s]),a=await i.isInitialWrite(),d;if(!a)try{d=await _t.getInitialWrite(o),_t.verifyEqualityOfImmutableProperties(d,t)}catch(p){return gt(p,400)}try{await this.enforceSquashBackstop(e,t)}catch(p){return gt(p,409)}let l=await ye.getNewestMessage(o),c=!1,u;if(l===void 0||await ye.isNewer(t,l)?(c=!0,u=t):u=l,!c){let p=!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;p=!y&&!v}if(!p)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);try{if(l?.descriptor.method===me.Delete)throw new ne(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let p=!1,m=t;if(n===void 0){if(!a){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),p=!0}}else m=await this.processMessageWithDataStream(e,t,n),p=!0;let y=await i.constructIndexes(p);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&&p&&await this.deps.eventLog.emit(e,{message:m,initialWrite:d},y,v)}catch(p){if(p instanceof ne&&(p.code===re.RecordsWriteMissingEncodedDataInPrevious||p.code===re.RecordsWriteMissingDataInPrevious||p.code===re.RecordsWriteNotAllowedAfterDelete||p.code===re.RecordsWriteDataCidMismatch||p.code===re.RecordsWriteDataSizeMismatch||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return gt(p,400);throw p}let h={status:a&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Ag.deleteAllOlderMessagesButKeepInitialWrite(e,o,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:zf.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}),h}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=Ie.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=bs.maxDataSizeAllowedToBeEncoded){let s=await Et.toBytes(n),o=await pr.computeDagPbCidFromBytes(s);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,s.length);let a=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);a?.validateRecord!==void 0&&a.validateRecord(t,s),i=await this.cloneAndAddEncodedData(t,s)}else{let[s,o]=Et.duplicateDataStream(n,2);try{let[a,d]=await Promise.all([pr.computeDagPbCidFromStream(s),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,o)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,a,d.dataSize)}catch(a){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),a}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:s,dataSize:o}=t.descriptor;if(r.validateDataIntegrity(s,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=bs.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new ne(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");i.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ne(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 ne(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ne(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 Do.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(c){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,c);return}let i=t.descriptor.protocolPath.split("/"),s=n.structure[i[0]];for(let c=1;c<i.length&&s!==void 0;c++)s=s[i[c]];if(s?.$squash!==!0)return;let o={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},a=ke.getParentContextFromOfContextId(t.contextId);if(a!==void 0&&a!==""){let c=tr.constructPrefixFilterAsRangeFilter(a);o.contextId=c}let{messages:d}=await this.deps.messageStore.query(e,[o],{messageTimestamp:It.Descending},{limit:1});if(d.length===0)return;let l=d[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ne(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 ne(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 Qe.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Fn.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await Do.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function Sfe(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 s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,d=r.charAt(0),l=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,v=0,w=p.length;v!==w&&p[v]===0;)v++,m++;for(var b=(w-v)*c+1>>>0,T=new Uint8Array(b);v!==w;){for(var D=p[v],I=0,M=b-1;(D!==0||I<y)&&M!==-1;M--,I++)D+=256*T[M]>>>0,T[M]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");y=I,v++}for(var C=b-y;C!==b&&T[C]===0;)C++;for(var z=d.repeat(m);C<b;++C)z+=r.charAt(T[C]);return z}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,v=0;p[m]===d;)y++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var T=t[p.charCodeAt(m)];if(T===255)return;for(var D=0,I=w-1;(T!==0||D<v)&&I!==-1;I--,D++)T+=a*b[I]>>>0,b[I]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");v=D,m++}if(p[m]!==" "){for(var M=w-v;M!==w&&b[M]===0;)M++;for(var C=new Uint8Array(y+(w-M)),z=y;M!==w;)C[z++]=b[M++];return C}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}function jfe(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Nfe(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function M6(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function vF(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zfe;)e[t++]=r&255|qz,r/=128;for(;r&qfe;)e[t++]=r&255|qz,r>>>=7;return e[t]=r|0,vF.bytes=t-n+1,e}function U6(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw U6.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&zz)<<i:(o&zz)*Math.pow(2,i),i+=7}while(o>=Gfe);return U6.bytes=s-n,t}function bF(r){Object.keys(r).forEach(e=>{let t=r[e];t===void 0?delete r[e]:t!==null&&typeof t=="object"&&bF(t)})}function phe(r){let e=r.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t=e.indexOf("%");if(t!==-1&&(e=e.slice(0,t)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=PF(e);return n!==void 0?_F(n):e.includes(":")?whe(e):!1}function Hz(r,e="URL",t){var n;let i=typeof r=="string"?new URL(r):new URL(r.toString()),s=(n=t?.allowedProtocols)!==null&&n!==void 0?n:mhe;if(!s.includes(i.protocol))throw new O2(`${e} must use one of the allowed schemes (${s.join(", ")}): ${i.protocol}`);if(i.hostname==="")throw new O2(`${e} must specify a hostname.`);if(phe(i.hostname))throw new O2(`${e} must not target a private, loopback, or link-local host: ${i.hostname}`);return i}function xF(r,e,t){return hhe(this,void 0,void 0,function*(){var n,i;let s=(n=t?.description)!==null&&n!==void 0?n:"URL",o=(i=t?.maxRedirects)!==null&&i!==void 0?i:yhe,a=Hz(r,s,{allowedProtocols:t?.allowedProtocols}).href;for(let d=0;d<=o;d++){let l=yield fetch(a,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!ghe.has(l.status))return l;let c=l.headers.get("location");if(c===null)return l;a=Hz(new URL(c,a),s,{allowedProtocols:t?.allowedProtocols}).href}throw new Error(`${s} exceeded the maximum number of redirects (${o}).`)})}function PF(r){let e=r.split(".");if(e.length!==4)return;let t=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(t.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return t}function _F([r,e]){return r===0||r===10||r===100&&e>=64&&e<=127||r===127||r===169&&e===254||r===172&&e>=16&&e<=31||r===192&&e===168||r>=224}function whe(r){let e=vhe(r);if(e===void 0)return!1;let[t,n,i,s,o,a,d,l]=e,c=t===0&&n===0&&i===0&&s===0&&o===0&&a===0;return e.every(u=>u===0)||c&&d===0&&l===1||(t&65024)===64512||(t&65472)===65152||(t&65280)===65280?!0:t===100&&n===65435&&i===0&&s===0&&o===0&&a===0||t===0&&n===0&&i===0&&s===0&&o===0&&a===65535?_F(xhe(d,l)):!!c}function vhe(r){let[e,t,n]=r.split("::");if(n!==void 0)return;let i=e===""?[]:e.split(":"),s=t===void 0||t===""?[]:t.split(":"),o=bhe([...i,...s]);if(o===void 0||o.length>8||t===void 0&&o.length!==8||t!==void 0&&o.length>=8)return;let a=o.map(l=>/^[0-9a-f]{1,4}$/.test(l)?Number.parseInt(l,16):Number.NaN);if(!a.every(l=>Number.isInteger(l)&&l>=0&&l<=65535))return;if(t===void 0)return a;let d=new Array(8-a.length).fill(0);return[...a.slice(0,i.length),...d,...a.slice(i.length)]}function bhe(r){let e=r.at(-1);if(!e?.includes("."))return r;let t=PF(e);if(t===void 0)return;let[n,i,s,o]=t;return[...r.slice(0,-1),((n<<8|i)&65535).toString(16),((s<<8|o)&65535).toString(16)]}function xhe(r,e){return[r>>8&255,r&255,e>>8&255,e&255]}function rl(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Yp(r){if(!rl(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=_he[r[t]];return e}function TF(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function l5(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function Vz(r){if(r>=cu._0&&r<=cu._9)return r-cu._0;if(r>=cu._A&&r<=cu._F)return r-(cu._A-10);if(r>=cu._a&&r<=cu._f)return r-(cu._a-10)}function qg(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,s=0;i<t;i++,s+=2){let o=Vz(r.charCodeAt(s)),a=Vz(r.charCodeAt(s+1));if(o===void 0||a===void 0){let d=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+d+'" at index '+s)}n[i]=o*16+a}return n}function Hp(r){return l5(Yp(r))}function oh(r){if(!rl(r))throw new Error("Uint8Array expected");return l5(Yp(Uint8Array.from(r).reverse()))}function nl(r,e){return qg(r.toString(16).padStart(e*2,"0"))}function zg(r,e){return nl(r,e).reverse()}function Ehe(r){return qg(TF(r))}function Zn(r,e,t){let n;if(typeof e=="string")try{n=qg(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(rl(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 Zp(...r){let e=0;for(let i=0;i<r.length;i++){let s=r[i];if(!rl(s))throw new Error("Uint8Array expected");e+=s.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let s=r[i];t.set(s,n),n+=s.length}return t}function She(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 The(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Dhe(r){let e;for(e=0;r>SF;r>>=mE,e+=1);return e}function khe(r,e){return r>>BigInt(e)&mE}function DF(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=k6(r),i=k6(r),s=0,o=()=>{n.fill(1),i.fill(0),s=0},a=(...c)=>t(i,n,...c),d=(c=k6())=>{i=a(Jz([0]),c),n=a(),c.length!==0&&(i=a(Jz([1]),c),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let c=0,u=[];for(;c<e;){n=a();let f=n.slice();u.push(f),c+=n.length}return Zp(...u)};return(c,u)=>{o(),d(c);let f;for(;!(f=u(l()));)d();return o(),f}}function em(r,e,t={}){let n=(i,s,o)=>{let a=Ihe[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let d=r[i];if(!(o&&d===void 0)&&!a(d,r))throw new Error(`Invalid param ${String(i)}=${d} (${typeof d}), expected ${s}`)};for(let[i,s]of Object.entries(e))n(i,s,!1);for(let[i,s]of Object.entries(t))n(i,s,!0);return r}function Yz(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function Rhe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function kF(r,...e){if(!Rhe(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 Che(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yz(r.outputLen),Yz(r.blockLen)}function rE(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 $he(r,e){kF(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function AF(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function IF(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function f5(r){if(typeof r=="string"&&(r=IF(r)),!AF(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function RF(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!AF(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 s=r[n];t.set(s,i),i+=s.length}return t}function $F(r){let e=n=>r().update(f5(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function h5(r=32){if(A6&&typeof A6.getRandomValues=="function")return A6.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Bhe(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),d=n?4:0,l=n?0:4;r.setUint32(e+d,o,n),r.setUint32(e+l,a,n)}function en(r,e){let t=r%e;return t>=xi?t:e+t}function jF(r,e,t){if(t<=xi||e<xi)throw new Error("Expected power/modulo > 0");if(t===xn)return xi;let n=xn;for(;e>xi;)e&xn&&(n=n*r%t),r=r*r%t,e>>=xn;return n}function Dn(r,e,t){let n=r;for(;e-- >xi;)n*=n,n%=t;return n}function q6(r,e){if(r===xi||e<=xi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=en(r,e),n=e,i=xi,s=xn,o=xn,a=xi;for(;t!==xi;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}if(n!==xn)throw new Error("invert: does not exist");return en(i,e)}function qhe(r){let e=(r-xn)/qp,t,n,i;for(t=r-xn,n=0;t%qp===xi;t/=qp,n++);for(i=qp;i<r&&jF(i,e,r)!==r-xn;i++);if(n===1){let o=(r+xn)/L6;return function(a,d){let l=a.pow(d,o);if(!a.eql(a.sqr(l),d))throw new Error("Cannot find square root");return l}}let s=(t+xn)/qp;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let d=n,l=o.pow(o.mul(o.ONE,i),t),c=o.pow(a,s),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(u);f<d&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(l,xn<<BigInt(d-f-1));l=o.sqr(h),c=o.mul(c,h),u=o.mul(u,l),d=f}return c}}function zhe(r){if(r%L6===Khe){let e=(r+xn)/L6;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%Qz===Zz){let e=(r-Zz)/Qz;return function(t,n){let i=t.mul(n,qp),s=t.pow(i,e),o=t.mul(n,s),a=t.mul(t.mul(o,qp),s),d=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(d),n))throw new Error("Cannot find square root");return d}}return r%Lhe,qhe(r)}function Whe(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Ghe.reduce((n,i)=>(n[i]="function",n),e);return em(r,t)}function Hhe(r,e,t){if(t<xi)throw new Error("Expected power > 0");if(t===xi)return r.ONE;if(t===xn)return e;let n=r.ONE,i=e;for(;t>xi;)t&xn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=xn;return n}function Vhe(r,e){let t=new Array(e.length),n=e.reduce((s,o,a)=>r.is0(o)?s:(t[a]=s,r.mul(s,o)),r.ONE),i=r.inv(n);return e.reduceRight((s,o,a)=>r.is0(o)?s:(t[a]=r.mul(s,t[a]),r.mul(s,o)),i),t}function NF(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function p5(r,e,t=!1,n={}){if(r<=xi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:s}=NF(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=zhe(r),a=Object.freeze({ORDER:r,BITS:i,BYTES:s,MASK:u5(i),ZERO:xi,ONE:xn,create:d=>en(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof d}`);return xi<=d&&d<r},is0:d=>d===xi,isOdd:d=>(d&xn)===xn,neg:d=>en(-d,r),eql:(d,l)=>d===l,sqr:d=>en(d*d,r),add:(d,l)=>en(d+l,r),sub:(d,l)=>en(d-l,r),mul:(d,l)=>en(d*l,r),pow:(d,l)=>Hhe(a,d,l),div:(d,l)=>en(d*q6(l,r),r),sqrN:d=>d*d,addN:(d,l)=>d+l,subN:(d,l)=>d-l,mulN:(d,l)=>d*l,inv:d=>q6(d,r),sqrt:n.sqrt||(d=>o(a,d)),invertBatch:d=>Vhe(a,d),cmov:(d,l,c)=>c?l:d,toBytes:d=>t?zg(d,s):nl(d,s),fromBytes:d=>{if(d.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${d.length}`);return t?oh(d):Hp(d)}});return Object.freeze(a)}function Jhe(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 MF(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 UF(r){let e=MF(r);return e+Math.ceil(e/2)}function Yhe(r,e,t=!1){let n=r.length,i=MF(e),s=UF(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let o=t?Hp(r):oh(r),a=en(o,e-xn)+xn;return t?zg(a,i):nl(a,i)}function KF(r,e){let t=(i,s)=>{let o=s.negate();return i?o:s},n=i=>{let s=Math.ceil(e/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:t,unsafeLadder(i,s){let o=r.ZERO,a=i;for(;s>Zhe;)s&R6&&(o=o.add(a)),a=a.double(),s>>=R6;return o},precomputeWindow(i,s){let{windows:o,windowSize:a}=n(s),d=[],l=i,c=l;for(let u=0;u<o;u++){c=l,d.push(c);for(let f=1;f<a;f++)c=c.add(l),d.push(c);l=c.double()}return d},wNAF(i,s,o){let{windows:a,windowSize:d}=n(i),l=r.ZERO,c=r.BASE,u=BigInt(2**i-1),f=2**i,h=BigInt(i);for(let p=0;p<a;p++){let m=p*d,y=Number(o&u);o>>=h,y>d&&(y-=f,o+=R6);let v=m,w=m+Math.abs(y)-1,b=p%2!==0,T=y<0;y===0?c=c.add(t(b,s[v])):l=l.add(t(T,s[w]))}return{p:l,f:c}},wNAFCached(i,s,o,a){let d=i._WINDOW_SIZE||1,l=s.get(i);return l||(l=this.precomputeWindow(i,d),d!==1&&s.set(i,a(l))),this.wNAF(d,l,o)}}}function m5(r){return Whe(r.Fp),em(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...NF(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function Qhe(r){let e=m5(r);em(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 tpe(r){let e=Qhe(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let v=m.toAffine();return Zp(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(p=>{let m=p.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 s(p){let{a:m,b:y}=e,v=t.sqr(p),w=t.mul(v,p);return t.add(t.add(w,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function o(p){return typeof p=="bigint"&&pu<p&&p<e.n}function a(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function d(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof p!="bigint"){if(rl(p)&&(p=Yp(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let b;try{b=typeof p=="bigint"?p:Hp(Zn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return v&&(b=en(b,w)),a(b),b}let l=new Map;function c(p){if(!(p 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=b=>t.eql(b,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(Zn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(d(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=s(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){c(m);let{px:y,py:v,pz:w}=this,{px:b,py:T,pz:D}=m,I=t.eql(t.mul(y,D),t.mul(b,w)),M=t.eql(t.mul(v,D),t.mul(T,w));return I&&M}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,Xz),{px:w,py:b,pz:T}=this,D=t.ZERO,I=t.ZERO,M=t.ZERO,C=t.mul(w,w),z=t.mul(b,b),L=t.mul(T,T),B=t.mul(w,b);return B=t.add(B,B),M=t.mul(w,T),M=t.add(M,M),D=t.mul(m,M),I=t.mul(v,L),I=t.add(D,I),D=t.sub(z,I),I=t.add(z,I),I=t.mul(D,I),D=t.mul(B,D),M=t.mul(v,M),L=t.mul(m,L),B=t.sub(C,L),B=t.mul(m,B),B=t.add(B,M),M=t.add(C,C),C=t.add(M,C),C=t.add(C,L),C=t.mul(C,B),I=t.add(I,C),L=t.mul(b,T),L=t.add(L,L),C=t.mul(L,B),D=t.sub(D,C),M=t.mul(L,z),M=t.add(M,M),M=t.add(M,M),new u(D,I,M)}add(m){c(m);let{px:y,py:v,pz:w}=this,{px:b,py:T,pz:D}=m,I=t.ZERO,M=t.ZERO,C=t.ZERO,z=e.a,L=t.mul(e.b,Xz),B=t.mul(y,b),H=t.mul(v,T),ee=t.mul(w,D),R=t.add(y,v),$=t.add(b,T);R=t.mul(R,$),$=t.add(B,H),R=t.sub(R,$),$=t.add(y,w);let E=t.add(b,D);return $=t.mul($,E),E=t.add(B,ee),$=t.sub($,E),E=t.add(v,w),I=t.add(T,D),E=t.mul(E,I),I=t.add(H,ee),E=t.sub(E,I),C=t.mul(z,$),I=t.mul(L,ee),C=t.add(I,C),I=t.sub(H,C),C=t.add(H,C),M=t.mul(I,C),H=t.add(B,B),H=t.add(H,B),ee=t.mul(z,ee),$=t.mul(L,$),H=t.add(H,ee),ee=t.sub(B,ee),ee=t.mul(z,ee),$=t.add($,ee),B=t.mul(H,$),M=t.add(M,B),B=t.mul(E,$),I=t.mul(R,I),I=t.sub(I,B),B=t.mul(R,H),C=t.mul(E,C),C=t.add(C,B),new u(I,M,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return h.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,b)=>w.toAffine(v[b])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===pu)return y;if(a(m),m===Ja)return this;let{endo:v}=e;if(!v)return h.unsafeLadder(this,m);let{k1neg:w,k1:b,k2neg:T,k2:D}=v.splitScalar(m),I=y,M=y,C=this;for(;b>pu||D>pu;)b&Ja&&(I=I.add(C)),D&Ja&&(M=M.add(C)),C=C.double(),b>>=Ja,D>>=Ja;return w&&(I=I.negate()),T&&(M=M.negate()),M=new u(t.mul(M.px,v.beta),M.py,M.pz),I.add(M)}multiply(m){a(m);let y=m,v,w,{endo:b}=e;if(b){let{k1neg:T,k1:D,k2neg:I,k2:M}=b.splitScalar(y),{p:C,f:z}=this.wNAF(D),{p:L,f:B}=this.wNAF(M);C=h.constTimeNegate(T,C),L=h.constTimeNegate(I,L),L=new u(t.mul(L.px,b.beta),L.py,L.pz),v=C.add(L),w=z.add(B)}else{let{p:T,f:D}=this.wNAF(y);v=T,w=D}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,b=(D,I)=>I===pu||I===Ja||!D.equals(w)?D.multiplyUnsafe(I):D.multiply(I),T=b(this,y).add(b(m,v));return T.is0()?void 0:T}toAffine(m){let{px:y,py:v,pz:w}=this,b=this.is0();m==null&&(m=b?t.ONE:t.inv(w));let T=t.mul(y,m),D=t.mul(v,m),I=t.mul(w,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:T,y:D}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Ja)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===Ja?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return Yp(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,h=KF(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:o}}function rpe(r){let e=m5(r);return em(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function npe(r){let e=rpe(r),{Fp:t,n}=e,i=t.BYTES+1,s=2*t.BYTES+1;function o($){return pu<$&&$<t.ORDER}function a($){return en($,n)}function d($){return q6($,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:u,isWithinCurveOrder:f}=tpe({...e,toBytes($,E,P){let _=E.toAffine(),S=t.toBytes(_.x),A=Zp;return P?A(Uint8Array.from([E.hasEvenY()?2:3]),S):A(Uint8Array.from([4]),S,t.toBytes(_.y))},fromBytes($){let E=$.length,P=$[0],_=$.subarray(1);if(E===i&&(P===2||P===3)){let S=Hp(_);if(!o(S))throw new Error("Point is not on curve");let A=u(S),N=t.sqrt(A),q=(N&Ja)===Ja;return(P&1)===1!==q&&(N=t.neg(N)),{x:S,y:N}}else if(E===s&&P===4){let S=t.fromBytes(_.subarray(0,t.BYTES)),A=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:S,y:A}}else throw new Error(`Point of length ${E} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),h=$=>Yp(nl($,e.nByteLength));function p($){let E=n>>Ja;return $>E}function m($){return p($)?a(-$):$}let y=($,E,P)=>Hp($.slice(E,P));class v{constructor(E,P,_){this.r=E,this.s=P,this.recovery=_,this.assertValidity()}static fromCompact(E){let P=e.nByteLength;return E=Zn("compactSignature",E,P*2),new v(y(E,0,P),y(E,P,2*P))}static fromDER(E){let{r:P,s:_}=Gp.toSig(Zn("DER",E));return new v(P,_)}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(E){return new v(this.r,this.s,E)}recoverPublicKey(E){let{r:P,s:_,recovery:S}=this,A=M(Zn("msgHash",E));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let N=S===2||S===3?P+e.n:P;if(N>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=S&1?"03":"02",W=l.fromHex(q+h(N)),J=d(N),V=a(-A*J),Y=a(_*J),F=l.BASE.multiplyAndAddUnsafe(W,V,Y);if(!F)throw new Error("point at infinify");return F.assertValidity(),F}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return qg(this.toDERHex())}toDERHex(){return Gp.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qg(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey($){try{return c($),!0}catch{return!1}},normPrivateKeyToScalar:c,randomPrivateKey:()=>{let $=UF(e.n);return Yhe(e.randomBytes($),e.n)},precompute($=8,E=l.BASE){return E._setWindowSize($),E.multiply(BigInt(3)),E}};function b($,E=!0){return l.fromPrivateKey($).toRawBytes(E)}function T($){let E=rl($),P=typeof $=="string",_=(E||P)&&$.length;return E?_===i||_===s:P?_===2*i||_===2*s:$ instanceof l}function D($,E,P=!0){if(T($))throw new Error("first arg must be private key");if(!T(E))throw new Error("second arg must be public key");return l.fromHex(E).multiply(c($)).toRawBytes(P)}let I=e.bits2int||function($){let E=Hp($),P=$.length*8-e.nBitLength;return P>0?E>>BigInt(P):E},M=e.bits2int_modN||function($){return a(I($))},C=u5(e.nBitLength);function z($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(pu<=$&&$<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return nl($,e.nByteLength)}function L($,E,P=B){if(["recovered","canonical"].some(ie=>ie in P))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:S}=e,{lowS:A,prehash:N,extraEntropy:q}=P;A==null&&(A=!0),$=Zn("msgHash",$),N&&($=Zn("prehashed msgHash",_($)));let W=M($),J=c(E),V=[z(J),z(W)];if(q!=null){let ie=q===!0?S(t.BYTES):q;V.push(Zn("extraEntropy",ie))}let Y=Zp(...V),F=W;function Q(ie){let oe=I(ie);if(!f(oe))return;let Z=d(oe),le=l.BASE.multiply(oe).toAffine(),he=a(le.x);if(he===pu)return;let ue=a(Z*a(F+he*J));if(ue===pu)return;let Se=(le.x===he?0:2)|Number(le.y&Ja),pe=ue;return A&&p(ue)&&(pe=m(ue),Se^=1),new v(he,pe,Se)}return{seed:Y,k2sig:Q}}let B={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function ee($,E,P=B){let{seed:_,k2sig:S}=L($,E,P),A=e;return DF(A.hash.outputLen,A.nByteLength,A.hmac)(_,S)}l.BASE._setWindowSize(8);function R($,E,P,_=H){let S=$;if(E=Zn("msgHash",E),P=Zn("publicKey",P),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:N}=_,q,W;try{if(typeof S=="string"||rl(S))try{q=v.fromDER(S)}catch(Z){if(!(Z instanceof Gp.Err))throw Z;q=v.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:Z,s:le}=S;q=new v(Z,le)}else throw new Error("PARSE");W=l.fromHex(P)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(A&&q.hasHighS())return!1;N&&(E=e.hash(E));let{r:J,s:V}=q,Y=M(E),F=d(V),Q=a(Y*F),ie=a(J*F),oe=l.BASE.multiplyAndAddUnsafe(W,Q,ie)?.toAffine();return oe?a(oe.x)===J:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:D,sign:ee,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function ipe(r){return{hash:r,hmac:(e,...t)=>qF(r,e,RF(...t)),randomBytes:h5}}function zF(r,e){let t=n=>npe({...r,...ipe(n)});return Object.freeze({...t(e),create:t})}function spe(r){let e=FF,t=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),d=BigInt(88),l=r*r*r%e,c=l*l*r%e,u=Dn(c,t,e)*c%e,f=Dn(u,t,e)*c%e,h=Dn(f,z6,e)*l%e,p=Dn(h,i,e)*h%e,m=Dn(p,s,e)*p%e,y=Dn(m,a,e)*m%e,v=Dn(y,d,e)*y%e,w=Dn(v,a,e)*m%e,b=Dn(w,t,e)*c%e,T=Dn(b,o,e)*p%e,D=Dn(T,n,e)*l%e,I=Dn(D,z6,e);if(!F6.eql(F6.sqr(I),r))throw new Error("Cannot find square root");return I}function ape(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function GF(r,...e){if(!ape(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 r7(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 cpe(r,e){GF(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function dpe(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function WF(r){return typeof r=="string"&&(r=dpe(r)),GF(r),r}function upe(r){let e=n=>r().update(WF(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function fpe(r=32){if(B2&&typeof B2.getRandomValues=="function")return B2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function hpe(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),d=n?4:0,l=n?0:4;r.setUint32(e+d,o,n),r.setUint32(e+l,a,n)}function vpe(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort((o,a)=>o.localeCompare(a)),s={};for(let o of i)s[o]=e(n[o]);return s}return n},t=e(r);return JSON.stringify(t)}function Tr(r){return xpe(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}`);bF(n);let i=vpe(n),s=ot.string(i).toUint8Array(),o=yield HF.digest({data:s});return ot.uint8Array(o).toBase64Url()})}function Vp(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 y5(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 gu(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 g5(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 Ppe(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 JF(r,e=!1){return e?{h:Number(r&T2),l:Number(r>>G6&T2)}:{h:Number(r>>G6&T2)|0,l:Number(r&T2)|0}}function kpe(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:s,l:o}=JF(r[i],e);[t[i],n[i]]=[s,o]}return[t,n]}function qpe(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function tme(r){let e=m5(r);return em(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function w5(r){let e=tme(r),{Fp:t,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:d}=e,l=D2<<BigInt(a*8)-oa,c=t.create,u=e.uvRatio||((P,_)=>{try{return{isValid:!0,value:t.sqrt(P*t.inv(_))}}catch{return{isValid:!1,value:zc}}}),f=e.adjustScalarBytes||(P=>P),h=e.domain||((P,_,S)=>{if(_.length||S)throw new Error("Contexts/pre-hash are not supported");return P}),p=P=>typeof P=="bigint"&&zc<P,m=(P,_)=>p(P)&&p(_)&&P<_,y=P=>P===zc||m(P,l);function v(P,_){if(m(P,_))return P;throw new Error(`Expected valid scalar < ${_}, got ${typeof P} ${P}`)}function w(P){return P===zc?P:v(P,n)}let b=new Map;function T(P){if(!(P instanceof D))throw new Error("ExtendedPoint expected")}class D{constructor(_,S,A,N){if(this.ex=_,this.ey=S,this.ez=A,this.et=N,!y(_))throw new Error("x required");if(!y(S))throw new Error("y required");if(!y(A))throw new Error("z required");if(!y(N))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof D)throw new Error("extended point not allowed");let{x:S,y:A}=_||{};if(!y(S)||!y(A))throw new Error("invalid affine point");return new D(S,A,oa,c(S*A))}static normalizeZ(_){let S=t.invertBatch(_.map(A=>A.ez));return _.map((A,N)=>A.toAffine(S[N])).map(D.fromAffine)}_setWindowSize(_){this._WINDOW_SIZE=_,b.delete(this)}assertValidity(){let{a:_,d:S}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:N,ez:q,et:W}=this,J=c(A*A),V=c(N*N),Y=c(q*q),F=c(Y*Y),Q=c(J*_),ie=c(Y*c(Q+V)),oe=c(F+c(S*c(J*V)));if(ie!==oe)throw new Error("bad point: equation left != right (1)");let Z=c(A*N),le=c(q*W);if(Z!==le)throw new Error("bad point: equation left != right (2)")}equals(_){T(_);let{ex:S,ey:A,ez:N}=this,{ex:q,ey:W,ez:J}=_,V=c(S*J),Y=c(q*N),F=c(A*J),Q=c(W*N);return V===Y&&F===Q}is0(){return this.equals(D.ZERO)}negate(){return new D(c(-this.ex),this.ey,this.ez,c(-this.et))}double(){let{a:_}=e,{ex:S,ey:A,ez:N}=this,q=c(S*S),W=c(A*A),J=c(D2*c(N*N)),V=c(_*q),Y=S+A,F=c(c(Y*Y)-q-W),Q=V+W,ie=Q-J,oe=V-W,Z=c(F*ie),le=c(Q*oe),he=c(F*oe),ue=c(ie*Q);return new D(Z,le,ue,he)}add(_){T(_);let{a:S,d:A}=e,{ex:N,ey:q,ez:W,et:J}=this,{ex:V,ey:Y,ez:F,et:Q}=_;if(S===BigInt(-1)){let ds=c((q-N)*(Y+V)),Ye=c((q+N)*(Y-V)),ar=c(Ye-ds);if(ar===zc)return this.double();let qr=c(W*D2*Q),yr=c(J*D2*F),Gt=yr+qr,k=Ye+ds,U=yr-qr,K=c(Gt*ar),te=c(k*U),de=c(Gt*U),ge=c(ar*k);return new D(K,te,ge,de)}let ie=c(N*V),oe=c(q*Y),Z=c(J*A*Q),le=c(W*F),he=c((N+q)*(V+Y)-ie-oe),ue=le-Z,Se=le+Z,pe=c(oe-S*ie),Ae=c(he*ue),Ot=c(Se*pe),ai=c(he*pe),Lr=c(ue*Se);return new D(Ae,Ot,Lr,ai)}subtract(_){return this.add(_.negate())}wNAF(_){return C.wNAFCached(this,b,_,D.normalizeZ)}multiply(_){let{p:S,f:A}=this.wNAF(v(_,n));return D.normalizeZ([S,A])[0]}multiplyUnsafe(_){let S=w(_);return S===zc?M:this.equals(M)||S===oa?this:this.equals(I)?this.wNAF(S).p:C.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(_){let{ex:S,ey:A,ez:N}=this,q=this.is0();_==null&&(_=q?Xpe:t.inv(N));let W=c(S*_),J=c(A*_),V=c(N*_);if(q)return{x:zc,y:oa};if(V!==oa)throw new Error("invZ was invalid");return{x:W,y:J}}clearCofactor(){let{h:_}=e;return _===oa?this:this.multiplyUnsafe(_)}static fromHex(_,S=!1){let{d:A,a:N}=e,q=t.BYTES;_=Zn("pointHex",_,q);let W=_.slice(),J=_[q-1];W[q-1]=J&-129;let V=oh(W);V===zc||(S?v(V,l):v(V,t.ORDER));let Y=c(V*V),F=c(Y-oa),Q=c(A*Y-N),{isValid:ie,value:oe}=u(F,Q);if(!ie)throw new Error("Point.fromHex: invalid y coordinate");let Z=(oe&oa)===oa,le=(J&128)!==0;if(!S&&oe===zc&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==Z&&(oe=c(-oe)),D.fromAffine({x:oe,y:V})}static fromPrivateKey(_){return B(_).point}toRawBytes(){let{x:_,y:S}=this.toAffine(),A=zg(S,t.BYTES);return A[A.length-1]|=_&oa?128:0,A}toHex(){return Yp(this.toRawBytes())}}D.BASE=new D(e.Gx,e.Gy,oa,c(e.Gx*e.Gy)),D.ZERO=new D(zc,oa,oa,zc);let{BASE:I,ZERO:M}=D,C=KF(D,a*8);function z(P){return en(P,n)}function L(P){return z(oh(P))}function B(P){let _=a;P=Zn("private key",P,_);let S=Zn("hashed private key",s(P),2*_),A=f(S.slice(0,_)),N=S.slice(_,2*_),q=L(A),W=I.multiply(q),J=W.toRawBytes();return{head:A,prefix:N,scalar:q,point:W,pointBytes:J}}function H(P){return B(P).pointBytes}function ee(P=new Uint8Array,..._){let S=Zp(..._);return L(s(h(S,Zn("context",P),!!i)))}function R(P,_,S={}){P=Zn("message",P),i&&(P=i(P));let{prefix:A,scalar:N,pointBytes:q}=B(_),W=ee(S.context,A,P),J=I.multiply(W).toRawBytes(),V=ee(S.context,J,q,P),Y=z(W+V*N);w(Y);let F=Zp(J,zg(Y,t.BYTES));return Zn("result",F,a*2)}let $=eme;function E(P,_,S,A=$){let{context:N,zip215:q}=A,W=t.BYTES;P=Zn("signature",P,2*W),_=Zn("message",_),i&&(_=i(_));let J=oh(P.slice(W,2*W)),V,Y,F;try{V=D.fromHex(S,q),Y=D.fromHex(P.slice(0,W),q),F=I.multiplyUnsafe(J)}catch{return!1}if(!q&&V.isSmallOrder())return!1;let Q=ee(N,Y.toRawBytes(),V.toRawBytes(),_);return Y.add(V.multiplyUnsafe(Q)).subtract(F).clearCofactor().equals(D.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:E,ExtendedPoint:D,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(t.BYTES),precompute(P=8,_=D.BASE){return _._setWindowSize(P),_.multiply(BigInt(3)),_}}}}function rme(r){return em(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function nme(r){let e=rme(r),{P:t}=e,n=b=>en(b,t),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),d=e.powPminus2||(b=>jF(b,t-BigInt(2),t));function l(b,T,D){let I=n(b*(T-D));return T=n(T-I),D=n(D+I),[T,D]}function c(b){if(typeof b=="bigint"&&yb<=b&&b<t)return b;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(b,T){let D=c(b),I=c(T),M=D,C=$6,z=yb,L=D,B=$6,H=yb,ee;for(let $=BigInt(i-1);$>=yb;$--){let E=I>>$&$6;H^=E,ee=l(H,C,L),C=ee[0],L=ee[1],ee=l(H,z,B),z=ee[0],B=ee[1],H=E;let P=C+z,_=n(P*P),S=C-z,A=n(S*S),N=_-A,q=L+B,W=L-B,J=n(W*P),V=n(q*S),Y=J+V,F=J-V;L=n(Y*Y),B=n(M*n(F*F)),C=n(_*A),z=n(N*(_+n(u*N)))}ee=l(H,C,L),C=ee[0],L=ee[1],ee=l(H,z,B),z=ee[0],B=ee[1];let R=d(z);return n(C*R)}function h(b){return zg(n(b),s)}function p(b){let T=Zn("u coordinate",b,s);return o===32&&(T[31]&=127),oh(T)}function m(b){let T=Zn("scalar",b),D=T.length;if(D!==s&&D!==o)throw new Error(`Expected ${s} or ${o} bytes, got ${D}`);return oh(a(T))}function y(b,T){let D=p(T),I=m(b),M=f(D,I);if(M===yb)throw new Error("Invalid private or public key received");return h(M)}let v=h(e.Gu);function w(b){return y(b,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(b,T)=>y(b,T),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function ZF(r){let e=Lb,t=r*r%e*r%e,n=Dn(t,W6,e)*t%e,i=Dn(n,ime,e)*r%e,s=Dn(i,ome,e)*i%e,o=Dn(s,s7,e)*s%e,a=Dn(o,sme,e)*o%e,d=Dn(a,ame,e)*a%e,l=Dn(d,a7,e)*d%e,c=Dn(l,a7,e)*d%e,u=Dn(c,s7,e)*s%e;return{pow_p_5_8:Dn(u,W6,e)*r%e,b2:t}}function QF(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function cme(r,e){let t=Lb,n=en(e*e*e,t),i=en(n*n*e,t),s=ZF(r*i).pow_p_5_8,o=en(r*n*s,t),a=en(e*o*o,t),d=o,l=en(o*o7,t),c=a===r,u=a===en(-r,t),f=a===en(-r*o7,t);return c&&(o=d),(u||f)&&(o=l),Fhe(o,t)&&(o=en(-o,t)),{isValid:c||u,value:o}}function XF(r,e,t){if(e.length>255)throw new Error("Context is too big");return RF(IF("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function dme(r){let{y:e}=Kp.ExtendedPoint.fromHex(r),t=BigInt(1);return Xa.toBytes(Xa.create((t+e)*Xa.inv(t-e)))}function lme(r){let e=qb.hash(r.subarray(0,32));return qb.adjustScalarBytes(e).subarray(0,32)}function bme(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":xme(r)||"Object"}function xme(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(vme.includes(e))return e}function nE(r){return Vb&&globalThis.Buffer.isBuffer(r)}function tG(r){return r instanceof Uint8Array?nE(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function rG(r,e){if(nE(r)&&nE(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 c7(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 Vg(r,e,t){if(r.length-e<t)throw new Error(`${kn} not enough data for type`)}function tm(r,e,t){Vg(r,e,1);let n=r[e];if(t.strict===!0&&n<lo[0])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function rm(r,e,t){Vg(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<lo[1])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function nm(r,e,t){Vg(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<lo[2])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function im(r,e,t){Vg(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],s=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&s<lo[3])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${kn} integers outside of the safe integer range are not supported`)}function Rme(r,e,t,n){return new nt(_e.uint,tm(r,e+1,n),2)}function Cme(r,e,t,n){return new nt(_e.uint,rm(r,e+1,n),3)}function $me(r,e,t,n){return new nt(_e.uint,nm(r,e+1,n),5)}function Ome(r,e,t,n){return new nt(_e.uint,im(r,e+1,n),9)}function om(r,e){return tc(r,0,e.value)}function tc(r,e,t){if(t<lo[0]){let n=Number(t);r.push([e|n])}else if(t<lo[1]){let n=Number(t);r.push([e|24,n])}else if(t<lo[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<lo[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<lo[4]){let i=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&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 Bme(r,e,t,n){return new nt(_e.negint,-1-tm(r,e+1,n),2)}function jme(r,e,t,n){return new nt(_e.negint,-1-rm(r,e+1,n),3)}function Nme(r,e,t,n){return new nt(_e.negint,-1-nm(r,e+1,n),5)}function Mme(r,e,t,n){let i=im(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new nt(_e.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${kn} integers outside of the safe integer range are not supported`);return new nt(_e.negint,v5-BigInt(i),9)}function b5(r,e){let t=e.value,n=typeof t=="bigint"?t*v5-oG:t*-1-1;tc(r,e.type.majorEncoded,n)}function Yb(r,e,t,n){Vg(r,e,t+n);let i=r.slice(e+t,e+t+n);return new nt(_e.bytes,i,t+n)}function Ume(r,e,t,n){return Yb(r,e,1,t)}function Kme(r,e,t,n){return Yb(r,e,2,tm(r,e+1,n))}function Lme(r,e,t,n){return Yb(r,e,3,rm(r,e+1,n))}function qme(r,e,t,n){return Yb(r,e,5,nm(r,e+1,n))}function zme(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer bytes lengths not supported`);return Yb(r,e,9,i)}function iE(r){return r.encodedBytes===void 0&&(r.encodedBytes=_e.equals(r.type,_e.string)?Sme(r.value):r.value),r.encodedBytes}function yE(r,e){let t=iE(e);tc(r,e.type.majorEncoded,t.length),r.push(t)}function Fme(r,e){return r.length<e.length?-1:r.length>e.length?1:rG(r,e)}function Wme(r,e,t){if(t-e<Gme){let n="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return d7.decode(r.subarray(e,t));n+=String.fromCharCode(s)}return n}return d7.decode(r.subarray(e,t))}function Zb(r,e,t,n,i){let s=t+n;Vg(r,e,s);let o=new nt(_e.string,Wme(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=r.slice(e+t,e+s)),o}function Hme(r,e,t,n){return Zb(r,e,1,t,n)}function Vme(r,e,t,n){return Zb(r,e,2,tm(r,e+1,n),n)}function Jme(r,e,t,n){return Zb(r,e,3,rm(r,e+1,n),n)}function Yme(r,e,t,n){return Zb(r,e,5,nm(r,e+1,n),n)}function Zme(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer string lengths not supported`);return Zb(r,e,9,i,n)}function Jg(r,e,t,n){return new nt(_e.array,n,t)}function Xme(r,e,t,n){return Jg(r,e,1,t)}function eye(r,e,t,n){return Jg(r,e,2,tm(r,e+1,n))}function tye(r,e,t,n){return Jg(r,e,3,rm(r,e+1,n))}function rye(r,e,t,n){return Jg(r,e,5,nm(r,e+1,n))}function nye(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer array lengths not supported`);return Jg(r,e,9,i)}function iye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Jg(r,e,1,1/0)}function x5(r,e){tc(r,_e.array.majorEncoded,e.value)}function Yg(r,e,t,n){return new nt(_e.map,n,t)}function oye(r,e,t,n){return Yg(r,e,1,t)}function sye(r,e,t,n){return Yg(r,e,2,tm(r,e+1,n))}function aye(r,e,t,n){return Yg(r,e,3,rm(r,e+1,n))}function cye(r,e,t,n){return Yg(r,e,5,nm(r,e+1,n))}function dye(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer map lengths not supported`);return Yg(r,e,9,i)}function lye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Yg(r,e,1,1/0)}function P5(r,e){tc(r,_e.map.majorEncoded,e.value)}function uye(r,e,t,n){return new nt(_e.tag,t,1)}function fye(r,e,t,n){return new nt(_e.tag,tm(r,e+1,n),2)}function hye(r,e,t,n){return new nt(_e.tag,rm(r,e+1,n),3)}function pye(r,e,t,n){return new nt(_e.tag,nm(r,e+1,n),5)}function mye(r,e,t,n){return new nt(_e.tag,im(r,e+1,n),9)}function _5(r,e){tc(r,_e.tag.majorEncoded,e.value)}function yye(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${kn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new nt(_e.null,null,1):new nt(_e.undefined,void 0,1)}function gye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return new nt(_e.break,void 0,1)}function E5(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 nt(_e.float,r,e)}function wye(r,e,t,n){return E5(T5(r,e+1),3,n)}function vye(r,e,t,n){return E5(D5(r,e+1),5,n)}function bye(r,e,t,n){return E5(hG(r,e+1),9,n)}function S5(r,e,t){let n=e.value;if(n===!1)r.push([_e.float.majorEncoded|sG]);else if(n===!0)r.push([_e.float.majorEncoded|aG]);else if(n===null)r.push([_e.float.majorEncoded|cG]);else if(n===void 0)r.push([_e.float.majorEncoded|dG]);else{let i,s=!1;(!t||t.float64!==!0)&&(uG(n),i=T5(Fc,1),n===i||Number.isNaN(n)?(Fc[0]=249,r.push(Fc.slice(0,3)),s=!0):(fG(n),i=D5(Fc,1),n===i&&(Fc[0]=250,r.push(Fc.slice(0,5)),s=!0))),s||(xye(n),i=hG(Fc,1),Fc[0]=251,r.push(Fc.slice(0,9)))}}function uG(r){if(r===1/0)Ha.setUint16(0,31744,!1);else if(r===-1/0)Ha.setUint16(0,64512,!1);else if(Number.isNaN(r))Ha.setUint16(0,32256,!1);else{Ha.setFloat32(0,r);let e=Ha.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ha.setUint16(0,31744,!1);else if(t===0)Ha.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ha.setUint16(0,0):i<-14?Ha.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ha.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function T5(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,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function fG(r){Ha.setFloat32(0,r,!1)}function D5(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 xye(r){Ha.setFloat64(0,r,!1)}function hG(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 mr(r,e,t){throw new Error(`${kn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function gE(r){return()=>{throw new Error(`${kn} ${r}`)}}function Pye(r){switch(r.type){case _e.false:return fu([244]);case _e.true:return fu([245]);case _e.null:return fu([246]);case _e.bytes:return r.value.length?void 0:fu([64]);case _e.string:return r.value===""?fu([96]):void 0;case _e.array:return r.value===0?fu([128]):void 0;case _e.map:return r.value===0?fu([160]):void 0;case _e.uint:return r.value<24?fu([Number(r.value)]):void 0;case _e.negint:if(r.value>=-24)return fu([31-Number(r.value)])}}function Eye(){let r=[];return r[_e.uint.major]=om,r[_e.negint.major]=b5,r[_e.bytes.major]=yE,r[_e.string.major]=Qme,r[_e.array.major]=x5,r[_e.map.major]=P5,r[_e.tag.major]=_5,r[_e.float.major]=S5,r}function j2(r,e={},t){let n=bme(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||ah[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=ah[n];if(!s)throw new Error(`${iG} unsupported type: ${n}`);return s(r,n,e,t)}function Dye(r,e){e.mapSorter&&r.sort(e.mapSorter)}function kye(r,e){if(r[0]instanceof nt&&e[0]instanceof nt){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=u7(t.value)),n._keyBytes||(n._keyBytes=u7(n.value)),rG(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function u7(r){return Aye(r,Sye,_ye)}function mG(r,e,t,n){if(Array.isArray(e))for(let i of e)mG(r,i,t,n);else t[e.type.major](r,e,n)}function Aye(r,e,t,n){let i=n instanceof Uint8Array,s=i?new Ime(n):Tye,o=j2(r,t);if(!Array.isArray(o)&&t.quickEncodeToken){let a=t.quickEncodeToken(o);if(a)return i?(s.push(a),s.toBytes()):a;let d=e[o.type.major];if(d.encodedSize){let l=d.encodedSize(o,t);if(i||(s=new nG(l)),d(s,o,t),s.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return i?s.toBytes():tG(s.chunks[0])}}return s.reset(),mG(s,o,e,t),s.toBytes(!0)}function rs(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function Iye({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function Rye({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=wE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await Tr({jwk:e})===await Tr({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function wE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(oE)??[]),Object.keys(hE).forEach(t=>{e.push(...r[t]?.filter(oE)??[])}),e}function yG({didDocument:r}){let e=wE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function gG({didDocument:r,methodId:e}){let t=[];return Object.keys(hE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],s=rs(e);i.some(o=>{let a=rs(o)===s,d=oE(o)&&rs(o.id)===s;return a||d})&&t.push(n)}}),t}function wG(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function Cye(r){return!(!wG(r)||r.type!=="DecentralizedWebNode")}function oE(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 Zg(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 vG({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=ec.addPrefix({code:e,data:r,name:t}),i=ot.uint8Array(n).toBase58Btc();return ot.base58Btc(i).toMultibase()}function bG({multibaseKeyId:r}){try{let e=ot.multibase(r).toBase58Btc(),t=ot.base58Btc(e).toUint8Array(),{code:n,data:i,name:s}=ec.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:s}}catch{throw new rt("invalidDid",`Invalid multibase identifier: ${r}`)}}function Xb(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function TG(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=Oye(n),br.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function AG(r,e,t){let n=0,i=1;for(let s=e;s<t;s++){let o=r[s];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(s===e&&o===43)){if(s===e&&o===45){i=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+s+"] = "+o)}}return n*i}function vt(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),vt.position=0,vt.encoding=n||null,vt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):wu(r),vt.bytes=vt.data.length,vt.next())}function Fye(r){let e=2;for(let t of r)e+=bE(t);return e}function Gye(r){let e=2;for(let[t,n]of r){let i=wu(t).byteLength;e+=Xb(i)+1+i,e+=bE(n)}return e}function Wye(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=wu(t[n]).byteLength;e+=Xb(i)+1+i,e+=bE(r[t[n]])}return e}function Hye(r){let e=wu(r).byteLength;return Xb(e)+1+e}function Vye(r){let e=r.byteLength-r.byteOffset;return Xb(e)+1+e}function bE(r){if(r==null)return 0;let e=TG(r);switch(e){case"arraybufferview":return Vye(r);case"string":return Hye(r);case"array":case"set":return Fye(r);case"number":return 1+Xb(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Wye(r);case"map":return Gye(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function CG(r){if(tl.isFormat(r))return tl.size;if(sh.isFormat(r))return sh.size;throw Error(`Invalid ip address: ${r}`)}function Qye(r){return CG(r)===tl.size?1:2}function Xye(r,e,t){t=~~t;let n=CG(r);return typeof e=="function"&&(e=e(t+n)),n===tl.size?tl.encode(r,e,t):sh.encode(r,e,t)}function ege(r,e,t){if(e=~~e,t=t||r.length-e,t===tl.size)return tl.decode(r,e,t);if(t===sh.size)return sh.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${tl.size} for v4 or ${sh.size} for v6.`)}function xE(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 zb(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 tge(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 rge(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 $G(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 OG(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 nge(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 E7(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 BG(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 s=n+1;s===t||i>=56320||(r.charCodeAt(s)&64512)!==56320?e+=3:(n=s,e+=4)}}return e}function Fb(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(BG(r)+t));let i=t;for(let s=0;s<n;s+=1){let o=r.charCodeAt(s);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 a=s+1;if(a===n||o>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let d=r.charCodeAt(a);(d&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(s=a,o=65536|(o&1023)<<10|d&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 Fb.bytes=i-t,e}function e1(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let s=r[i++],o;if(s<=128)o=s;else if(s>191&&s<224)o=(s&31)<<6|r[i++]&63;else if(s>239&&s<365){o=((s&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let a=55296|o>>10&1023;n+=String.fromCharCode(a),o=56320|o&1023}else o=(s&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(o)}return e1.bytes=t-e,n}function ch(r){return typeof r=="string"?BG(r):r.byteLength}function R5(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):Fb(r)}function C5(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return Fb(e,r,t),Fb.bytes}function ige(r,e,t){let n="";for(let i=e;i<t;){let s=r[i++];n+=jG[s]}return n}function S7(r){return r.length>>>1}function oge(r,e,t,n){let i=0;for(;t<n;){let s=e.substr(i,2),o=Eb[s];if(o===void 0)return;r[t++]=o,i+=2}return r}function la(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:dge(r,e,t,n,i)}function dge(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let s=i-n,o=r.length-n;return s>o&&(s=o),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,s)),e.set(r,t),s}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 V6(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function B6(r){switch(r.toUpperCase()){case"A":return MG;case"PTR":return Ug;case"CNAME":return Ug;case"DNAME":return Ug;case"TXT":return K2;case"NULL":return L2;case"AAAA":return G2;case"SRV":return z2;case"HINFO":return q2;case"CAA":return nh;case"NS":return M2;case"SOA":return U2;case"MX":return F2;case"OPT":return ih;case"DNSKEY":return el;case"RRSIG":return Sb;case"RP":return Tb;case"NSEC":return Db;case"NSEC3":return kb;case"SSHFP":return jg;case"DS":return Ab}return N2}function sE(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 UG(r){let e=dE(r),t=new Uint8Array(2+e.byteLength);return st(t,e.byteLength),la(e,t,2,0,e.length),UG.bytes=t.byteLength,t}function KG(r){let e=Lt(r,0);if(r.byteLength<e+2)return null;let t=J6(r.slice(2));return KG.bytes=J6.bytes,t}function Ng(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function Ib(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 k2(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 LG(r,e){let t=ot.uint8Array(r).toBase32Z();return new URL(t,e).href}async function qG(r,e,t){if(t)return fetch(r,e);try{return await xF(r,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof O2?new rt("invalidGatewayUri",n.message):n}}async function mge({gatewayUri:r,publicKeyBytes:e,allowPrivateGatewayUri:t=!1}){let n=ot.uint8Array(e).toBase32Z(),i=LG(e,r),s;try{if(s=await qG(i,{method:"GET",signal:AbortSignal.timeout(3e4)},t),!s.ok)throw new rt("notFound",`Pkarr record not found for: ${n}`)}catch(a){throw a instanceof rt?a:new rt("internalError",`Failed to fetch Pkarr record: ${a.message}`)}let o=await s.arrayBuffer();if(!o)throw new rt("notFound",`Pkarr record not found for: ${n}`);if(o.byteLength<72)throw new rt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${o.byteLength}`);if(o.byteLength>1072)throw new rt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${o.byteLength}`);return{k:e,seq:Number(new DataView(o).getBigUint64(64)),sig:new Uint8Array(o,0,64),v:new Uint8Array(o,72)}}async function yge({gatewayUri:r,bep44Message:e,allowPrivateGatewayUri:t=!1}){let n=ot.uint8Array(e.k).toBase32Z(),i=LG(e.k,r),s=new Uint8Array(e.v.length+72);s.set(e.sig,0),new DataView(s.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),s.set(e.v,e.sig.length+8);let o;try{o=await qG(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)},t)}catch(a){throw a instanceof rt?a:new rt("internalError",`Failed to put Pkarr record for identifier ${n}: ${a.message}`)}return o.ok}async function gge({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=dE(r),s=RG.encode({seq:n,v:i}).subarray(1,-1);if(s.length>1e3)throw new rt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${s.length} bytes`);let o=await t.sign({data:new Uint8Array(s)});return{k:e,seq:n,sig:o,v:i}}async function wge({bep44Message:r}){let e=await co.bytesToPublicKey({publicKeyBytes:r.k}),t=RG.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await co.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new rt("invalidSignature","Invalid signature for DHT BEP44 message");return J6(r.v)}async function FG({didUri:r}){let e=$5({didUri:r});return await co.bytesToPublicKey({publicKeyBytes:e})}function $5({didUri:r}){let e=Qn.parse(r);if(!e)throw new rt("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==zG)throw new rt("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=ot.base32Z(e.id).toUint8Array()}catch{throw new rt("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new rt("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function vge({identityKey:r}){let e=await co.publicKeyToBytes({publicKey:r}),t=ot.uint8Array(e).toBase32Z();return`did:${zG}:${t}`}function O5(r){let e={Ed25519:co,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await Ao.publicKeyToBytes({publicKey:t});return await Ao.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Ao.bytesToPublicKey,privateKeyToBytes:Ao.privateKeyToBytes,bytesToPrivateKey:Ao.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await ao.publicKeyToBytes({publicKey:t});return await ao.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ao.bytesToPublicKey,privateKeyToBytes:ao.privateKeyToBytes,bytesToPrivateKey:ao.bytesToPrivateKey},X25519:Rg}[r];if(!e)throw new rt("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function GG({newDid:r,previousDidProof:e}){let t=await FG({didUri:e.previousDid}),n=$5({didUri:r}),i=ot.base64Url(e.signature).toUint8Array();if(!await co.verify({key:t,data:n,signature:i}))throw new rt("invalidPreviousDidProof","The previous DID proof is invalid.")}function Gb(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return ot.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>Gb(e)).join("");throw new rt("internalError","Pkarr returned DNS TXT record with invalid data type")}function Rb(r){return Gb(r).split(W2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function VG(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 xge({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let s of e?.answers??[]){if(s.type!=="TXT")continue;let o=s.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let a=Gb(s.data);t.alsoKnownAs=a.split(ts);break}case o.startsWith("cnt"):{let a=Gb(s.data);t.controller=a.includes(ts)?a.split(ts):a;break}case o.startsWith("k"):{let{id:a,t:d,k:l,c,a:u}=Rb(s.data),f=ot.base64Url(l).toUint8Array(),h=A5[Number(d)],p=await O5(h).bytesToPublicKey({publicKeyBytes:f});p.alg=u||HG[Number(d)];let m=o==="k0"?"0":a===void 0?await Tr({jwk:p}):a;t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:c??r,publicKeyJwk:p}),i.set(o,y);break}case o.startsWith("s"):{let{id:a,t:d,se:l,...c}=Rb(s.data),u=l.includes(ts)?l.split(ts):[l],f=Object.fromEntries(Object.entries(c).map(([h,p])=>[h,p.includes(ts)?p.split(ts):p]));t.service??=[],t.service.push({...f,id:`${r}#${a}`,type:d,serviceEndpoint:u});break}case o.startsWith("typ"):{let{id:a}=Rb(s.data);n.types=a.split(ts).map(d=>Number(d));break}case o.startsWith("did"):{let a=h=>h.split(ts).map(p=>i.get(p)).filter(p=>typeof p=="string"),{auth:d,asm:l,del:c,inv:u,agm:f}=Rb(s.data);d&&(t.authentication=a(d)),l&&(t.assertionMethod=a(l)),c&&(t.capabilityDelegation=a(c)),u&&(t.capabilityInvocation=a(u)),f&&(t.keyAgreement=a(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function Pge({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],s=[],o=new Map,a=[],d=[];if(n!==void 0){let{signature:c,previousDid:u}=n;await GG({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:Xf,data:`id=${u};s=${c}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:Xf,data:r.alsoKnownAs.join(ts)}),r.controller){let c=Array.isArray(r.controller)?r.controller.join(ts):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:Xf,data:c})}for(let[c,u]of r.verificationMethod?.entries()??[]){let f=`k${c}`;d.push(f);let h=u.id.split("#").pop();o.set(h,f);let p=u.publicKeyJwk;if(!(p?.crv&&p.crv in WG))throw new rt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=A5[p.crv],y=await O5(p.crv).publicKeyToBytes({publicKey:p}),v=ot.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];h!=="0"&&await Tr({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==HG[m]&&w.push(`a=${p.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:Xf,data:w.join(W2)})}r.service?.forEach((c,u)=>{let f=`s${u}`;a.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=c;h=rs(h),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:h,t:p,se:m,...y}).map(([b,T])=>`${b}=${T}`).join(W2),w=VG(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:Xf,data:w})});let l=[`v=${bge}`];if(d.length&&l.push(`vm=${d.join(ts)}`),Object.keys(hE).forEach(c=>{let u=r[c]?.map(f=>o.get(f.split("#").pop()));if(u){let f=_G[c];l.push(`${f}=${u.join(ts)}`)}}),a.length&&l.push(`svc=${a.join(ts)}`),e.types?.length){let c=e.types.map(u=>typeof u=="string"?PG[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:Xf,data:`id=${c.join(ts)}`})}i.push({type:"TXT",name:"_did."+k7(r.id)+".",ttl:Xf,data:l.join(W2)});for(let c of t||[])s.push({type:"NS",name:"_did."+k7(r.id)+".",ttl:Xf,data:c+"."});return{id:0,type:"response",flags:hge,answers:[...i,...s]}}function k7(r){return r.split(":")[2]}function Ege(){return O.DID_DHT_GATEWAY_URI||_ge}function Sge(){return O.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function A7(r,e){return{gatewayUri:r??Ege(),allowPrivateGatewayUri:e??Sge()}}function ZG(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Uge;)e[t++]=r&255|C7,r/=128;for(;r&Mge;)e[t++]=r&255|C7,r>>>=7;return e[t]=r|0,ZG.bytes=t-n+1,e}function X6(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw X6.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&$7)<<i:(o&$7)*Math.pow(2,i),i+=7}while(o>=Lge);return X6.bytes=s-n,t}function hwe(r){r=L5(r);let e=Lg+8;(r.length<e||r.length>1024)&&Bi("expected proper params");let t=tt(SE(r),K5-1n)+1n;return z5(t)}var Yue,i5,Zue,Que,Xue,efe,Xt,o5,tfe,Xp,rfe,nfe,il,ife,ofe,s5,nF,iF,oF,sfe,afe,cfe,dfe,fE,a5,Wp,lfe,ufe,sF,ffe,hfe,aF,pfe,mfe,yfe,Uz,cF,gfe,dF,lF,wfe,vfe,bfe,uF,xfe,Pfe,fF,hE,fo,oo,Qn,rt,_fe,Qa,ks,Efe,Tfe,Dfe,kfe,P9e,Afe,c5,Ife,Rfe,Cfe,yF,$fe,gF,wF,Ofe,Bfe,ua,$2,_9e,E9e,S9e,T9e,D9e,k9e,A9e,Kz,Ya,I9e,R9e,C9e,au,$9e,pb,Lz,S2,Up,ot,jb,Mfe,Ufe,xb,Kfe,qz,Lfe,qfe,zfe,Ffe,Gfe,zz,Wfe,Hfe,Vfe,Jfe,Yfe,Zfe,Qfe,Xfe,ehe,the,rhe,nhe,eE,tE,Mb,Ub,ihe,ohe,she,d5,Fz,Gz,K6,O9e,ahe,che,dhe,mb,lhe,Wz,uhe,ec,B9e,Ff,fhe,hhe,mhe,O2,yhe,ghe,pE,EF,SF,mE,Phe,_he,cu,Ahe,u5,k6,Jz,Ihe,A6,I6,Vd,Ohe,CF,j9e,OF,jhe,Nhe,Mhe,Gf,Wf,Uhe,BF,xi,xn,qp,Khe,L6,Zz,Qz,N9e,Lhe,Fhe,Ghe,Zhe,R6,Xhe,epe,Gp,pu,Ja,M9e,Xz,U9e,LF,qF,FF,e7,ope,z6,t7,F6,aa,K9e,L9e,B2,C6,Jd,q9e,lpe,z9e,ppe,mpe,ype,gpe,Hf,Vf,wpe,Kb,bpe,HF,xpe,n7,no,_pe,ao,VF,Epe,Spe,Tpe,Fa,io,Dpe,Ao,du,i7,T2,G6,Ape,Ipe,Rpe,Cpe,$pe,Ope,Bpe,jpe,Npe,Mpe,Upe,Kpe,Lpe,zpe,Fpe,Gpe,Wpe,Hpe,Vpe,Jpe,Kt,Ype,Zpe,Jf,Yf,Qpe,YF,zc,oa,D2,Xpe,eme,yb,$6,Lb,o7,F9e,ime,W6,ome,s7,sme,ame,a7,Xa,qb,Kp,G9e,W9e,Pb,ume,H9e,V9e,J9e,Y9e,Z9e,Q9e,X9e,eze,tze,rze,Ga,fme,co,lu,hme,pme,mme,Zf,yme,Rg,gb,gme,uu,O6,Wc,wme,vme,_e,nt,Vb,Pme,_me,Eme,Sme,fu,Tme,Dme,kme,Ame,nG,Ime,kn,iG,Jb,lo,v5,oG,d7,Gme,Qme,sG,aG,cG,dG,lG,Ha,Fc,Be,vu,_ye,Sye,Tye,l7,Qf,ah,nze,ize,oze,sze,aze,cze,dze,lze,uze,fze,hze,pze,mze,f7,Io,Za,h7,p7,yze,gze,wze,vze,m7,y7,g7,w7,k5,Ro,Qb,PG,A5,_G,v7,EG,b7,$ye,Oye,x7,Bye,wb,jye,SG,Nye,wu,P7,_7,bze,vE,DG,kG,Mye,Uye,Kye,Lye,qye,I5,zye,IG,Jye,RG,Yye,Zye,tl,sh,Qp,Eb,jG,sge,age,cge,mu,Lt,yu,st,lge,T7,H6,uge,NG,fge,Ve,bi,Cg,N2,M2,U2,K2,L2,q2,Ug,z2,nh,F2,MG,G2,D7,hu,ih,el,Sb,Tb,da,Db,kb,Ab,jg,Va,Kg,hge,uo,aE,cE,dE,J6,pge,zG,bge,Xf,W2,ts,WG,HG,_ge,JG,fa,I7,Mg,Jn,Yn,xze,Tge,Dge,kge,Age,YG,Ige,Rge,Cge,$ge,PE,Pze,_ze,R7,Eze,Fg,Oge,Z6,Xd,sa,B5,Gc,Bge,Wb,jge,C7,Nge,Mge,Uge,Kge,Lge,$7,qge,zge,Fge,Gge,Wge,Hge,Vge,Jge,Yge,Zge,Qge,Xge,lE,O7,B7,j7,N7,ewe,QG,XG,twe,eW,M7,Sze,vb,ca,e5,A2,t5,Ig,I2,tW,U7,rwe,so,V2,r5,n5,R2,Ds,nW,j5,Gg,nwe,dt,K7,L7,Wg,uE,J2,iW,N5,M5,iwe,owe,q7,oW,Yd,swe,z7,awe,j6,F7,cwe,zp,dwe,lwe,U5,Jp,K5,sW,aW,cW,Lg,G7,Bi,_E,dW,N6,lW,uW,Hb,L5,tt,W7,H7,Hg,Nb,Y2,fW,q5,EE,SE,V7,z5,J7,Y7,hW,uwe,fwe,Z7,Z2,pwe,Fp,mwe,ywe,Q7,X7,bb,gwe,wwe,eF,vwe,pW,ns,bwe,Q2,C2,xwe,tF,mW,sm,Pwe,yW,TE,_we,Ewe,DE,Swe,t1,Twe,dh,is=G(()=>{"use strict";g();Yue=Object.create,i5=Object.defineProperty,Zue=Object.getOwnPropertyDescriptor,Que=Object.getOwnPropertyNames,Xue=Object.getPrototypeOf,efe=Object.prototype.hasOwnProperty,Xt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),o5=(r,e)=>{for(var t in e)i5(r,t,{get:e[t],enumerable:!0})},tfe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Que(e))!efe.call(r,i)&&i!==t&&i5(r,i,{get:()=>e[i],enumerable:!(n=Zue(e,i))||n.enumerable});return r},Xp=(r,e,t)=>(t=r!=null?Yue(Xue(r)):{},tfe(e||!r||!r.__esModule?i5(t,"default",{value:r,enumerable:!0}):t,r)),rfe=Xt((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),s=a=>a===1/0||i(a),o=class rF{constructor({max:d=1/0,ttl:l,updateAgeOnGet:c=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!s(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!s(d))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=d,this.updateAgeOnGet=!!c,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!p,h!==void 0){if(typeof h!="function")throw new TypeError("dispose must be function if set");this.dispose=h}this.timer=void 0,this.timerExpiration=void 0}setTimer(d,l){if(this.timerExpiration<d)return;this.timer&&clearTimeout(this.timer);let c=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);c.unref&&c.unref(),this.timerExpiration=d,this.timer=c}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 d=this.dispose!==rF.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,c]of d)this.dispose(c,l,"delete")}setTTL(d,l=this.ttl){let c=this.expirationMap.get(d);if(c!==void 0){let u=this.expirations[c];!u||u.length<=1?delete this.expirations[c]:this.expirations[c]=u.filter(f=>f!==d)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(d,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(d)}else this.expirationMap.set(d,1/0)}set(d,l,{ttl:c=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!s(c))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(d)){u||this.setTTL(d,c);let h=this.data.get(d);h!==l&&(this.data.set(d,l),f||this.dispose(h,d,"set"))}else this.setTTL(d,c),this.data.set(d,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(d){return this.data.has(d)}getRemainingTTL(d){let l=this.expirationMap.get(d);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(d,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:c=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(d);if(u&&this.getRemainingTTL(d)===0){this.delete(d);return}return l&&this.setTTL(d,c),f}dispose(d,l){}delete(d){let l=this.expirationMap.get(d);if(l!==void 0){let c=this.data.get(d);this.data.delete(d),this.expirationMap.delete(d);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==d)),this.dispose(c,d,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let d in this.expirations){let l=this.expirations[d];if(this.size-l.length>=this.max){delete this.expirations[d];let c=[];for(let u of l)c.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of c)this.dispose(f,u,"evict")}else{let c=this.size-this.max,u=[];for(let f of l.splice(0,c))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let d=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>d)return;let c=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of c)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let d in this.expirations)for(let l of this.expirations[d])yield[l,this.data.get(l)]}*keys(){for(let d in this.expirations)for(let l of this.expirations[d])yield l}*values(){for(let d in this.expirations)for(let l of this.expirations[d])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=o}),nfe=Xt(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)})}}),il=Xt((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)}}}),ife=Xt(r=>{"use strict";r.byteLength=d,r.toByteArray=c,r.fromByteArray=h;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(s=0,o=i.length;s<o;++s)e[s]=i[s],t[i.charCodeAt(s)]=s;var s,o;t[45]=62,t[95]=63;function a(p){var m=p.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=p.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function d(p){var m=a(p),y=m[0],v=m[1];return(y+v)*3/4-v}function l(p,m,y){return(m+y)*3/4-y}function c(p){var m,y=a(p),v=y[0],w=y[1],b=new n(l(p,v,w)),T=0,D=w>0?v-4:v,I;for(I=0;I<D;I+=4)m=t[p.charCodeAt(I)]<<18|t[p.charCodeAt(I+1)]<<12|t[p.charCodeAt(I+2)]<<6|t[p.charCodeAt(I+3)],b[T++]=m>>16&255,b[T++]=m>>8&255,b[T++]=m&255;return w===2&&(m=t[p.charCodeAt(I)]<<2|t[p.charCodeAt(I+1)]>>4,b[T++]=m&255),w===1&&(m=t[p.charCodeAt(I)]<<10|t[p.charCodeAt(I+1)]<<4|t[p.charCodeAt(I+2)]>>2,b[T++]=m>>8&255,b[T++]=m&255),b}function u(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var v,w=[],b=m;b<y;b+=3)v=(p[b]<<16&16711680)+(p[b+1]<<8&65280)+(p[b+2]&255),w.push(u(v));return w.join("")}function h(p){for(var m,y=p.length,v=y%3,w=[],b=16383,T=0,D=y-v;T<D;T+=b)w.push(f(p,T,T+b>D?D:T+b));return v===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),ofe=Xt(r=>{r.read=function(e,t,n,i,s){var o,a,d=s*8-i-1,l=(1<<d)-1,c=l>>1,u=-7,f=n?s-1:0,h=n?-1:1,p=e[t+f];for(f+=h,o=p&(1<<-u)-1,p>>=-u,u+=d;u>0;o=o*256+e[t+f],f+=h,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=i;u>0;a=a*256+e[t+f],f+=h,u-=8);if(o===0)o=1-c;else{if(o===l)return a?NaN:(p?-1:1)*(1/0);a=a+Math.pow(2,i),o=o-c}return(p?-1:1)*a*Math.pow(2,o-i)},r.write=function(e,t,n,i,s,o){var a,d,l,c=o*8-s-1,u=(1<<c)-1,f=u>>1,h=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=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?(d=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+f>=1?t+=h/l:t+=h*Math.pow(2,1-f),t*l>=2&&(a++,l/=2),a+f>=u?(d=0,a=u):a+f>=1?(d=(t*l-1)*Math.pow(2,s),a=a+f):(d=t*Math.pow(2,f-1)*Math.pow(2,s),a=0));s>=8;e[n+p]=d&255,p+=m,d/=256,s-=8);for(a=a<<s|d,c+=s;c>0;e[n+p]=a&255,p+=m,a/=256,c-=8);e[n+p-m]|=y*128}}),s5=Xt(r=>{"use strict";var e=ife(),t=ofe(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=a,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.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 s(){try{let k=new Uint8Array(1),U={foo:function(){return 42}};return Object.setPrototypeOf(U,Uint8Array.prototype),Object.setPrototypeOf(k,U),k.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(k){if(k>i)throw new RangeError('The value "'+k+'" is invalid for option "size"');let U=new Uint8Array(k);return Object.setPrototypeOf(U,a.prototype),U}function a(k,U,K){if(typeof k=="number"){if(typeof U=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(k)}return d(k,U,K)}a.poolSize=8192;function d(k,U,K){if(typeof k=="string")return f(k,U);if(ArrayBuffer.isView(k))return p(k);if(k==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k);if(Ye(k,ArrayBuffer)||k&&Ye(k.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ye(k,SharedArrayBuffer)||k&&Ye(k.buffer,SharedArrayBuffer)))return m(k,U,K);if(typeof k=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=k.valueOf&&k.valueOf();if(te!=null&&te!==k)return a.from(te,U,K);let de=y(k);if(de)return de;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof k[Symbol.toPrimitive]=="function")return a.from(k[Symbol.toPrimitive]("string"),U,K);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k)}a.from=function(k,U,K){return d(k,U,K)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(k){if(typeof k!="number")throw new TypeError('"size" argument must be of type number');if(k<0)throw new RangeError('The value "'+k+'" is invalid for option "size"')}function c(k,U,K){return l(k),k<=0?o(k):U!==void 0?typeof K=="string"?o(k).fill(U,K):o(k).fill(U):o(k)}a.alloc=function(k,U,K){return c(k,U,K)};function u(k){return l(k),o(k<0?0:v(k)|0)}a.allocUnsafe=function(k){return u(k)},a.allocUnsafeSlow=function(k){return u(k)};function f(k,U){if((typeof U!="string"||U==="")&&(U="utf8"),!a.isEncoding(U))throw new TypeError("Unknown encoding: "+U);let K=b(k,U)|0,te=o(K),de=te.write(k,U);return de!==K&&(te=te.slice(0,de)),te}function h(k){let U=k.length<0?0:v(k.length)|0,K=o(U);for(let te=0;te<U;te+=1)K[te]=k[te]&255;return K}function p(k){if(Ye(k,Uint8Array)){let U=new Uint8Array(k);return m(U.buffer,U.byteOffset,U.byteLength)}return h(k)}function m(k,U,K){if(U<0||k.byteLength<U)throw new RangeError('"offset" is outside of buffer bounds');if(k.byteLength<U+(K||0))throw new RangeError('"length" is outside of buffer bounds');let te;return U===void 0&&K===void 0?te=new Uint8Array(k):K===void 0?te=new Uint8Array(k,U):te=new Uint8Array(k,U,K),Object.setPrototypeOf(te,a.prototype),te}function y(k){if(a.isBuffer(k)){let U=v(k.length)|0,K=o(U);return K.length===0||k.copy(K,0,0,U),K}if(k.length!==void 0)return typeof k.length!="number"||ar(k.length)?o(0):h(k);if(k.type==="Buffer"&&Array.isArray(k.data))return h(k.data)}function v(k){if(k>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return k|0}function w(k){return+k!=k&&(k=0),a.alloc(+k)}a.isBuffer=function(k){return k!=null&&k._isBuffer===!0&&k!==a.prototype},a.compare=function(k,U){if(Ye(k,Uint8Array)&&(k=a.from(k,k.offset,k.byteLength)),Ye(U,Uint8Array)&&(U=a.from(U,U.offset,U.byteLength)),!a.isBuffer(k)||!a.isBuffer(U))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(k===U)return 0;let K=k.length,te=U.length;for(let de=0,ge=Math.min(K,te);de<ge;++de)if(k[de]!==U[de]){K=k[de],te=U[de];break}return K<te?-1:te<K?1:0},a.isEncoding=function(k){switch(String(k).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}},a.concat=function(k,U){if(!Array.isArray(k))throw new TypeError('"list" argument must be an Array of Buffers');if(k.length===0)return a.alloc(0);let K;if(U===void 0)for(U=0,K=0;K<k.length;++K)U+=k[K].length;let te=a.allocUnsafe(U),de=0;for(K=0;K<k.length;++K){let ge=k[K];if(Ye(ge,Uint8Array))de+ge.length>te.length?(a.isBuffer(ge)||(ge=a.from(ge)),ge.copy(te,de)):Uint8Array.prototype.set.call(te,ge,de);else if(a.isBuffer(ge))ge.copy(te,de);else throw new TypeError('"list" argument must be an Array of Buffers');de+=ge.length}return te};function b(k,U){if(a.isBuffer(k))return k.length;if(ArrayBuffer.isView(k)||Ye(k,ArrayBuffer))return k.byteLength;if(typeof k!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof k);let K=k.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&K===0)return 0;let de=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return K;case"utf8":case"utf-8":return Ae(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K*2;case"hex":return K>>>1;case"base64":return Lr(k).length;default:if(de)return te?-1:Ae(k).length;U=(""+U).toLowerCase(),de=!0}}a.byteLength=b;function T(k,U,K){let te=!1;if((U===void 0||U<0)&&(U=0),U>this.length||((K===void 0||K>this.length)&&(K=this.length),K<=0)||(K>>>=0,U>>>=0,K<=U))return"";for(k||(k="utf8");;)switch(k){case"hex":return S(this,U,K);case"utf8":case"utf-8":return R(this,U,K);case"ascii":return P(this,U,K);case"latin1":case"binary":return _(this,U,K);case"base64":return ee(this,U,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,U,K);default:if(te)throw new TypeError("Unknown encoding: "+k);k=(k+"").toLowerCase(),te=!0}}a.prototype._isBuffer=!0;function D(k,U,K){let te=k[U];k[U]=k[K],k[K]=te}a.prototype.swap16=function(){let k=this.length;if(k%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;U<k;U+=2)D(this,U,U+1);return this},a.prototype.swap32=function(){let k=this.length;if(k%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let U=0;U<k;U+=4)D(this,U,U+3),D(this,U+1,U+2);return this},a.prototype.swap64=function(){let k=this.length;if(k%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let U=0;U<k;U+=8)D(this,U,U+7),D(this,U+1,U+6),D(this,U+2,U+5),D(this,U+3,U+4);return this},a.prototype.toString=function(){let k=this.length;return k===0?"":arguments.length===0?R(this,0,k):T.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(k){if(!a.isBuffer(k))throw new TypeError("Argument must be a Buffer");return this===k?!0:a.compare(this,k)===0},a.prototype.inspect=function(){let k="",U=r.INSPECT_MAX_BYTES;return k=this.toString("hex",0,U).replace(/(.{2})/g,"$1 ").trim(),this.length>U&&(k+=" ... "),"<Buffer "+k+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(k,U,K,te,de){if(Ye(k,Uint8Array)&&(k=a.from(k,k.offset,k.byteLength)),!a.isBuffer(k))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof k);if(U===void 0&&(U=0),K===void 0&&(K=k?k.length:0),te===void 0&&(te=0),de===void 0&&(de=this.length),U<0||K>k.length||te<0||de>this.length)throw new RangeError("out of range index");if(te>=de&&U>=K)return 0;if(te>=de)return-1;if(U>=K)return 1;if(U>>>=0,K>>>=0,te>>>=0,de>>>=0,this===k)return 0;let ge=de-te,Ee=K-U,Wt=Math.min(ge,Ee),ci=this.slice(te,de),Vr=k.slice(U,K);for(let Dr=0;Dr<Wt;++Dr)if(ci[Dr]!==Vr[Dr]){ge=ci[Dr],Ee=Vr[Dr];break}return ge<Ee?-1:Ee<ge?1:0};function I(k,U,K,te,de){if(k.length===0)return-1;if(typeof K=="string"?(te=K,K=0):K>2147483647?K=2147483647:K<-2147483648&&(K=-2147483648),K=+K,ar(K)&&(K=de?0:k.length-1),K<0&&(K=k.length+K),K>=k.length){if(de)return-1;K=k.length-1}else if(K<0)if(de)K=0;else return-1;if(typeof U=="string"&&(U=a.from(U,te)),a.isBuffer(U))return U.length===0?-1:M(k,U,K,te,de);if(typeof U=="number")return U=U&255,typeof Uint8Array.prototype.indexOf=="function"?de?Uint8Array.prototype.indexOf.call(k,U,K):Uint8Array.prototype.lastIndexOf.call(k,U,K):M(k,[U],K,te,de);throw new TypeError("val must be string, number or Buffer")}function M(k,U,K,te,de){let ge=1,Ee=k.length,Wt=U.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(k.length<2||U.length<2)return-1;ge=2,Ee/=2,Wt/=2,K/=2}function ci(Dr,gr){return ge===1?Dr[gr]:Dr.readUInt16BE(gr*ge)}let Vr;if(de){let Dr=-1;for(Vr=K;Vr<Ee;Vr++)if(ci(k,Vr)===ci(U,Dr===-1?0:Vr-Dr)){if(Dr===-1&&(Dr=Vr),Vr-Dr+1===Wt)return Dr*ge}else Dr!==-1&&(Vr-=Vr-Dr),Dr=-1}else for(K+Wt>Ee&&(K=Ee-Wt),Vr=K;Vr>=0;Vr--){let Dr=!0;for(let gr=0;gr<Wt;gr++)if(ci(k,Vr+gr)!==ci(U,gr)){Dr=!1;break}if(Dr)return Vr}return-1}a.prototype.includes=function(k,U,K){return this.indexOf(k,U,K)!==-1},a.prototype.indexOf=function(k,U,K){return I(this,k,U,K,!0)},a.prototype.lastIndexOf=function(k,U,K){return I(this,k,U,K,!1)};function C(k,U,K,te){K=Number(K)||0;let de=k.length-K;te?(te=Number(te),te>de&&(te=de)):te=de;let ge=U.length;te>ge/2&&(te=ge/2);let Ee;for(Ee=0;Ee<te;++Ee){let Wt=parseInt(U.substr(Ee*2,2),16);if(ar(Wt))return Ee;k[K+Ee]=Wt}return Ee}function z(k,U,K,te){return ds(Ae(U,k.length-K),k,K,te)}function L(k,U,K,te){return ds(Ot(U),k,K,te)}function B(k,U,K,te){return ds(Lr(U),k,K,te)}function H(k,U,K,te){return ds(ai(U,k.length-K),k,K,te)}a.prototype.write=function(k,U,K,te){if(U===void 0)te="utf8",K=this.length,U=0;else if(K===void 0&&typeof U=="string")te=U,K=this.length,U=0;else if(isFinite(U))U=U>>>0,isFinite(K)?(K=K>>>0,te===void 0&&(te="utf8")):(te=K,K=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let de=this.length-U;if((K===void 0||K>de)&&(K=de),k.length>0&&(K<0||U<0)||U>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return C(this,k,U,K);case"utf8":case"utf-8":return z(this,k,U,K);case"ascii":case"latin1":case"binary":return L(this,k,U,K);case"base64":return B(this,k,U,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,k,U,K);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(k,U,K){return U===0&&K===k.length?e.fromByteArray(k):e.fromByteArray(k.slice(U,K))}function R(k,U,K){K=Math.min(k.length,K);let te=[],de=U;for(;de<K;){let ge=k[de],Ee=null,Wt=ge>239?4:ge>223?3:ge>191?2:1;if(de+Wt<=K){let ci,Vr,Dr,gr;switch(Wt){case 1:ge<128&&(Ee=ge);break;case 2:ci=k[de+1],(ci&192)===128&&(gr=(ge&31)<<6|ci&63,gr>127&&(Ee=gr));break;case 3:ci=k[de+1],Vr=k[de+2],(ci&192)===128&&(Vr&192)===128&&(gr=(ge&15)<<12|(ci&63)<<6|Vr&63,gr>2047&&(gr<55296||gr>57343)&&(Ee=gr));break;case 4:ci=k[de+1],Vr=k[de+2],Dr=k[de+3],(ci&192)===128&&(Vr&192)===128&&(Dr&192)===128&&(gr=(ge&15)<<18|(ci&63)<<12|(Vr&63)<<6|Dr&63,gr>65535&&gr<1114112&&(Ee=gr))}}Ee===null?(Ee=65533,Wt=1):Ee>65535&&(Ee-=65536,te.push(Ee>>>10&1023|55296),Ee=56320|Ee&1023),te.push(Ee),de+=Wt}return E(te)}var $=4096;function E(k){let U=k.length;if(U<=$)return String.fromCharCode.apply(String,k);let K="",te=0;for(;te<U;)K+=String.fromCharCode.apply(String,k.slice(te,te+=$));return K}function P(k,U,K){let te="";K=Math.min(k.length,K);for(let de=U;de<K;++de)te+=String.fromCharCode(k[de]&127);return te}function _(k,U,K){let te="";K=Math.min(k.length,K);for(let de=U;de<K;++de)te+=String.fromCharCode(k[de]);return te}function S(k,U,K){let te=k.length;(!U||U<0)&&(U=0),(!K||K<0||K>te)&&(K=te);let de="";for(let ge=U;ge<K;++ge)de+=qr[k[ge]];return de}function A(k,U,K){let te=k.slice(U,K),de="";for(let ge=0;ge<te.length-1;ge+=2)de+=String.fromCharCode(te[ge]+te[ge+1]*256);return de}a.prototype.slice=function(k,U){let K=this.length;k=~~k,U=U===void 0?K:~~U,k<0?(k+=K,k<0&&(k=0)):k>K&&(k=K),U<0?(U+=K,U<0&&(U=0)):U>K&&(U=K),U<k&&(U=k);let te=this.subarray(k,U);return Object.setPrototypeOf(te,a.prototype),te};function N(k,U,K){if(k%1!==0||k<0)throw new RangeError("offset is not uint");if(k+U>K)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k],de=1,ge=0;for(;++ge<U&&(de*=256);)te+=this[k+ge]*de;return te},a.prototype.readUintBE=a.prototype.readUIntBE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k+--U],de=1;for(;U>0&&(de*=256);)te+=this[k+--U]*de;return te},a.prototype.readUint8=a.prototype.readUInt8=function(k,U){return k=k>>>0,U||N(k,1,this.length),this[k]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(k,U){return k=k>>>0,U||N(k,2,this.length),this[k]|this[k+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(k,U){return k=k>>>0,U||N(k,2,this.length),this[k]<<8|this[k+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(k,U){return k=k>>>0,U||N(k,4,this.length),(this[k]|this[k+1]<<8|this[k+2]<<16)+this[k+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]*16777216+(this[k+1]<<16|this[k+2]<<8|this[k+3])},a.prototype.readBigUInt64LE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=U+this[++k]*2**8+this[++k]*2**16+this[++k]*2**24,de=this[++k]+this[++k]*2**8+this[++k]*2**16+K*2**24;return BigInt(te)+(BigInt(de)<<BigInt(32))}),a.prototype.readBigUInt64BE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=U*2**24+this[++k]*2**16+this[++k]*2**8+this[++k],de=this[++k]*2**24+this[++k]*2**16+this[++k]*2**8+K;return(BigInt(te)<<BigInt(32))+BigInt(de)}),a.prototype.readIntLE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k],de=1,ge=0;for(;++ge<U&&(de*=256);)te+=this[k+ge]*de;return de*=128,te>=de&&(te-=Math.pow(2,8*U)),te},a.prototype.readIntBE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=U,de=1,ge=this[k+--te];for(;te>0&&(de*=256);)ge+=this[k+--te]*de;return de*=128,ge>=de&&(ge-=Math.pow(2,8*U)),ge},a.prototype.readInt8=function(k,U){return k=k>>>0,U||N(k,1,this.length),this[k]&128?(255-this[k]+1)*-1:this[k]},a.prototype.readInt16LE=function(k,U){k=k>>>0,U||N(k,2,this.length);let K=this[k]|this[k+1]<<8;return K&32768?K|4294901760:K},a.prototype.readInt16BE=function(k,U){k=k>>>0,U||N(k,2,this.length);let K=this[k+1]|this[k]<<8;return K&32768?K|4294901760:K},a.prototype.readInt32LE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]|this[k+1]<<8|this[k+2]<<16|this[k+3]<<24},a.prototype.readInt32BE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]<<24|this[k+1]<<16|this[k+2]<<8|this[k+3]},a.prototype.readBigInt64LE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=this[k+4]+this[k+5]*2**8+this[k+6]*2**16+(K<<24);return(BigInt(te)<<BigInt(32))+BigInt(U+this[++k]*2**8+this[++k]*2**16+this[++k]*2**24)}),a.prototype.readBigInt64BE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=(U<<24)+this[++k]*2**16+this[++k]*2**8+this[++k];return(BigInt(te)<<BigInt(32))+BigInt(this[++k]*2**24+this[++k]*2**16+this[++k]*2**8+K)}),a.prototype.readFloatLE=function(k,U){return k=k>>>0,U||N(k,4,this.length),t.read(this,k,!0,23,4)},a.prototype.readFloatBE=function(k,U){return k=k>>>0,U||N(k,4,this.length),t.read(this,k,!1,23,4)},a.prototype.readDoubleLE=function(k,U){return k=k>>>0,U||N(k,8,this.length),t.read(this,k,!0,52,8)},a.prototype.readDoubleBE=function(k,U){return k=k>>>0,U||N(k,8,this.length),t.read(this,k,!1,52,8)};function q(k,U,K,te,de,ge){if(!a.isBuffer(k))throw new TypeError('"buffer" argument must be a Buffer instance');if(U>de||U<ge)throw new RangeError('"value" argument is out of bounds');if(K+te>k.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(k,U,K,te){if(k=+k,U=U>>>0,K=K>>>0,!te){let Ee=Math.pow(2,8*K)-1;q(this,k,U,K,Ee,0)}let de=1,ge=0;for(this[U]=k&255;++ge<K&&(de*=256);)this[U+ge]=k/de&255;return U+K},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(k,U,K,te){if(k=+k,U=U>>>0,K=K>>>0,!te){let Ee=Math.pow(2,8*K)-1;q(this,k,U,K,Ee,0)}let de=K-1,ge=1;for(this[U+de]=k&255;--de>=0&&(ge*=256);)this[U+de]=k/ge&255;return U+K},a.prototype.writeUint8=a.prototype.writeUInt8=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,1,255,0),this[U]=k&255,U+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,65535,0),this[U]=k&255,this[U+1]=k>>>8,U+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,65535,0),this[U]=k>>>8,this[U+1]=k&255,U+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,4294967295,0),this[U+3]=k>>>24,this[U+2]=k>>>16,this[U+1]=k>>>8,this[U]=k&255,U+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,4294967295,0),this[U]=k>>>24,this[U+1]=k>>>16,this[U+2]=k>>>8,this[U+3]=k&255,U+4};function W(k,U,K,te,de){le(U,te,de,k,K,7);let ge=Number(U&BigInt(4294967295));k[K++]=ge,ge=ge>>8,k[K++]=ge,ge=ge>>8,k[K++]=ge,ge=ge>>8,k[K++]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,K}function J(k,U,K,te,de){le(U,te,de,k,K,7);let ge=Number(U&BigInt(4294967295));k[K+7]=ge,ge=ge>>8,k[K+6]=ge,ge=ge>>8,k[K+5]=ge,ge=ge>>8,k[K+4]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return k[K+3]=Ee,Ee=Ee>>8,k[K+2]=Ee,Ee=Ee>>8,k[K+1]=Ee,Ee=Ee>>8,k[K]=Ee,K+8}a.prototype.writeBigUInt64LE=yr(function(k,U=0){return W(this,k,U,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=yr(function(k,U=0){return J(this,k,U,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(k,U,K,te){if(k=+k,U=U>>>0,!te){let Wt=Math.pow(2,8*K-1);q(this,k,U,K,Wt-1,-Wt)}let de=0,ge=1,Ee=0;for(this[U]=k&255;++de<K&&(ge*=256);)k<0&&Ee===0&&this[U+de-1]!==0&&(Ee=1),this[U+de]=(k/ge>>0)-Ee&255;return U+K},a.prototype.writeIntBE=function(k,U,K,te){if(k=+k,U=U>>>0,!te){let Wt=Math.pow(2,8*K-1);q(this,k,U,K,Wt-1,-Wt)}let de=K-1,ge=1,Ee=0;for(this[U+de]=k&255;--de>=0&&(ge*=256);)k<0&&Ee===0&&this[U+de+1]!==0&&(Ee=1),this[U+de]=(k/ge>>0)-Ee&255;return U+K},a.prototype.writeInt8=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,1,127,-128),k<0&&(k=255+k+1),this[U]=k&255,U+1},a.prototype.writeInt16LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,32767,-32768),this[U]=k&255,this[U+1]=k>>>8,U+2},a.prototype.writeInt16BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,32767,-32768),this[U]=k>>>8,this[U+1]=k&255,U+2},a.prototype.writeInt32LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,2147483647,-2147483648),this[U]=k&255,this[U+1]=k>>>8,this[U+2]=k>>>16,this[U+3]=k>>>24,U+4},a.prototype.writeInt32BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,2147483647,-2147483648),k<0&&(k=4294967295+k+1),this[U]=k>>>24,this[U+1]=k>>>16,this[U+2]=k>>>8,this[U+3]=k&255,U+4},a.prototype.writeBigInt64LE=yr(function(k,U=0){return W(this,k,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=yr(function(k,U=0){return J(this,k,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(k,U,K,te,de,ge){if(K+te>k.length)throw new RangeError("Index out of range");if(K<0)throw new RangeError("Index out of range")}function Y(k,U,K,te,de){return U=+U,K=K>>>0,de||V(k,U,K,4,34028234663852886e22,-34028234663852886e22),t.write(k,U,K,te,23,4),K+4}a.prototype.writeFloatLE=function(k,U,K){return Y(this,k,U,!0,K)},a.prototype.writeFloatBE=function(k,U,K){return Y(this,k,U,!1,K)};function F(k,U,K,te,de){return U=+U,K=K>>>0,de||V(k,U,K,8,17976931348623157e292,-17976931348623157e292),t.write(k,U,K,te,52,8),K+8}a.prototype.writeDoubleLE=function(k,U,K){return F(this,k,U,!0,K)},a.prototype.writeDoubleBE=function(k,U,K){return F(this,k,U,!1,K)},a.prototype.copy=function(k,U,K,te){if(!a.isBuffer(k))throw new TypeError("argument should be a Buffer");if(K||(K=0),!te&&te!==0&&(te=this.length),U>=k.length&&(U=k.length),U||(U=0),te>0&&te<K&&(te=K),te===K||k.length===0||this.length===0)return 0;if(U<0)throw new RangeError("targetStart out of bounds");if(K<0||K>=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),k.length-U<te-K&&(te=k.length-U+K);let de=te-K;return this===k&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(U,K,te):Uint8Array.prototype.set.call(k,this.subarray(K,te),U),de},a.prototype.fill=function(k,U,K,te){if(typeof k=="string"){if(typeof U=="string"?(te=U,U=0,K=this.length):typeof K=="string"&&(te=K,K=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!a.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(k.length===1){let ge=k.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(k=ge)}}else typeof k=="number"?k=k&255:typeof k=="boolean"&&(k=Number(k));if(U<0||this.length<U||this.length<K)throw new RangeError("Out of range index");if(K<=U)return this;U=U>>>0,K=K===void 0?this.length:K>>>0,k||(k=0);let de;if(typeof k=="number")for(de=U;de<K;++de)this[de]=k;else{let ge=a.isBuffer(k)?k:a.from(k,te),Ee=ge.length;if(Ee===0)throw new TypeError('The value "'+k+'" is invalid for argument "value"');for(de=0;de<K-U;++de)this[de+U]=ge[de%Ee]}return this};var Q={};function ie(k,U,K){Q[k]=class extends K{constructor(){super(),Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${k}]`,this.stack,delete this.name}get code(){return k}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${k}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(k){return k?`${k} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(k,U){return`The "${k}" argument must be of type number. Received type ${typeof U}`},TypeError),ie("ERR_OUT_OF_RANGE",function(k,U,K){let te=`The value of "${k}" is out of range.`,de=K;return Number.isInteger(K)&&Math.abs(K)>2**32?de=oe(String(K)):typeof K=="bigint"&&(de=String(K),(K>BigInt(2)**BigInt(32)||K<-(BigInt(2)**BigInt(32)))&&(de=oe(de)),de+="n"),te+=` It must be ${U}. Received ${de}`,te},RangeError);function oe(k){let U="",K=k.length,te=k[0]==="-"?1:0;for(;K>=te+4;K-=3)U=`_${k.slice(K-3,K)}${U}`;return`${k.slice(0,K)}${U}`}function Z(k,U,K){he(U,"offset"),(k[U]===void 0||k[U+K]===void 0)&&ue(U,k.length-(K+1))}function le(k,U,K,te,de,ge){if(k>K||k<U){let Ee=typeof U=="bigint"?"n":"",Wt;throw ge>3?U===0||U===BigInt(0)?Wt=`>= 0${Ee} and < 2${Ee} ** ${(ge+1)*8}${Ee}`:Wt=`>= -(2${Ee} ** ${(ge+1)*8-1}${Ee}) and < 2 ** ${(ge+1)*8-1}${Ee}`:Wt=`>= ${U}${Ee} and <= ${K}${Ee}`,new Q.ERR_OUT_OF_RANGE("value",Wt,k)}Z(te,de,ge)}function he(k,U){if(typeof k!="number")throw new Q.ERR_INVALID_ARG_TYPE(U,"number",k)}function ue(k,U,K){throw Math.floor(k)!==k?(he(k,K),new Q.ERR_OUT_OF_RANGE(K||"offset","an integer",k)):U<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(K||"offset",`>= ${K?1:0} and <= ${U}`,k)}var Se=/[^+/0-9A-Za-z-_]/g;function pe(k){if(k=k.split("=")[0],k=k.trim().replace(Se,""),k.length<2)return"";for(;k.length%4!==0;)k=k+"=";return k}function Ae(k,U){U=U||1/0;let K,te=k.length,de=null,ge=[];for(let Ee=0;Ee<te;++Ee){if(K=k.charCodeAt(Ee),K>55295&&K<57344){if(!de){if(K>56319){(U-=3)>-1&&ge.push(239,191,189);continue}else if(Ee+1===te){(U-=3)>-1&&ge.push(239,191,189);continue}de=K;continue}if(K<56320){(U-=3)>-1&&ge.push(239,191,189),de=K;continue}K=(de-55296<<10|K-56320)+65536}else de&&(U-=3)>-1&&ge.push(239,191,189);if(de=null,K<128){if((U-=1)<0)break;ge.push(K)}else if(K<2048){if((U-=2)<0)break;ge.push(K>>6|192,K&63|128)}else if(K<65536){if((U-=3)<0)break;ge.push(K>>12|224,K>>6&63|128,K&63|128)}else if(K<1114112){if((U-=4)<0)break;ge.push(K>>18|240,K>>12&63|128,K>>6&63|128,K&63|128)}else throw new Error("Invalid code point")}return ge}function Ot(k){let U=[];for(let K=0;K<k.length;++K)U.push(k.charCodeAt(K)&255);return U}function ai(k,U){let K,te,de,ge=[];for(let Ee=0;Ee<k.length&&!((U-=2)<0);++Ee)K=k.charCodeAt(Ee),te=K>>8,de=K%256,ge.push(de),ge.push(te);return ge}function Lr(k){return e.toByteArray(pe(k))}function ds(k,U,K,te){let de;for(de=0;de<te&&!(de+K>=U.length||de>=k.length);++de)U[de+K]=k[de];return de}function Ye(k,U){return k instanceof U||k!=null&&k.constructor!=null&&k.constructor.name!=null&&k.constructor.name===U.name}function ar(k){return k!==k}var qr=function(){let k="0123456789abcdef",U=new Array(256);for(let K=0;K<16;++K){let te=K*16;for(let de=0;de<16;++de)U[te+de]=k[K]+k[de]}return U}();function yr(k){return typeof BigInt>"u"?Gt:k}function Gt(){throw new Error("BigInt not supported")}}),nF=Xt((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),iF=Xt(r=>{"use strict";var e=il(),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}),oF=Xt(r=>{"use strict";var{Buffer:e}=s5()||{},{Encoding:t}=iF(),n=nF(),i=class extends t{constructor(a){super({...a,format:"buffer"})}createViewTranscoder(){return new s({encode:this.encode,decode:a=>this.decode(e.from(a.buffer,a.byteOffset,a.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},s=class extends t{constructor(a){super({...a,format:"view"})}createBufferTranscoder(){return new i({encode:a=>{let d=this.encode(a);return e.from(d.buffer,d.byteOffset,d.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends t{constructor(a){super({...a,format:"utf8"})}createBufferTranscoder(){return new i({encode:a=>e.from(this.encode(a),"utf8"),decode:a=>this.decode(a.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:a,textDecoder:d}=n();return new s({encode:l=>a.encode(this.encode(l)),decode:l=>this.decode(d.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=s,r.UTF8Format=o}),sfe=Xt(r=>{"use strict";var{Buffer:e}=s5()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=nF()(),{BufferFormat:i,ViewFormat:s,UTF8Format:o}=oF(),a=d=>d;r.utf8=new o({encode:function(d){return e.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?n.decode(d):String(d)},decode:a,name:"utf8",createViewTranscoder(){return new s({encode:function(d){return ArrayBuffer.isView(d)?d:t.encode(d)},decode:function(d){return n.decode(d)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:function(d){return d.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:a,name:"buffer",createViewTranscoder(){return new s({encode:function(d){return ArrayBuffer.isView(d)?d:e.from(String(d),"utf8")},decode:function(d){return e.from(d.buffer,d.byteOffset,d.byteLength)},name:`${this.name}+view`})}}),r.view=new s({encode:function(d){return ArrayBuffer.isView(d)?d:t.encode(d)},decode:a,name:"view",createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:a,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"hex")},decode:function(d){return d.toString("hex")},name:"hex"}),r.base64=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"base64")},decode:function(d){return d.toString("base64")},name:"base64"})}),afe=Xt(r=>{"use strict";var e=il(),t=sfe(),{Encoding:n}=iF(),{BufferFormat:i,ViewFormat:s,UTF8Format:o}=oF(),a=Symbol("formats"),d=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),c=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[d]=new Map,this[a]=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[d].values()))}encoding(y){let v=this[d].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=p[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:b}=v;if(!this[a].has(b))if(this[a].has("view"))v=v.createViewTranscoder();else if(this[a].has("buffer"))v=v.createBufferTranscoder();else if(this[a].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let T of[y,w,v.name,v.commonName])this[d].set(T,v)}return v}};r.Transcoder=c;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 s({...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 h={binary:t.buffer,"utf-8":t.utf8},p={...t,...h},m=0}),cfe=Xt((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 s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,f||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function d(){this._events=new i,this._eventsCount=0}d.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)t.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},d.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,h=u.length,p=new Array(h);f<h;f++)p[f]=u[f].fn;return p},d.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},d.prototype.emit=function(l,c,u,f,h,p){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,b;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,c),!0;case 3:return y.fn.call(y.context,c,u),!0;case 4:return y.fn.call(y.context,c,u,f),!0;case 5:return y.fn.call(y.context,c,u,f,h),!0;case 6:return y.fn.call(y.context,c,u,f,h,p),!0}for(b=1,w=new Array(v-1);b<v;b++)w[b-1]=arguments[b];y.fn.apply(y.context,w)}else{var T=y.length,D;for(b=0;b<T;b++)switch(y[b].once&&this.removeListener(l,y[b].fn,void 0,!0),v){case 1:y[b].fn.call(y[b].context);break;case 2:y[b].fn.call(y[b].context,c);break;case 3:y[b].fn.call(y[b].context,c,u);break;case 4:y[b].fn.call(y[b].context,c,u,f);break;default:if(!w)for(D=1,w=new Array(v-1);D<v;D++)w[D-1]=arguments[D];y[b].fn.apply(y[b].context,w)}}return!0},d.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},d.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},d.prototype.removeListener=function(l,c,u,f){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return a(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!f||p.once)&&(!u||p.context===u)&&a(this,h);else{for(var m=0,y=[],v=p.length;m<v;m++)(p[m].fn!==c||f&&!p[m].once||u&&p[m].context!==u)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:a(this,h)}return this},d.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)}),dfe=Xt((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),fE=Xt(r=>{"use strict";var e=dfe();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(s,o){t=function(a,d){a?o(a):s(d)}});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))})}}),a5=Xt(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:{}}}),Wp=Xt(r=>{"use strict";var{fromCallback:e}=fE(),t=il(),{getOptions:n,getCallback:i}=a5(),s=Symbol("promise"),o=Symbol("callback"),a=Symbol("working"),d=Symbol("handleOne"),l=Symbol("handleMany"),c=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),b=Symbol("abortOnClose"),T=Symbol("legacy"),D=Symbol("keys"),I=Symbol("values"),M=Symbol("limit"),C=Symbol("count"),z=Object.freeze({}),L=()=>{},B=!1,H=class{constructor(P,_,S){if(typeof P!="object"||P===null){let A=P===null?"null":typeof P;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof _!="object"||_===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[a]=!1,this[h]=!1,this[c]=!1,this[o]=null,this[d]=this[d].bind(this),this[l]=this[l].bind(this),this[p]=this[p].bind(this),this[v]=_[v],this[w]=_[w],this[T]=S,this[M]=Number.isInteger(_.limit)&&_.limit>=0?_.limit:1/0,this[C]=0,this[b]=!!_.abortOnClose,this.db=P,this.db.attachResource(this),this.nextTick=P.nextTick}get count(){return this[C]}get limit(){return this[M]}next(P){let _;if(P===void 0)_=new Promise((S,A)=>{P=(N,q,W)=>{N?A(N):this[T]?q===void 0&&W===void 0?S():S([q,W]):S(q)}});else if(typeof P!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(P,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(P,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[a]=!0,this[o]=P,this[C]>=this[M]?this.nextTick(this[d],null):this._next(this[d])),_}_next(P){this.nextTick(P)}nextv(P,_,S){return S=i(_,S),S=e(S,s),_=n(_,z),Number.isInteger(P)?(this[h]?this.nextTick(S,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(S,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(P<1&&(P=1),this[M]<1/0&&(P=Math.min(P,this[M]-this[C])),this[a]=!0,this[o]=S,P<=0?this.nextTick(this[l],null,[]):this._nextv(P,_,this[l])),S[s]):(this.nextTick(S,new TypeError("The first argument 'size' must be an integer")),S[s])}_nextv(P,_,S){let A=[],N=(q,W,J)=>{if(q)return S(q);if(this[T]?W===void 0&&J===void 0:W===void 0)return S(null,A);A.push(this[T]?[W,J]:W),A.length===P?S(null,A):this._next(N)};this._next(N)}all(P,_){return _=i(P,_),_=e(_,s),P=n(P,z),this[h]?this.nextTick(_,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(_,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[a]=!0,this[o]=_,this[c]=!0,this[C]>=this[M]?this.nextTick(this[l],null,[]):this._all(P,this[l])),_[s]}_all(P,_){let S=this[C],A=[],N=()=>{let W=this[M]<1/0?Math.min(1e3,this[M]-S):1e3;W<=0?this.nextTick(_,null,A):this._nextv(W,z,q)},q=(W,J)=>{W?_(W):J.length===0?_(null,A):(A.push.apply(A,J),S+=J.length,N())};N()}[u](){let P=this[o];return this[b]&&P===null?L:(this[a]=!1,this[o]=null,this[h]&&this._close(this[p]),P)}[f](P,_,S){this[c]?this.close(P.bind(null,_,S)):P(_,S)}seek(P,_){if(_=n(_,z),!this[h]){if(this[a])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let S=this.db.keyEncoding(_.keyEncoding||this[v]),A=S.format;_.keyEncoding!==A&&(_={..._,keyEncoding:A});let N=this.db.prefixKey(S.encode(P),A);this._seek(N,_)}}}_seek(P,_){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(P){return P=e(P,s),this[m]?this.nextTick(P):this[h]?this[y].push(P):(this[h]=!0,this[y].push(P),this[a]?this[b]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),P[s]}_close(P){this.nextTick(P)}[p](){this[m]=!0,this.db.detachResource(this);let P=this[y];this[y]=[];for(let _ of P)_()}async*[Symbol.asyncIterator](){try{let P;for(;(P=await this.next())!==void 0;)yield P}finally{this[m]||await this.close()}}},ee=class extends H{constructor(P,_){super(P,_,!0),this[D]=_.keys!==!1,this[I]=_.values!==!1}[d](P,_,S){let A=this[u]();if(P)return A(P);try{_=this[D]&&_!==void 0?this[v].decode(_):void 0,S=this[I]&&S!==void 0?this[w].decode(S):void 0}catch(N){return A(new E("entry",N))}_===void 0&&S===void 0||this[C]++,A(null,_,S)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A of _){let N=A[0],q=A[1];A[0]=this[D]&&N!==void 0?this[v].decode(N):void 0,A[1]=this[I]&&q!==void 0?this[w].decode(q):void 0}}catch(A){return this[f](S,new E("entries",A))}this[C]+=_.length,this[f](S,null,_)}end(P){return!B&&typeof console<"u"&&(B=!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(P)}},R=class extends H{constructor(P,_){super(P,_,!1)}[d](P,_){let S=this[u]();if(P)return S(P);try{_=_!==void 0?this[v].decode(_):void 0}catch(A){return S(new E("key",A))}_!==void 0&&this[C]++,S(null,_)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A=0;A<_.length;A++){let N=_[A];_[A]=N!==void 0?this[v].decode(N):void 0}}catch(A){return this[f](S,new E("keys",A))}this[C]+=_.length,this[f](S,null,_)}},$=class extends H{constructor(P,_){super(P,_,!1)}[d](P,_){let S=this[u]();if(P)return S(P);try{_=_!==void 0?this[w].decode(_):void 0}catch(A){return S(new E("value",A))}_!==void 0&&this[C]++,S(null,_)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A=0;A<_.length;A++){let N=_[A];_[A]=N!==void 0?this[w].decode(N):void 0}}catch(A){return this[f](S,new E("values",A))}this[C]+=_.length,this[f](S,null,_)}},E=class extends t{constructor(P,_){super(`Iterator could not decode ${P}`,{code:"LEVEL_DECODE_ERROR",cause:_})}};for(let P of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,P.split(" ")[0],{get(){throw new t(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=v,ee.valueEncoding=w,r.AbstractIterator=ee,r.AbstractKeyIterator=R,r.AbstractValueIterator=$}),lfe=Xt(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=Wp(),n=Symbol("iterator"),i=Symbol("callback"),s=Symbol("handleOne"),o=Symbol("handleMany"),a=class extends e{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!0,values:!1}),this[s]=this[s].bind(this),this[o]=this[o].bind(this)}},d=class extends t{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!1,values:!0}),this[s]=this[s].bind(this),this[o]=this[o].bind(this)}};for(let l of[a,d]){let c=l===a,u=c?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[s])},l.prototype[s]=function(f,h,p){let m=this[i];f?m(f):m(null,c?h:p)},l.prototype._nextv=function(f,h,p){this[i]=p,this[n].nextv(f,h,this[o])},l.prototype._all=function(f,h){this[i]=h,this[n].all(f,this[o])},l.prototype[o]=function(f,h){let p=this[i];f?p(f):p(null,h.map(u))},l.prototype._seek=function(f,h){this[n].seek(f,h)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=a,r.DefaultValueIterator=d}),ufe=Xt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=Wp(),i=il(),s=Symbol("nut"),o=Symbol("undefer"),a=Symbol("factory"),d=class extends e{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.iterator(f),this.db.defer(()=>this[o]())}},l=class extends t{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.keys(f),this.db.defer(()=>this[o]())}},c=class extends n{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.values(f),this.db.defer(()=>this[o]())}};for(let u of[d,l,c])u.prototype[o]=function(){this.db.status==="open"&&(this[s]=this[a]())},u.prototype._next=function(f){this[s]!==null?this[s].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,h,p){this[s]!==null?this[s].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,h){this[s]!==null?this[s].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,h){this[s]!==null?this[s]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},u.prototype._close=function(f){this[s]!==null?this[s].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=d,r.DeferredKeyIterator=l,r.DeferredValueIterator=c}),sF=Xt(r=>{"use strict";var{fromCallback:e}=fE(),t=il(),{getCallback:n,getOptions:i}=a5(),s=Symbol("promise"),o=Symbol("status"),a=Symbol("operations"),d=Symbol("finishClose"),l=Symbol("closeCallbacks"),c=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[a]=[],this[l]=[],this[o]="open",this[d]=this[d].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[a].length}put(u,f,h){if(this[o]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,v=m.keyEncoding(h&&h.keyEncoding),w=m.valueEncoding(h&&h.valueEncoding),b=v.format;h={...h,keyEncoding:b,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let T=m.prefixKey(v.encode(u),b),D=w.encode(f);return this._put(T,D,h),this[a].push({...y,type:"put",key:u,value:f}),this}_put(u,f,h){}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 h=this.db._checkKey(u);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(u),v),f),this[a].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[a]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,s),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,h=>{this[o]="closing",this[l].push(()=>f(h)),h||this.db.emit("batch",this[a]),this._close(this[d])})),f[s]}_write(u,f){}close(u){return u=e(u,s),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[d]))),u[s]}_close(u){this.nextTick(u)}[d](){this[o]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=c}),ffe=Xt(r=>{"use strict";var{AbstractChainedBatch:e}=sF(),t=il(),n=Symbol("encoded"),i=class extends e{constructor(s){super(s),this[n]=[]}_put(s,o,a){this[n].push({...a,type:"put",key:s,value:o})}_del(s,o){this[n].push({...o,type:"del",key:s})}_clear(){this[n]=[]}_write(s,o){this.db.status==="opening"?this.db.defer(()=>this._write(s,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],s,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}),hfe=Xt((r,e)=>{"use strict";var t=il(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(s,o){let a={};for(let d in s)if(n.call(s,d)&&!(d==="keyEncoding"||d==="valueEncoding")){if(d==="start"||d==="end")throw new t(`The legacy range option '${d}' has been removed`,{code:"LEVEL_LEGACY"});if(d==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(d)?a[d]=o.encode(s[d]):a[d]=s[d]}return a.reverse=!!a.reverse,a.limit=Number.isInteger(a.limit)&&a.limit>=0?a.limit:-1,a}}),aF=Xt((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))}),pfe=Xt((r,e)=>{"use strict";var t=aF();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),mfe=Xt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=Wp(),i=Symbol("unfix"),s=Symbol("iterator"),o=Symbol("handleOne"),a=Symbol("handleMany"),d=Symbol("callback"),l=class extends e{constructor(f,h,p,m){super(f,h),this[s]=p,this[i]=m,this[o]=this[o].bind(this),this[a]=this[a].bind(this),this[d]=null}[o](f,h,p){let m=this[d];if(f)return m(f);h!==void 0&&(h=this[i](h)),m(f,h,p)}[a](f,h){let p=this[d];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[i](y))}p(f,h)}},c=class extends t{constructor(f,h,p,m){super(f,h),this[s]=p,this[i]=m,this[o]=this[o].bind(this),this[a]=this[a].bind(this),this[d]=null}[o](f,h){let p=this[d];if(f)return p(f);h!==void 0&&(h=this[i](h)),p(f,h)}[a](f,h){let p=this[d];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[i](y))}p(f,h)}},u=class extends n{constructor(f,h,p){super(f,h),this[s]=p}};for(let f of[l,c])f.prototype._next=function(h){this[d]=h,this[s].next(this[o])},f.prototype._nextv=function(h,p,m){this[d]=m,this[s].nextv(h,p,this[a])},f.prototype._all=function(h,p){this[d]=p,this[s].all(h,this[a])};for(let f of[u])f.prototype._next=function(h){this[s].next(h)},f.prototype._nextv=function(h,p,m){this[s].nextv(h,p,m)},f.prototype._all=function(h,p){this[s].all(h,p)};for(let f of[l,c,u])f.prototype._seek=function(h,p){this[s].seek(h,p)},f.prototype._close=function(h){this[s].close(h)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=c,r.AbstractSublevelValueIterator=u}),yfe=Xt((r,e)=>{"use strict";var t=il(),{Buffer:n}=s5()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:s,AbstractSublevelValueIterator:o}=mfe(),a=Symbol("prefix"),d=Symbol("upperBound"),l=Symbol("prefixRange"),c=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:b}){class T extends b{static defaults(I){if(typeof I=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(I&&I.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return I==null?h:I.separator?I:{...I,separator:"!"}}constructor(I,M,C){let{separator:z,manifest:L,...B}=T.defaults(C);M=w(M,z);let H=z.charCodeAt(0)+1,ee=I[c]||I;if(!f.encode(M).every(E=>E>H&&E<127))throw new t(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,L),B);let R=(I.prefix||"")+z+M+z,$=R.slice(0,-1)+String.fromCharCode(H);this[c]=ee,this[a]=new y(R),this[d]=new y($),this[u]=new v,this.nextTick=ee.nextTick}prefixKey(I,M){if(M==="utf8")return this[a].utf8+I;if(I.byteLength===0)return this[a][M];if(M==="view"){let C=this[a].view,z=new Uint8Array(C.byteLength+I.byteLength);return z.set(C,0),z.set(I,C.byteLength),z}else{let C=this[a].buffer;return n.concat([C,I],C.byteLength+I.byteLength)}}[l](I,M){I.gte!==void 0?I.gte=this.prefixKey(I.gte,M):I.gt!==void 0?I.gt=this.prefixKey(I.gt,M):I.gte=this[a][M],I.lte!==void 0?I.lte=this.prefixKey(I.lte,M):I.lt!==void 0?I.lt=this.prefixKey(I.lt,M):I.lte=this[d][M]}get prefix(){return this[a].utf8}get db(){return this[c]}_open(I,M){this[c].open({passive:!0},M)}_put(I,M,C,z){this[c].put(I,M,C,z)}_get(I,M,C){this[c].get(I,M,C)}_getMany(I,M,C){this[c].getMany(I,M,C)}_del(I,M,C){this[c].del(I,M,C)}_batch(I,M,C){this[c].batch(I,M,C)}_clear(I,M){this[l](I,I.keyEncoding),this[c].clear(I,M)}_iterator(I){this[l](I,I.keyEncoding);let M=this[c].iterator(I),C=this[u].get(this[a].utf8.length,I.keyEncoding);return new i(this,I,M,C)}_keys(I){this[l](I,I.keyEncoding);let M=this[c].keys(I),C=this[u].get(this[a].utf8.length,I.keyEncoding);return new s(this,I,M,C)}_values(I){this[l](I,I.keyEncoding);let M=this[c].values(I);return new o(this,I,M)}}return{AbstractSublevel:T}};var p=function(b,T){return{...b.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...T,encodings:{utf8:m(b,"utf8"),buffer:m(b,"buffer"),view:m(b,"view")}}},m=function(b,T){return b.supports.encodings[T]?b.keyEncoding(T).name===T:!1},y=class{constructor(b){this.utf8=b,this.view=f.encode(b),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(b,T){let D=this.cache.get(T);return D===void 0&&(T==="view"?D=(function(I,M){return M.subarray(I)}).bind(null,b):D=(function(I,M){return M.slice(I)}).bind(null,b),this.cache.set(T,D)),D}},w=function(b,T){let D=0,I=b.length;for(;D<I&&b[D]===T;)D++;for(;I>D&&b[I-1]===T;)I--;return b.slice(D,I)}}),Uz=Xt(r=>{"use strict";var{supports:e}=nfe(),{Transcoder:t}=afe(),{EventEmitter:n}=cfe(),{fromCallback:i}=fE(),s=il(),{AbstractIterator:o}=Wp(),{DefaultKeyIterator:a,DefaultValueIterator:d}=lfe(),{DeferredIterator:l,DeferredKeyIterator:c,DeferredValueIterator:u}=ufe(),{DefaultChainedBatch:f}=ffe(),{getCallback:h,getOptions:p}=a5(),m=hfe(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),b=Symbol("closeResources"),T=Symbol("operations"),D=Symbol("undefer"),I=Symbol("deferOpen"),M=Symbol("options"),C=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),B=Symbol("keyEncoding"),H=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(_,S){if(super(),typeof _!="object"||_===null)throw new TypeError("The first argument 'manifest' must be an object");S=p(S);let{keyEncoding:A,valueEncoding:N,passive:q,...W}=S;this[w]=new Set,this[T]=[],this[I]=!0,this[M]=W,this[C]="opening",this.supports=e(_,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:_.snapshots!==!1,permanence:_.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:_.encodings||{},events:Object.assign({},_.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(P(this)),this[B]=this[L].encoding(A||"utf8"),this[H]=this[L].encoding(N||"utf8");for(let J of this[L].encodings())this.supports.encodings[J.commonName]||(this.supports.encodings[J.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[H].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[I]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(_){return this[L].encoding(_??this[B])}valueEncoding(_){return this[L].encoding(_??this[H])}open(_,S){S=h(_,S),S=i(S,y),_={...this[M],...p(_)},_.createIfMissing=_.createIfMissing!==!1,_.errorIfExists=!!_.errorIfExists;let A=N=>{this[C]==="closing"||this[C]==="opening"?this.once(v,N?()=>A(N):A):this[C]!=="open"?S(new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:N})):S()};return _.passive?this[C]==="opening"?this.once(v,A):this.nextTick(A):this[C]==="closed"||this[I]?(this[I]=!1,this[C]="opening",this.emit("opening"),this._open(_,N=>{if(N){this[C]="closed",this[b](()=>{this.emit(v),A(N)}),this[D]();return}this[C]="open",this[D](),this.emit(v),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),A()})):this[C]==="open"?this.nextTick(A):this.once(v,()=>this.open(_,S)),S[y]}_open(_,S){this.nextTick(S)}close(_){_=i(_,y);let S=A=>{this[C]==="opening"||this[C]==="closing"?this.once(v,A?S(A):S):this[C]!=="closed"?_(new s("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):_()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let A=N=>{this[C]="open",this[D](),this.emit(v),S(N)};this[b](()=>{this._close(N=>{if(N)return A(N);this[C]="closed",this[D](),this.emit(v),this[C]==="closed"&&this.emit("closed"),S()})})}else this[C]==="closed"?this.nextTick(S):this.once(v,()=>this.close(_));return _[y]}[b](_){if(this[w].size===0)return this.nextTick(_);let S=this[w].size,A=!0,N=()=>{--S===0&&(A?this.nextTick(_):_())};for(let q of this[w])q.close(N);A=!1,this[w].clear()}_close(_){this.nextTick(_)}get(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].entry),this[C]==="opening")return this.defer(()=>this.get(_,S,A)),A[y];if(E(this,A))return A[y];let N=this._checkKey(_);if(N)return this.nextTick(A,N),A[y];let q=this.keyEncoding(S.keyEncoding),W=this.valueEncoding(S.valueEncoding),J=q.format,V=W.format;return(S.keyEncoding!==J||S.valueEncoding!==V)&&(S=Object.assign({},S,{keyEncoding:J,valueEncoding:V})),this._get(this.prefixKey(q.encode(_),J),S,(Y,F)=>{if(Y)return(Y.code==="LEVEL_NOT_FOUND"||Y.notFound||/NotFound/i.test(Y))&&(Y.code||(Y.code="LEVEL_NOT_FOUND"),Y.notFound||(Y.notFound=!0),Y.status||(Y.status=404)),A(Y);try{F=W.decode(F)}catch(Q){return A(new s("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,F)}),A[y]}_get(_,S,A){this.nextTick(A,new Error("NotFound"))}getMany(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].entry),this[C]==="opening")return this.defer(()=>this.getMany(_,S,A)),A[y];if(E(this,A))return A[y];if(!Array.isArray(_))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(_.length===0)return this.nextTick(A,null,[]),A[y];let N=this.keyEncoding(S.keyEncoding),q=this.valueEncoding(S.valueEncoding),W=N.format,J=q.format;(S.keyEncoding!==W||S.valueEncoding!==J)&&(S=Object.assign({},S,{keyEncoding:W,valueEncoding:J}));let V=new Array(_.length);for(let Y=0;Y<_.length;Y++){let F=_[Y],Q=this._checkKey(F);if(Q)return this.nextTick(A,Q),A[y];V[Y]=this.prefixKey(N.encode(F),W)}return this._getMany(V,S,(Y,F)=>{if(Y)return A(Y);try{for(let Q=0;Q<F.length;Q++)F[Q]!==void 0&&(F[Q]=q.decode(F[Q]))}catch(Q){return A(new s(`Could not decode one or more of ${F.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,F)}),A[y]}_getMany(_,S,A){this.nextTick(A,null,new Array(_.length).fill(void 0))}put(_,S,A,N){if(N=h(A,N),N=i(N,y),A=p(A,this[z].entry),this[C]==="opening")return this.defer(()=>this.put(_,S,A,N)),N[y];if(E(this,N))return N[y];let q=this._checkKey(_)||this._checkValue(S);if(q)return this.nextTick(N,q),N[y];let W=this.keyEncoding(A.keyEncoding),J=this.valueEncoding(A.valueEncoding),V=W.format,Y=J.format;(A.keyEncoding!==V||A.valueEncoding!==Y)&&(A=Object.assign({},A,{keyEncoding:V,valueEncoding:Y}));let F=this.prefixKey(W.encode(_),V),Q=J.encode(S);return this._put(F,Q,A,ie=>{if(ie)return N(ie);this.emit("put",_,S),N()}),N[y]}_put(_,S,A,N){this.nextTick(N)}del(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].key),this[C]==="opening")return this.defer(()=>this.del(_,S,A)),A[y];if(E(this,A))return A[y];let N=this._checkKey(_);if(N)return this.nextTick(A,N),A[y];let q=this.keyEncoding(S.keyEncoding),W=q.format;return S.keyEncoding!==W&&(S=Object.assign({},S,{keyEncoding:W})),this._del(this.prefixKey(q.encode(_),W),S,J=>{if(J)return A(J);this.emit("del",_),A()}),A[y]}_del(_,S,A){this.nextTick(A)}batch(_,S,A){if(!arguments.length){if(this[C]==="opening")return new f(this);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof _=="function"?A=_:A=h(S,A),A=i(A,y),S=p(S,this[z].empty),this[C]==="opening")return this.defer(()=>this.batch(_,S,A)),A[y];if(E(this,A))return A[y];if(!Array.isArray(_))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(_.length===0)return this.nextTick(A),A[y];let N=new Array(_.length),{keyEncoding:q,valueEncoding:W,...J}=S;for(let V=0;V<_.length;V++){if(typeof _[V]!="object"||_[V]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let Y=Object.assign({},_[V]);if(Y.type!=="put"&&Y.type!=="del")return this.nextTick(A,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),A[y];let F=this._checkKey(Y.key);if(F)return this.nextTick(A,F),A[y];let Q=Y.sublevel!=null?Y.sublevel:this,ie=Q.keyEncoding(Y.keyEncoding||q),oe=ie.format;if(Y.key=Q.prefixKey(ie.encode(Y.key),oe),Y.keyEncoding=oe,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(A,Z),A[y];let le=Q.valueEncoding(Y.valueEncoding||W);Y.value=le.encode(Y.value),Y.valueEncoding=le.format}Q!==this&&(Y.sublevel=null),N[V]=Y}return this._batch(N,J,V=>{if(V)return A(V);this.emit("batch",_),A()}),A[y]}_batch(_,S,A){this.nextTick(A)}sublevel(_,S){return this._sublevel(_,$.defaults(S))}_sublevel(_,S){return new $(this,_,S)}prefixKey(_,S){return _}clear(_,S){if(S=h(_,S),S=i(S,y),_=p(_,this[z].empty),this[C]==="opening")return this.defer(()=>this.clear(_,S)),S[y];if(E(this,S))return S[y];let A=_,N=this.keyEncoding(_.keyEncoding);return _=m(_,N),_.keyEncoding=N.format,_.limit===0?this.nextTick(S):this._clear(_,q=>{if(q)return S(q);this.emit("clear",A),S()}),S[y]}_clear(_,S){this.nextTick(S)}iterator(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_.keys=_.keys!==!1,_.values=_.values!==!1,_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new l(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(_)}_iterator(_){return new o(this,_)}keys(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new c(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(_)}_keys(_){return new a(this,_)}values(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new u(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(_)}_values(_){return new d(this,_)}defer(_){if(typeof _!="function")throw new TypeError("The first argument must be a function");this[T].push(_)}[D](){if(this[T].length===0)return;let _=this[T];this[T]=[];for(let S of _)S()}attachResource(_){if(typeof _!="object"||_===null||typeof _.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(_)}detachResource(_){this[w].delete(_)}_chainedBatch(){return new f(this)}_checkKey(_){if(_==null)return new s("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(_){if(_==null)return new s("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=pfe();var{AbstractSublevel:$}=yfe()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=$;var E=function(_,S){return _[C]!=="open"?(_.nextTick(S,new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},P=function(_){return Object.keys(_.supports.encodings).filter(S=>!!_.supports.encodings[S])}}),cF=Xt(r=>{"use strict";r.AbstractLevel=Uz().AbstractLevel,r.AbstractSublevel=Uz().AbstractSublevel,r.AbstractIterator=Wp().AbstractIterator,r.AbstractKeyIterator=Wp().AbstractKeyIterator,r.AbstractValueIterator=Wp().AbstractValueIterator,r.AbstractChainedBatch=sF().AbstractChainedBatch}),gfe=Xt((r,e)=>{e.exports=n;var t=aF();function n(i,s,o){if(typeof s!="number")throw new Error("second argument must be a Number");let a,d,l,c,u,f=!0,h;Array.isArray(i)?(a=[],l=d=i.length):(c=Object.keys(i),a={},l=d=c.length);function p(y){function v(){o&&o(y,a),o=null}f?t(v):v()}function m(y,v,w){if(a[y]=w,v&&(u=!0),--l===0||v)p(v);else if(!u&&h<d){let b;c?(b=c[h],h+=1,i[b](function(T,D){m(b,T,D)})):(b=h,h+=1,i[b](function(T,D){m(b,T,D)}))}}h=s,l?c?c.some(function(y,v){return i[y](function(w,b){m(y,w,b)}),v===s-1}):i.some(function(y,v){return y(function(w,b){m(v,w,b)}),v===s-1}):p(null),f=!1}}),dF=Xt((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,s=t.gte===void 0,o=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,s,o):n!==void 0?IDBKeyRange.lowerBound(n,s):i!==void 0?IDBKeyRange.upperBound(i,o):null}}),lF=Xt((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)}}),wfe=Xt(r=>{"use strict";var{AbstractIterator:e}=cF(),t=dF(),n=lF(),i=Symbol("cache"),s=Symbol("finished"),o=Symbol("options"),a=Symbol("currentOptions"),d=Symbol("position"),l=Symbol("location"),c=Symbol("first"),u={},f=class extends e{constructor(p,m,y){super(p,y),this[i]=[],this[s]=this.limit===0,this[o]=y,this[a]={...y},this[d]=void 0,this[l]=m,this[c]=!0}_nextv(p,m,y){if(this[c]=!1,this[s])return this.nextTick(y,null,[]);if(this[i].length>0)return p=Math.min(p,this[i].length),this.nextTick(y,null,this[i].splice(0,p));this[d]!==void 0&&(this[o].reverse?(this[a].lt=this[d],this[a].lte=void 0):(this[a].gt=this[d],this[a].gte=void 0));let v;try{v=t(this[a])}catch{return this[s]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),b=w.objectStore(this[l]),T=[];if(this[o].reverse){let D=!this[o].values&&b.openKeyCursor?"openKeyCursor":"openCursor";b[D](v,"prev").onsuccess=I=>{let M=I.target.result;if(M){let{key:C,value:z}=M;this[d]=C,T.push([this[o].keys&&C!==void 0?n(C):void 0,this[o].values&&z!==void 0?n(z):void 0]),T.length<p?M.continue():h(w)}else this[s]=!0}}else{let D,I,M=()=>{if(D===void 0||I===void 0)return;let C=Math.max(D.length,I.length);C===0||p===1/0?this[s]=!0:this[d]=D[C-1],T.length=C;for(let z=0;z<C;z++){let L=D[z],B=I[z];T[z]=[this[o].keys&&L!==void 0?n(L):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(w)};this[o].keys||p<1/0?b.getAllKeys(v,p<1/0?p:void 0).onsuccess=C=>{D=C.target.result,M()}:(D=[],this.nextTick(M)),this[o].values?b.getAll(v,p<1/0?p:void 0).onsuccess=C=>{I=C.target.result,M()}:(I=[],this.nextTick(M))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,T),y=null}}_next(p){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(p,null,m,y)}else if(this[s])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[c]&&(this[c]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return p(y);this[i]=v,this._next(p)})}}_all(p,m){this[c]=!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,b)=>{if(w)return m(w);y.length>0&&(b=y.concat(b)),m(null,b)})}_seek(p,m){this[c]=!0,this[i]=[],this[s]=!1,this[d]=void 0,this[a]={...this[o]};let y;try{y=t(this[o])}catch{this[s]=!0;return}y!==null&&!y.includes(p)?this[s]=!0:this[o].reverse?this[a].lte=p:this[a].gte=p}};r.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),vfe=Xt((r,e)=>{"use strict";e.exports=function(t,n,i,s,o){if(s.limit===0)return t.nextTick(o);let a=t.db.transaction([n],"readwrite"),d=a.objectStore(n),l=0;a.oncomplete=function(){o()},a.onabort=function(){o(a.error||new Error("aborted by user"))};let c=d.openKeyCursor?"openKeyCursor":"openCursor",u=s.reverse?"prev":"next";d[c](i,u).onsuccess=function(f){let h=f.target.result;h&&(d.delete(h.key).onsuccess=function(){(s.limit<=0||++l<s.limit)&&h.continue()})}}}),bfe=Xt(r=>{"use strict";var{AbstractLevel:e}=cF(),t=il(),n=gfe(),{fromCallback:i}=fE(),{Iterator:s}=wfe(),o=lF(),a=vfe(),d=dF(),l="level-js-",c=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,b,T){if(typeof b=="function"||typeof T=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:D,version:I,...M}=b||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},M),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=D??l,this[h]=parseInt(I||1,10),this[c]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[h]}get db(){return this[c]}get type(){return"browser-level"}_open(w,b){let T=indexedDB.open(this[u]+this[f],this[h]);T.onerror=function(){b(T.error||new Error("unknown error"))},T.onsuccess=()=>{this[c]=T.result,b()},T.onupgradeneeded=D=>{let I=D.target.result;I.objectStoreNames.contains(this[f])||I.createObjectStore(this[f])}}[p](w){return this[c].transaction([this[f]],w).objectStore(this[f])}[m](w,b){let T=w.transaction;T.onabort=function(){b(T.error||new Error("aborted by user"))},T.oncomplete=function(){b(null,w.result)}}_get(w,b,T){let D=this[p]("readonly"),I;try{I=D.get(w)}catch(M){return this.nextTick(T,M)}this[m](I,function(M,C){if(M)return T(M);if(C===void 0)return T(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));T(null,o(C))})}_getMany(w,b,T){let D=this[p]("readonly"),I=w.map(M=>C=>{let z;try{z=D.get(M)}catch(L){return C(L)}z.onsuccess=()=>{let L=z.result;C(null,L===void 0?L:o(L))},z.onerror=L=>{L.stopPropagation(),C(z.error)}});n(I,16,T)}_del(w,b,T){let D=this[p]("readwrite"),I;try{I=D.delete(w)}catch(M){return this.nextTick(T,M)}this[m](I,T)}_put(w,b,T,D){let I=this[p]("readwrite"),M;try{M=I.put(b,w)}catch(C){return this.nextTick(D,C)}this[m](M,D)}_iterator(w){return new s(this,this[f],w)}_batch(w,b,T){let D=this[p]("readwrite"),I=D.transaction,M=0,C;I.onabort=function(){T(C||I.error||new Error("aborted by user"))},I.oncomplete=function(){T()};function z(){let L=w[M++],B=L.key,H;try{H=L.type==="del"?D.delete(B):D.put(L.value,B)}catch(ee){C=ee,I.abort();return}M<w.length?H.onsuccess=z:typeof I.commit=="function"&&I.commit()}z()}_clear(w,b){let T,D;try{T=d(w)}catch{return this.nextTick(b)}if(w.limit>=0)return a(this,this[f],T,w,b);try{let I=this[p]("readwrite");D=T?I.delete(T):I.clear()}catch(I){return this.nextTick(b,I)}this[m](D,b)}_close(w){this[c].close(),this.nextTick(w)}};v.destroy=function(w,b,T){typeof b=="function"&&(T=b,b=l),T=i(T,y);let D=indexedDB.deleteDatabase(b+w);return D.onsuccess=function(){T()},D.onerror=function(I){T(I)},T[y]},r.BrowserLevel=v}),uF=Xt(r=>{r.Level=bfe().BrowserLevel}),xfe=Xt((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 X=arguments.length,se=Array(X),ce=0;ce<X;ce++)se[ce]=arguments[ce];if(se.length>1){se[0]=se[0].slice(0,-1);for(var be=se.length-1,Pe=1;Pe<be;++Pe)se[Pe]=se[Pe].slice(1,-1);return se[be]=se[be].slice(1),se.join("")}else return se[0]}function i(X){return"(?:"+X+")"}function s(X){return X===void 0?"undefined":X===null?"null":Object.prototype.toString.call(X).split(" ").pop().split("]").shift().toLowerCase()}function o(X){return X.toUpperCase()}function a(X){return X!=null?X instanceof Array?X:typeof X.length!="number"||X.split||X.setInterval||X.call?[X]:Array.prototype.slice.call(X):[]}function d(X,se){var ce=X;if(se)for(var be in se)ce[be]=se[be];return ce}function l(X){var se="[A-Za-z]",ce="[\\x0D]",be="[0-9]",Pe="[\\x22]",We=n(be,"[A-Fa-f]"),Nt="[\\x0A]",Pr="[\\x20]",tn=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),rn="[\\:\\/\\?\\#\\[\\]\\@]",fr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",In=n(rn,fr),ti=X?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",_n=X?"[\\uE000-\\uF8FF]":"[]",Rr=n(se,be,"[\\-\\.\\_\\~]",ti),kr=i(se+n(se,be,"[\\+\\-\\.]")+"*"),mo=i(i(tn+"|"+n(Rr,fr,"[\\:]"))+"*"),_w=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),ls=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),ac=i(ls+"\\."+ls+"\\."+ls+"\\."+ls),Cr=i(We+"{1,4}"),Bs=i(i(Cr+"\\:"+Cr)+"|"+ac),ga=i(i(Cr+"\\:")+"{6}"+Bs),ul=i("\\:\\:"+i(Cr+"\\:")+"{5}"+Bs),Ph=i(i(Cr)+"?\\:\\:"+i(Cr+"\\:")+"{4}"+Bs),ed=i(i(i(Cr+"\\:")+"{0,1}"+Cr)+"?\\:\\:"+i(Cr+"\\:")+"{3}"+Bs),q1=i(i(i(Cr+"\\:")+"{0,2}"+Cr)+"?\\:\\:"+i(Cr+"\\:")+"{2}"+Bs),z1=i(i(i(Cr+"\\:")+"{0,3}"+Cr)+"?\\:\\:"+Cr+"\\:"+Bs),Bm=i(i(i(Cr+"\\:")+"{0,4}"+Cr)+"?\\:\\:"+Bs),jm=i(i(i(Cr+"\\:")+"{0,5}"+Cr)+"?\\:\\:"+Cr),Nm=i(i(i(Cr+"\\:")+"{0,6}"+Cr)+"?\\:\\:"),_h=i([ga,ul,Ph,ed,q1,z1,Bm,jm,Nm].join("|")),Mm=i(i(Rr+"|"+tn)+"+"),Um=i(_h+"\\%25"+Mm),GJ=i(_h+i("\\%25|\\%(?!"+We+"{2})")+Mm),WJ=i("[vV]"+We+"+\\."+n(Rr,fr,"[\\:]")+"+"),HJ=i("\\["+i(GJ+"|"+_h+"|"+WJ)+"\\]"),nO=i(i(tn+"|"+n(Rr,fr))+"*"),Ew=i(HJ+"|"+ac+"(?!"+nO+")|"+nO),Sw=i(be+"*"),iO=i(i(mo+"@")+"?"+Ew+i("\\:"+Sw)+"?"),Tw=i(tn+"|"+n(Rr,fr,"[\\:\\@]")),VJ=i(Tw+"*"),oO=i(Tw+"+"),JJ=i(i(tn+"|"+n(Rr,fr,"[\\@]"))+"+"),fl=i(i("\\/"+VJ)+"*"),Km=i("\\/"+i(oO+fl)+"?"),ZS=i(JJ+fl),F1=i(oO+fl),Lm="(?!"+Tw+")",$be=i(fl+"|"+Km+"|"+ZS+"|"+F1+"|"+Lm),qm=i(i(Tw+"|"+n("[\\/\\?]",_n))+"*"),Dw=i(i(Tw+"|[\\/\\?]")+"*"),sO=i(i("\\/\\/"+iO+fl)+"|"+Km+"|"+F1+"|"+Lm),YJ=i(kr+"\\:"+sO+i("\\?"+qm)+"?"+i("\\#"+Dw)+"?"),ZJ=i(i("\\/\\/"+iO+fl)+"|"+Km+"|"+ZS+"|"+Lm),QJ=i(ZJ+i("\\?"+qm)+"?"+i("\\#"+Dw)+"?"),Obe=i(YJ+"|"+QJ),Bbe=i(kr+"\\:"+sO+i("\\?"+qm)+"?"),jbe="^("+kr+")\\:"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+F1+"|"+Lm+")")+i("\\?("+qm+")")+"?"+i("\\#("+Dw+")")+"?$",Nbe="^(){0}"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+ZS+"|"+Lm+")")+i("\\?("+qm+")")+"?"+i("\\#("+Dw+")")+"?$",Mbe="^("+kr+")\\:"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+F1+"|"+Lm+")")+i("\\?("+qm+")")+"?$",Ube="^"+i("\\#("+Dw+")")+"?$",Kbe="^"+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",se,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Rr,fr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Rr,fr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Rr,fr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Rr,fr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Rr,fr,"[\\:\\@\\/\\?]",_n),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Rr,fr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Rr,fr),"g"),UNRESERVED:new RegExp(Rr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Rr,In),"g"),PCT_ENCODED:new RegExp(tn,"g"),IPV4ADDRESS:new RegExp("^("+ac+")$"),IPV6ADDRESS:new RegExp("^\\[?("+_h+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+Mm+")")+"?\\]?$")}}var c=l(!1),u=l(!0),f=function(){function X(se,ce){var be=[],Pe=!0,We=!1,Nt=void 0;try{for(var Pr=se[Symbol.iterator](),tn;!(Pe=(tn=Pr.next()).done)&&(be.push(tn.value),!(ce&&be.length===ce));Pe=!0);}catch(rn){We=!0,Nt=rn}finally{try{!Pe&&Pr.return&&Pr.return()}finally{if(We)throw Nt}}return be}return function(se,ce){if(Array.isArray(se))return se;if(Symbol.iterator in Object(se))return X(se,ce);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(X){if(Array.isArray(X)){for(var se=0,ce=Array(X.length);se<X.length;se++)ce[se]=X[se];return ce}else return Array.from(X)},p=2147483647,m=36,y=1,v=26,w=38,b=700,T=72,D=128,I="-",M=/^xn--/,C=/[^\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"},B=m-y,H=Math.floor,ee=String.fromCharCode;function R(X){throw new RangeError(L[X])}function $(X,se){for(var ce=[],be=X.length;be--;)ce[be]=se(X[be]);return ce}function E(X,se){var ce=X.split("@"),be="";ce.length>1&&(be=ce[0]+"@",X=ce[1]),X=X.replace(z,".");var Pe=X.split("."),We=$(Pe,se).join(".");return be+We}function P(X){for(var se=[],ce=0,be=X.length;ce<be;){var Pe=X.charCodeAt(ce++);if(Pe>=55296&&Pe<=56319&&ce<be){var We=X.charCodeAt(ce++);(We&64512)==56320?se.push(((Pe&1023)<<10)+(We&1023)+65536):(se.push(Pe),ce--)}else se.push(Pe)}return se}var _=function(X){return String.fromCodePoint.apply(String,h(X))},S=function(X){return X-48<10?X-22:X-65<26?X-65:X-97<26?X-97:m},A=function(X,se){return X+22+75*(X<26)-((se!=0)<<5)},N=function(X,se,ce){var be=0;for(X=ce?H(X/b):X>>1,X+=H(X/se);X>B*v>>1;be+=m)X=H(X/B);return H(be+(B+1)*X/(X+w))},q=function(X){var se=[],ce=X.length,be=0,Pe=D,We=T,Nt=X.lastIndexOf(I);Nt<0&&(Nt=0);for(var Pr=0;Pr<Nt;++Pr)X.charCodeAt(Pr)>=128&&R("not-basic"),se.push(X.charCodeAt(Pr));for(var tn=Nt>0?Nt+1:0;tn<ce;){for(var rn=be,fr=1,In=m;;In+=m){tn>=ce&&R("invalid-input");var ti=S(X.charCodeAt(tn++));(ti>=m||ti>H((p-be)/fr))&&R("overflow"),be+=ti*fr;var _n=In<=We?y:In>=We+v?v:In-We;if(ti<_n)break;var Rr=m-_n;fr>H(p/Rr)&&R("overflow"),fr*=Rr}var kr=se.length+1;We=N(be-rn,kr,rn==0),H(be/kr)>p-Pe&&R("overflow"),Pe+=H(be/kr),be%=kr,se.splice(be++,0,Pe)}return String.fromCodePoint.apply(String,se)},W=function(X){var se=[];X=P(X);var ce=X.length,be=D,Pe=0,We=T,Nt=!0,Pr=!1,tn=void 0;try{for(var rn=X[Symbol.iterator](),fr;!(Nt=(fr=rn.next()).done);Nt=!0){var In=fr.value;In<128&&se.push(ee(In))}}catch(Um){Pr=!0,tn=Um}finally{try{!Nt&&rn.return&&rn.return()}finally{if(Pr)throw tn}}var ti=se.length,_n=ti;for(ti&&se.push(I);_n<ce;){var Rr=p,kr=!0,mo=!1,_w=void 0;try{for(var ls=X[Symbol.iterator](),ac;!(kr=(ac=ls.next()).done);kr=!0){var Cr=ac.value;Cr>=be&&Cr<Rr&&(Rr=Cr)}}catch(Um){mo=!0,_w=Um}finally{try{!kr&&ls.return&&ls.return()}finally{if(mo)throw _w}}var Bs=_n+1;Rr-be>H((p-Pe)/Bs)&&R("overflow"),Pe+=(Rr-be)*Bs,be=Rr;var ga=!0,ul=!1,Ph=void 0;try{for(var ed=X[Symbol.iterator](),q1;!(ga=(q1=ed.next()).done);ga=!0){var z1=q1.value;if(z1<be&&++Pe>p&&R("overflow"),z1==be){for(var Bm=Pe,jm=m;;jm+=m){var Nm=jm<=We?y:jm>=We+v?v:jm-We;if(Bm<Nm)break;var _h=Bm-Nm,Mm=m-Nm;se.push(ee(A(Nm+_h%Mm,0))),Bm=H(_h/Mm)}se.push(ee(A(Bm,0))),We=N(Pe,Bs,_n==ti),Pe=0,++_n}}}catch(Um){ul=!0,Ph=Um}finally{try{!ga&&ed.return&&ed.return()}finally{if(ul)throw Ph}}++Pe,++be}return se.join("")},J=function(X){return E(X,function(se){return M.test(se)?q(se.slice(4).toLowerCase()):se})},V=function(X){return E(X,function(se){return C.test(se)?"xn--"+W(se):se})},Y={version:"2.1.0",ucs2:{decode:P,encode:_},decode:q,encode:W,toASCII:V,toUnicode:J},F={};function Q(X){var se=X.charCodeAt(0),ce=void 0;return se<16?ce="%0"+se.toString(16).toUpperCase():se<128?ce="%"+se.toString(16).toUpperCase():se<2048?ce="%"+(se>>6|192).toString(16).toUpperCase()+"%"+(se&63|128).toString(16).toUpperCase():ce="%"+(se>>12|224).toString(16).toUpperCase()+"%"+(se>>6&63|128).toString(16).toUpperCase()+"%"+(se&63|128).toString(16).toUpperCase(),ce}function ie(X){for(var se="",ce=0,be=X.length;ce<be;){var Pe=parseInt(X.substr(ce+1,2),16);if(Pe<128)se+=String.fromCharCode(Pe),ce+=3;else if(Pe>=194&&Pe<224){if(be-ce>=6){var We=parseInt(X.substr(ce+4,2),16);se+=String.fromCharCode((Pe&31)<<6|We&63)}else se+=X.substr(ce,6);ce+=6}else if(Pe>=224){if(be-ce>=9){var Nt=parseInt(X.substr(ce+4,2),16),Pr=parseInt(X.substr(ce+7,2),16);se+=String.fromCharCode((Pe&15)<<12|(Nt&63)<<6|Pr&63)}else se+=X.substr(ce,9);ce+=9}else se+=X.substr(ce,3),ce+=3}return se}function oe(X,se){function ce(be){var Pe=ie(be);return Pe.match(se.UNRESERVED)?Pe:be}return X.scheme&&(X.scheme=String(X.scheme).replace(se.PCT_ENCODED,ce).toLowerCase().replace(se.NOT_SCHEME,"")),X.userinfo!==void 0&&(X.userinfo=String(X.userinfo).replace(se.PCT_ENCODED,ce).replace(se.NOT_USERINFO,Q).replace(se.PCT_ENCODED,o)),X.host!==void 0&&(X.host=String(X.host).replace(se.PCT_ENCODED,ce).toLowerCase().replace(se.NOT_HOST,Q).replace(se.PCT_ENCODED,o)),X.path!==void 0&&(X.path=String(X.path).replace(se.PCT_ENCODED,ce).replace(X.scheme?se.NOT_PATH:se.NOT_PATH_NOSCHEME,Q).replace(se.PCT_ENCODED,o)),X.query!==void 0&&(X.query=String(X.query).replace(se.PCT_ENCODED,ce).replace(se.NOT_QUERY,Q).replace(se.PCT_ENCODED,o)),X.fragment!==void 0&&(X.fragment=String(X.fragment).replace(se.PCT_ENCODED,ce).replace(se.NOT_FRAGMENT,Q).replace(se.PCT_ENCODED,o)),X}function Z(X){return X.replace(/^0*(.*)/,"$1")||"0"}function le(X,se){var ce=X.match(se.IPV4ADDRESS)||[],be=f(ce,2),Pe=be[1];return Pe?Pe.split(".").map(Z).join("."):X}function he(X,se){var ce=X.match(se.IPV6ADDRESS)||[],be=f(ce,3),Pe=be[1],We=be[2];if(Pe){for(var Nt=Pe.toLowerCase().split("::").reverse(),Pr=f(Nt,2),tn=Pr[0],rn=Pr[1],fr=rn?rn.split(":").map(Z):[],In=tn.split(":").map(Z),ti=se.IPV4ADDRESS.test(In[In.length-1]),_n=ti?7:8,Rr=In.length-_n,kr=Array(_n),mo=0;mo<_n;++mo)kr[mo]=fr[mo]||In[Rr+mo]||"";ti&&(kr[_n-1]=le(kr[_n-1],se));var _w=kr.reduce(function(ga,ul,Ph){if(!ul||ul==="0"){var ed=ga[ga.length-1];ed&&ed.index+ed.length===Ph?ed.length++:ga.push({index:Ph,length:1})}return ga},[]),ls=_w.sort(function(ga,ul){return ul.length-ga.length})[0],ac=void 0;if(ls&&ls.length>1){var Cr=kr.slice(0,ls.index),Bs=kr.slice(ls.index+ls.length);ac=Cr.join(":")+"::"+Bs.join(":")}else ac=kr.join(":");return We&&(ac+="%"+We),ac}else return X}var ue=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function pe(X){var se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce={},be=se.iri!==!1?u:c;se.reference==="suffix"&&(X=(se.scheme?se.scheme+":":"")+"//"+X);var Pe=X.match(ue);if(Pe){Se?(ce.scheme=Pe[1],ce.userinfo=Pe[3],ce.host=Pe[4],ce.port=parseInt(Pe[5],10),ce.path=Pe[6]||"",ce.query=Pe[7],ce.fragment=Pe[8],isNaN(ce.port)&&(ce.port=Pe[5])):(ce.scheme=Pe[1]||void 0,ce.userinfo=X.indexOf("@")!==-1?Pe[3]:void 0,ce.host=X.indexOf("//")!==-1?Pe[4]:void 0,ce.port=parseInt(Pe[5],10),ce.path=Pe[6]||"",ce.query=X.indexOf("?")!==-1?Pe[7]:void 0,ce.fragment=X.indexOf("#")!==-1?Pe[8]:void 0,isNaN(ce.port)&&(ce.port=X.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Pe[4]:void 0)),ce.host&&(ce.host=he(le(ce.host,be),be)),ce.scheme===void 0&&ce.userinfo===void 0&&ce.host===void 0&&ce.port===void 0&&!ce.path&&ce.query===void 0?ce.reference="same-document":ce.scheme===void 0?ce.reference="relative":ce.fragment===void 0?ce.reference="absolute":ce.reference="uri",se.reference&&se.reference!=="suffix"&&se.reference!==ce.reference&&(ce.error=ce.error||"URI is not a "+se.reference+" reference.");var We=F[(se.scheme||ce.scheme||"").toLowerCase()];if(!se.unicodeSupport&&(!We||!We.unicodeSupport)){if(ce.host&&(se.domainHost||We&&We.domainHost))try{ce.host=Y.toASCII(ce.host.replace(be.PCT_ENCODED,ie).toLowerCase())}catch(Nt){ce.error=ce.error||"Host's domain name can not be converted to ASCII via punycode: "+Nt}oe(ce,c)}else oe(ce,be);We&&We.parse&&We.parse(ce,se)}else ce.error=ce.error||"URI can not be parsed.";return ce}function Ae(X,se){var ce=se.iri!==!1?u:c,be=[];return X.userinfo!==void 0&&(be.push(X.userinfo),be.push("@")),X.host!==void 0&&be.push(he(le(String(X.host),ce),ce).replace(ce.IPV6ADDRESS,function(Pe,We,Nt){return"["+We+(Nt?"%25"+Nt:"")+"]"})),(typeof X.port=="number"||typeof X.port=="string")&&(be.push(":"),be.push(String(X.port))),be.length?be.join(""):void 0}var Ot=/^\.\.?\//,ai=/^\/\.(\/|$)/,Lr=/^\/\.\.(\/|$)/,ds=/^\/?(?:.|\n)*?(?=\/|$)/;function Ye(X){for(var se=[];X.length;)if(X.match(Ot))X=X.replace(Ot,"");else if(X.match(ai))X=X.replace(ai,"/");else if(X.match(Lr))X=X.replace(Lr,"/"),se.pop();else if(X==="."||X==="..")X="";else{var ce=X.match(ds);if(ce){var be=ce[0];X=X.slice(be.length),se.push(be)}else throw new Error("Unexpected dot segment condition")}return se.join("")}function ar(X){var se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce=se.iri?u:c,be=[],Pe=F[(se.scheme||X.scheme||"").toLowerCase()];if(Pe&&Pe.serialize&&Pe.serialize(X,se),X.host&&!ce.IPV6ADDRESS.test(X.host)&&(se.domainHost||Pe&&Pe.domainHost))try{X.host=se.iri?Y.toUnicode(X.host):Y.toASCII(X.host.replace(ce.PCT_ENCODED,ie).toLowerCase())}catch(Pr){X.error=X.error||"Host's domain name can not be converted to "+(se.iri?"Unicode":"ASCII")+" via punycode: "+Pr}oe(X,ce),se.reference!=="suffix"&&X.scheme&&(be.push(X.scheme),be.push(":"));var We=Ae(X,se);if(We!==void 0&&(se.reference!=="suffix"&&be.push("//"),be.push(We),X.path&&X.path.charAt(0)!=="/"&&be.push("/")),X.path!==void 0){var Nt=X.path;!se.absolutePath&&(!Pe||!Pe.absolutePath)&&(Nt=Ye(Nt)),We===void 0&&(Nt=Nt.replace(/^\/\//,"/%2F")),be.push(Nt)}return X.query!==void 0&&(be.push("?"),be.push(X.query)),X.fragment!==void 0&&(be.push("#"),be.push(X.fragment)),be.join("")}function qr(X,se){var ce=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Pe={};return be||(X=pe(ar(X,ce),ce),se=pe(ar(se,ce),ce)),ce=ce||{},!ce.tolerant&&se.scheme?(Pe.scheme=se.scheme,Pe.userinfo=se.userinfo,Pe.host=se.host,Pe.port=se.port,Pe.path=Ye(se.path||""),Pe.query=se.query):(se.userinfo!==void 0||se.host!==void 0||se.port!==void 0?(Pe.userinfo=se.userinfo,Pe.host=se.host,Pe.port=se.port,Pe.path=Ye(se.path||""),Pe.query=se.query):(se.path?(se.path.charAt(0)==="/"?Pe.path=Ye(se.path):((X.userinfo!==void 0||X.host!==void 0||X.port!==void 0)&&!X.path?Pe.path="/"+se.path:X.path?Pe.path=X.path.slice(0,X.path.lastIndexOf("/")+1)+se.path:Pe.path=se.path,Pe.path=Ye(Pe.path)),Pe.query=se.query):(Pe.path=X.path,se.query!==void 0?Pe.query=se.query:Pe.query=X.query),Pe.userinfo=X.userinfo,Pe.host=X.host,Pe.port=X.port),Pe.scheme=X.scheme),Pe.fragment=se.fragment,Pe}function yr(X,se,ce){var be=d({scheme:"null"},ce);return ar(qr(pe(X,be),pe(se,be),be,!0),be)}function Gt(X,se){return typeof X=="string"?X=ar(pe(X,se),se):s(X)==="object"&&(X=pe(ar(X,se),se)),X}function k(X,se,ce){return typeof X=="string"?X=ar(pe(X,ce),ce):s(X)==="object"&&(X=ar(X,ce)),typeof se=="string"?se=ar(pe(se,ce),ce):s(se)==="object"&&(se=ar(se,ce)),X===se}function U(X,se){return X&&X.toString().replace(!se||!se.iri?c.ESCAPE:u.ESCAPE,Q)}function K(X,se){return X&&X.toString().replace(!se||!se.iri?c.PCT_ENCODED:u.PCT_ENCODED,ie)}var te={scheme:"http",domainHost:!0,parse:function(X,se){return X.host||(X.error=X.error||"HTTP URIs must have a host."),X},serialize:function(X,se){var ce=String(X.scheme).toLowerCase()==="https";return(X.port===(ce?443:80)||X.port==="")&&(X.port=void 0),X.path||(X.path="/"),X}},de={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(X){return typeof X.secure=="boolean"?X.secure:String(X.scheme).toLowerCase()==="wss"}var Ee={scheme:"ws",domainHost:!0,parse:function(X,se){var ce=X;return ce.secure=ge(ce),ce.resourceName=(ce.path||"/")+(ce.query?"?"+ce.query:""),ce.path=void 0,ce.query=void 0,ce},serialize:function(X,se){if((X.port===(ge(X)?443:80)||X.port==="")&&(X.port=void 0),typeof X.secure=="boolean"&&(X.scheme=X.secure?"wss":"ws",X.secure=void 0),X.resourceName){var ce=X.resourceName.split("?"),be=f(ce,2),Pe=be[0],We=be[1];X.path=Pe&&Pe!=="/"?Pe:void 0,X.query=We,X.resourceName=void 0}return X.fragment=void 0,X}},Wt={scheme:"wss",domainHost:Ee.domainHost,parse:Ee.parse,serialize:Ee.serialize},ci={},Vr=!0,Dr="[A-Za-z0-9\\-\\.\\_\\~"+(Vr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",gr="[0-9A-Fa-f]",BJ=i(i("%[EFef]"+gr+"%"+gr+gr+"%"+gr+gr)+"|"+i("%[89A-Fa-f]"+gr+"%"+gr+gr)+"|"+i("%"+gr+gr)),jJ="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",NJ="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",MJ=n(NJ,'[\\"\\\\]'),UJ="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",KJ=new RegExp(Dr,"g"),Om=new RegExp(BJ,"g"),LJ=new RegExp(n("[^]",jJ,"[\\.]",'[\\"]',MJ),"g"),X$=new RegExp(n("[^]",Dr,UJ),"g"),qJ=X$;function YS(X){var se=ie(X);return se.match(KJ)?se:X}var eO={scheme:"mailto",parse:function(X,se){var ce=X,be=ce.to=ce.path?ce.path.split(","):[];if(ce.path=void 0,ce.query){for(var Pe=!1,We={},Nt=ce.query.split("&"),Pr=0,tn=Nt.length;Pr<tn;++Pr){var rn=Nt[Pr].split("=");switch(rn[0]){case"to":for(var fr=rn[1].split(","),In=0,ti=fr.length;In<ti;++In)be.push(fr[In]);break;case"subject":ce.subject=K(rn[1],se);break;case"body":ce.body=K(rn[1],se);break;default:Pe=!0,We[K(rn[0],se)]=K(rn[1],se);break}}Pe&&(ce.headers=We)}ce.query=void 0;for(var _n=0,Rr=be.length;_n<Rr;++_n){var kr=be[_n].split("@");if(kr[0]=K(kr[0]),se.unicodeSupport)kr[1]=K(kr[1],se).toLowerCase();else try{kr[1]=Y.toASCII(K(kr[1],se).toLowerCase())}catch(mo){ce.error=ce.error||"Email address's domain name can not be converted to ASCII via punycode: "+mo}be[_n]=kr.join("@")}return ce},serialize:function(X,se){var ce=X,be=a(X.to);if(be){for(var Pe=0,We=be.length;Pe<We;++Pe){var Nt=String(be[Pe]),Pr=Nt.lastIndexOf("@"),tn=Nt.slice(0,Pr).replace(Om,YS).replace(Om,o).replace(LJ,Q),rn=Nt.slice(Pr+1);try{rn=se.iri?Y.toUnicode(rn):Y.toASCII(K(rn,se).toLowerCase())}catch(_n){ce.error=ce.error||"Email address's domain name can not be converted to "+(se.iri?"Unicode":"ASCII")+" via punycode: "+_n}be[Pe]=tn+"@"+rn}ce.path=be.join(",")}var fr=X.headers=X.headers||{};X.subject&&(fr.subject=X.subject),X.body&&(fr.body=X.body);var In=[];for(var ti in fr)fr[ti]!==ci[ti]&&In.push(ti.replace(Om,YS).replace(Om,o).replace(X$,Q)+"="+fr[ti].replace(Om,YS).replace(Om,o).replace(qJ,Q));return In.length&&(ce.query=In.join("&")),ce}},zJ=/^([^\:]+)\:(.*)/,tO={scheme:"urn",parse:function(X,se){var ce=X.path&&X.path.match(zJ),be=X;if(ce){var Pe=se.scheme||be.scheme||"urn",We=ce[1].toLowerCase(),Nt=ce[2],Pr=Pe+":"+(se.nid||We),tn=F[Pr];be.nid=We,be.nss=Nt,be.path=void 0,tn&&(be=tn.parse(be,se))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(X,se){var ce=se.scheme||X.scheme||"urn",be=X.nid,Pe=ce+":"+(se.nid||be),We=F[Pe];We&&(X=We.serialize(X,se));var Nt=X,Pr=X.nss;return Nt.path=(be||se.nid)+":"+Pr,Nt}},FJ=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,rO={scheme:"urn:uuid",parse:function(X,se){var ce=X;return ce.uuid=ce.nss,ce.nss=void 0,!se.tolerant&&(!ce.uuid||!ce.uuid.match(FJ))&&(ce.error=ce.error||"UUID is not valid."),ce},serialize:function(X,se){var ce=X;return ce.nss=(X.uuid||"").toLowerCase(),ce}};F[te.scheme]=te,F[de.scheme]=de,F[Ee.scheme]=Ee,F[Wt.scheme]=Wt,F[eO.scheme]=eO,F[tO.scheme]=tO,F[rO.scheme]=rO,t.SCHEMES=F,t.pctEncChar=Q,t.pctDecChars=ie,t.parse=pe,t.removeDotSegments=Ye,t.serialize=ar,t.resolveComponents=qr,t.resolve=yr,t.normalize=Gt,t.equal=k,t.escapeComponent=U,t.unescapeComponent=K,Object.defineProperty(t,"__esModule",{value:!0})})}),Pfe=Xt((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,s,o)=>`${i}${o===0?"":","}${t(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,s)=>{if(n[s]===void 0||typeof n[s]=="symbol")return i;let o=i.length===0?"":",";return`${i}${o}${t(s)}:${t(n[s])}`},"")}}`}}),fF=Xt((r,e)=>{var t=1e3,n=t*60,i=n*60,s=i*24,o=s*7,a=s*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return d(f);if(p==="number"&&isFinite(f))return h.long?c(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function d(f){if(f=String(f),!(f.length>100)){var h=/^(-?(?:\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(h){var p=parseFloat(h[1]),m=(h[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return p*a;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*s;case"hours":case"hour":case"hrs":case"hr":case"h":return p*i;case"minutes":case"minute":case"mins":case"min":case"m":return p*n;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function l(f){var h=Math.abs(f);return h>=s?Math.round(f/s)+"d":h>=i?Math.round(f/i)+"h":h>=n?Math.round(f/n)+"m":h>=t?Math.round(f/t)+"s":f+"ms"}function c(f){var h=Math.abs(f);return h>=s?u(f,h,s,"day"):h>=i?u(f,h,i,"hour"):h>=n?u(f,h,n,"minute"):h>=t?u(f,h,t,"second"):f+" ms"}function u(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),hE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(hE||{}),fo={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},oo=class hF{constructor({method:e,id:t,path:n,query:i,fragment:s,params:o}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=s,this.params=o}static parse(e){if(!e||e.length>2048)return null;let t=hF.DID_URI_PATTERN.exec(e);if(!t?.groups)return null;let{method:n,id:i,path:s,query:o,fragment:a}=t.groups,d={uri:`did:${n}:${i}`,method:n,id:i};if(s&&(d.path=s),o&&(d.query=o.slice(1)),a&&(d.fragment=a.slice(1)),o){let l={},c=o.slice(1).split("&");for(let u of c){let[f,h]=u.split("=");l[f]=h}d.params=l}return d}};oo.METHOD_PATTERN="([a-z0-9]+)",oo.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",oo.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${oo.PCT_ENCODED_PATTERN})`,oo.METHOD_ID_PATTERN=`((?:${oo.ID_CHAR_PATTERN}*:)*(${oo.ID_CHAR_PATTERN}+))`,oo.PATH_PATTERN="(/[^#?]*)?",oo.QUERY_PATTERN="([?][^#]*)?",oo.FRAGMENT_PATTERN="(#.*)?",oo.DID_URI_PATTERN=new RegExp("^did:(?<method>"+oo.METHOD_PATTERN+"):(?<id>"+oo.METHOD_ID_PATTERN+")(?<path>"+oo.PATH_PATTERN+")(?<query>"+oo.QUERY_PATTERN+")(?<fragment>"+oo.FRAGMENT_PATTERN+")$");Qn=oo,rt=class pF 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,pF)}},_fe=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidGatewayUri="invalidGatewayUri",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))(_fe||{}),Qa=class mF extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,mF)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(ks||(ks={}));Efe=Xp(rfe(),1);Tfe=Sfe,Dfe=Tfe,kfe=Dfe,P9e=new Uint8Array(0),Afe=(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},c5=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")},Ife=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")}},Rfe=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 yF(this,r)}},Cfe=class{constructor(r){this.decoders=r}or(r){return yF(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`)}},yF=(r,e)=>new Cfe({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),$fe=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Ife(r,e,t),this.decoder=new Rfe(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},gF=({name:r,prefix:e,encode:t,decode:n})=>new $fe(r,e,t,n),wF=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=kfe(t,e);return gF({prefix:r,name:e,encode:n,decode:s=>c5(i(s))})},Ofe=(r,e,t,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,d=0,l=0;for(let c=0;c<s;++c){let u=i[r[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&d>>a)}if(a>=t||255&d<<8-a)throw new SyntaxError("Unexpected end of data");return o},Bfe=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let d=0;d<r.length;++d)for(a=a<<8|r[d],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},ua=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>gF({prefix:e,name:r,encode(i){return Bfe(i,n,t)},decode(i){return Ofe(i,n,t,r)}}),$2=ua({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_9e=ua({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),E9e=ua({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),S9e=ua({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),T9e=ua({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),D9e=ua({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),k9e=ua({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),A9e=ua({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Kz=ua({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ya=wF({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),I9e=wF({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),R9e=ua({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),C9e=ua({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),au=ua({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$9e=ua({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});pb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Lz=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(s){t[s]=r[s]&&function(o){return new Promise(function(a,d){o=r[s](o),i(a,d,o.done,o.value)})}}function i(s,o,a,d){Promise.resolve(d).then(function(l){s({value:l,done:a})},o)}},S2=new TextEncoder,Up=new TextDecoder,ot=class Ts{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new Ts(e,"ArrayBuffer")}static asyncIterable(e){if(!Nfe(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ts(e,"AsyncIterable")}static base32Z(e){return new Ts(e,"Base32Z")}static base58Btc(e){return new Ts(e,"Base58Btc")}static base64Url(e){return new Ts(e,"Base64Url")}static bufferSource(e){return new Ts(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 Ts(e,"Hex")}static multibase(e){return new Ts(e,"Multibase")}static object(e){return new Ts(e,"Object")}static string(e){return new Ts(e,"String")}static uint8Array(e){return new Ts(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ya.baseDecode(this.data).buffer;case"Base64Url":return au.baseDecode(this.data).buffer;case"BufferSource":{if(M6(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return jfe(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 pb(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 Kz.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 Ya.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ya.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 au.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return au.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=S2.encode(e);return au.baseEncode(t)}case"String":{let e=S2.encode(this.data);return au.baseEncode(e)}case"Uint8Array":return au.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return pb(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let d=[];try{for(var s=!0,o=Lz(this.data),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;let l=i;d.push(l)}}catch(l){t={error:l}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return new Blob(d)}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 Ts.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return Ts.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=au.baseDecode(this.data),t=Up.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Up.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return pb(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 Up.decode(this.data);case"Base64Url":{let e=au.baseDecode(this.data);return Up.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Up.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return pb(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let d="";try{for(var s=!0,o=Lz(this.data),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;let l=i;typeof l=="string"?d+=l:d+=Up.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return d+=Up.decode(void 0,{stream:!1}),d}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 Kz.baseDecode(this.data);case"Base58Btc":return Ya.baseDecode(this.data);case"Base64Url":return au.baseDecode(this.data);case"BufferSource":{let e=M6(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 S2.encode(e)}case"String":return S2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return pb(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"})(jb||(jb={}));Mfe=class{constructor(){this.logLevel=jb.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==jb.Silent&&console.info(r)}error(r){this.logLevel!==jb.Silent&&console.error(r)}},Ufe=new Mfe;typeof window<"u"&&(window.enboxLogger=Ufe);xb={};o5(xb,{decode:()=>tE,encodeTo:()=>Mb,encodingLength:()=>Ub});Kfe=vF,qz=128,Lfe=127,qfe=~Lfe,zfe=Math.pow(2,31);Ffe=U6,Gfe=128,zz=127;Wfe=Math.pow(2,7),Hfe=Math.pow(2,14),Vfe=Math.pow(2,21),Jfe=Math.pow(2,28),Yfe=Math.pow(2,35),Zfe=Math.pow(2,42),Qfe=Math.pow(2,49),Xfe=Math.pow(2,56),ehe=Math.pow(2,63),the=function(r){return r<Wfe?1:r<Hfe?2:r<Vfe?3:r<Jfe?4:r<Yfe?5:r<Zfe?6:r<Qfe?7:r<Xfe?8:r<ehe?9:10},rhe={encode:Kfe,decode:Ffe,encodingLength:the},nhe=rhe,eE=nhe,tE=(r,e=0)=>[eE.decode(r,e),eE.decode.bytes],Mb=(r,e,t=0)=>(eE.encode(r,e,t),e),Ub=r=>eE.encodingLength(r),ihe=(r,e)=>{let t=e.byteLength,n=Ub(r),i=n+Ub(t),s=new Uint8Array(i+t);return Mb(r,s,0),Mb(t,s,n),s.set(e,i),new d5(r,t,e,s)},ohe=r=>{let e=c5(r),[t,n]=tE(e),[i,s]=tE(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new d5(t,i,o,e)},she=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Afe(r.bytes,t.bytes)}},d5=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},Fz=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return che(t,K6(r),e||Ya.encoder);default:return dhe(t,K6(r),e||$2.encoder)}},Gz=new WeakMap,K6=r=>{let e=Gz.get(r);if(e==null){let t=new Map;return Gz.set(r,t),t}return e},O9e=class ko{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!==mb)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==lhe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ko.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=ihe(e,t);return ko.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 ko.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&she(e.multihash,n.multihash)}toString(e){return Fz(this,e)}toJSON(){return{"/":Fz(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 ko)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new ko(n,i,s,o||Wz(n,i,s.bytes))}else if(t[uhe]===!0){let{version:n,multihash:i,code:s}=t,o=ohe(i);return ko.create(n,s,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!==mb)throw new Error(`Version 0 CID must use dag-pb (code: ${mb}) block encoding`);return new ko(e,t,n,n.bytes)}case 1:{let i=Wz(e,t,n.bytes);return new ko(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ko.create(0,mb,e)}static createV1(e,t){return ko.create(1,e,t)}static decode(e){let[t,n]=ko.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ko.inspectBytes(e),n=t.size-t.multihashSize,i=c5(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new d5(t.multihashCode,t.digestSize,s,i);return[t.version===0?ko.createV0(o):ko.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=tE(e.subarray(t));return t+=f,u},i=n(),s=mb;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),d=n(),l=t+d,c=l-o;return{version:i,codec:s,multihashCode:a,digestSize:d,multihashSize:c,size:l}}static parse(e,t){let[n,i]=ahe(e,t),s=ko.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return K6(s).set(n,e),s}},ahe=(r,e)=>{switch(r[0]){case"Q":{let t=e||Ya;return[Ya.prefix,t.decode(`${Ya.prefix}${r}`)]}case Ya.prefix:{let t=e||Ya;return[Ya.prefix,t.decode(r)]}case $2.prefix:{let t=e||$2;return[$2.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)]}}},che=(r,e,t)=>{let{prefix:n}=t;if(n!==Ya.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},dhe=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},mb=112,lhe=18,Wz=(r,e,t)=>{let n=Ub(r),i=n+Ub(e),s=new Uint8Array(i+t.byteLength);return Mb(r,s,0),Mb(e,s,n),s.set(t,i),s},uhe=Symbol.for("@ipld/js-cid/CID"),ec=class eh{static addPrefix(e){var t;let{code:n,data:i,name:s}=e;if(!(s?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=eh.codeToName.has(n)?n:eh.nameToCode.get(s),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let o=xb.encodingLength(n),a=new Uint8Array(o+i.byteLength);return a.set(i,o),xb.encodeTo(n,a),a}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=xb.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=eh.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=eh.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){eh.codeToName.set(e.code,e.name),eh.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=xb.decode(t),s=eh.codeToName.get(n);if(s===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:s}}};ec.codeToName=new Map;ec.nameToCode=new Map;ec.registerCodec({code:237,name:"ed25519-pub"});ec.registerCodec({code:4864,name:"ed25519-priv"});ec.registerCodec({code:236,name:"x25519-pub"});ec.registerCodec({code:4866,name:"x25519-priv"});ec.registerCodec({code:231,name:"secp256k1-pub"});ec.registerCodec({code:4865,name:"secp256k1-priv"});B9e=Xp(uF(),1),Ff=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},fhe=class{constructor(){this.store=new Map}clear(){return Ff(this,void 0,void 0,function*(){this.store.clear()})}open(){return Ff(this,void 0,void 0,function*(){})}close(){return Ff(this,void 0,void 0,function*(){})}delete(r){return Ff(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return Ff(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return Ff(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return Ff(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return Ff(this,void 0,void 0,function*(){this.store.set(r,e)})}},hhe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};mhe=["http:","https:"],O2=class extends Error{constructor(r){super(r),this.name="PublicUrlValidationError"}};yhe=5,ghe=new Set([301,302,303,307,308]);pE=class{},EF={};o5(EF,{bitGet:()=>khe,bitLen:()=>Dhe,bitMask:()=>u5,bitSet:()=>Ahe,bytesToHex:()=>Yp,bytesToNumberBE:()=>Hp,bytesToNumberLE:()=>oh,concatBytes:()=>Zp,createHmacDrbg:()=>DF,ensureBytes:()=>Zn,equalBytes:()=>She,hexToBytes:()=>qg,hexToNumber:()=>l5,isBytes:()=>rl,numberToBytesBE:()=>nl,numberToBytesLE:()=>zg,numberToHexUnpadded:()=>TF,numberToVarBytesBE:()=>Ehe,utf8ToBytes:()=>The,validateObject:()=>em});SF=BigInt(0),mE=BigInt(1),Phe=BigInt(2);_he=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));cu={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};Ahe=(r,e,t)=>r|(t?mE:SF)<<BigInt(e),u5=r=>(Phe<<BigInt(r-1))-mE,k6=r=>new Uint8Array(r),Jz=r=>Uint8Array.from(r);Ihe={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"||rl(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)};A6=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;I6=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Vd=(r,e)=>r<<32-e|r>>>e,Ohe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ohe)throw new Error("Non little-endian hardware is not supported");CF=class{clone(){return this._cloneInto()}},j9e={}.toString;OF=class extends CF{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=I6(this.buffer)}update(r){rE(this);let{view:e,buffer:t,blockLen:n}=this;r=f5(r);let i=r.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){let a=I6(r);for(;n<=i-s;s+=n)this.process(a,s);continue}t.set(r.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){rE(this),$he(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>n-s&&(this.process(t,0),s=0);for(let c=s;c<n;c++)e[c]=0;Bhe(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=I6(r),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=a/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)o.setUint32(4*c,l[c],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:s,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=s,n%e&&r.buffer.set(t),r}},jhe=(r,e,t)=>r&e^~r&t,Nhe=(r,e,t)=>r&e^r&t^e&t,Mhe=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]),Gf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Wf=new Uint32Array(64),Uhe=class extends OF{constructor(){super(64,32,8,!1),this.A=Gf[0]|0,this.B=Gf[1]|0,this.C=Gf[2]|0,this.D=Gf[3]|0,this.E=Gf[4]|0,this.F=Gf[5]|0,this.G=Gf[6]|0,this.H=Gf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:s,G:o,H:a}=this;return[r,e,t,n,i,s,o,a]}set(r,e,t,n,i,s,o,a){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=s|0,this.G=o|0,this.H=a|0}process(r,e){for(let c=0;c<16;c++,e+=4)Wf[c]=r.getUint32(e,!1);for(let c=16;c<64;c++){let u=Wf[c-15],f=Wf[c-2],h=Vd(u,7)^Vd(u,18)^u>>>3,p=Vd(f,17)^Vd(f,19)^f>>>10;Wf[c]=p+Wf[c-7]+h+Wf[c-16]|0}let{A:t,B:n,C:i,D:s,E:o,F:a,G:d,H:l}=this;for(let c=0;c<64;c++){let u=Vd(o,6)^Vd(o,11)^Vd(o,25),f=l+u+jhe(o,a,d)+Mhe[c]+Wf[c]|0,h=(Vd(t,2)^Vd(t,13)^Vd(t,22))+Nhe(t,n,i)|0;l=d,d=a,a=o,o=s+f|0,s=i,i=n,n=t,t=f+h|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,d=d+this.G|0,l=l+this.H|0,this.set(t,n,i,s,o,a,d,l)}roundClean(){Wf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},BF=$F(()=>new Uhe),xi=BigInt(0),xn=BigInt(1),qp=BigInt(2),Khe=BigInt(3),L6=BigInt(4),Zz=BigInt(5),Qz=BigInt(8),N9e=BigInt(9),Lhe=BigInt(16);Fhe=(r,e)=>(en(r,e)&xn)===xn,Ghe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Zhe=BigInt(0),R6=BigInt(1);({bytesToNumberBE:Xhe,hexToBytes:epe}=EF),Gp={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=Gp;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:Xhe(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Gp,t=typeof r=="string"?epe(r):r;if(!rl(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:s}=Gp._parseInt(t.subarray(2)),{d:o,l:a}=Gp._parseInt(s);if(a.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 c=l.toString(16);return c.length&1?`0${c}`:c},n=e(t(r.s)),i=e(t(r.r)),s=n.length/2,o=i.length/2,a=t(s),d=t(o);return`30${t(o+s+4)}02${d}${i}02${a}${n}`}},pu=BigInt(0),Ja=BigInt(1),M9e=BigInt(2),Xz=BigInt(3),U9e=BigInt(4);LF=class extends CF{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,Che(r);let t=f5(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 s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=r.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(r){return rE(this),this.iHash.update(r),this}digestInto(r){rE(this),kF(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:s,outputLen:o}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=s,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()}},qF=(r,e,t)=>new LF(r,e).update(t).digest();qF.create=(r,e)=>new LF(r,e);FF=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),e7=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ope=BigInt(1),z6=BigInt(2),t7=(r,e)=>(r+e/z6)/e;F6=p5(FF,void 0,void 0,{sqrt:spe}),aa=zF({a:BigInt(0),b:BigInt(7),Fp:F6,n:e7,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=e7,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ope*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=t7(s*r,e),d=t7(-n*r,e),l=en(r-a*t-d*i,e),c=en(-a*n-d*s,e),u=l>o,f=c>o;if(u&&(l=e-l),f&&(c=e-c),l>o||c>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:c}}}},BF),K9e=BigInt(0),L9e=aa.ProjectivePoint;B2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,C6=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Jd=(r,e)=>r<<32-e|r>>>e,q9e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;lpe=class{clone(){return this._cloneInto()}},z9e={}.toString;ppe=(r,e,t)=>r&e^~r&t,mpe=(r,e,t)=>r&e^r&t^e&t,ype=class extends lpe{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=C6(this.buffer)}update(r){r7(this);let{view:e,buffer:t,blockLen:n}=this;r=WF(r);let i=r.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){let a=C6(r);for(;n<=i-s;s+=n)this.process(a,s);continue}t.set(r.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){r7(this),cpe(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>n-s&&(this.process(t,0),s=0);for(let c=s;c<n;c++)e[c]=0;hpe(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=C6(r),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=a/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)o.setUint32(4*c,l[c],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:s,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=s,n%e&&r.buffer.set(t),r}},gpe=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]),Hf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vf=new Uint32Array(64),wpe=class extends ype{constructor(){super(64,32,8,!1),this.A=Hf[0]|0,this.B=Hf[1]|0,this.C=Hf[2]|0,this.D=Hf[3]|0,this.E=Hf[4]|0,this.F=Hf[5]|0,this.G=Hf[6]|0,this.H=Hf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:s,G:o,H:a}=this;return[r,e,t,n,i,s,o,a]}set(r,e,t,n,i,s,o,a){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=s|0,this.G=o|0,this.H=a|0}process(r,e){for(let c=0;c<16;c++,e+=4)Vf[c]=r.getUint32(e,!1);for(let c=16;c<64;c++){let u=Vf[c-15],f=Vf[c-2],h=Jd(u,7)^Jd(u,18)^u>>>3,p=Jd(f,17)^Jd(f,19)^f>>>10;Vf[c]=p+Vf[c-7]+h+Vf[c-16]|0}let{A:t,B:n,C:i,D:s,E:o,F:a,G:d,H:l}=this;for(let c=0;c<64;c++){let u=Jd(o,6)^Jd(o,11)^Jd(o,25),f=l+u+ppe(o,a,d)+gpe[c]+Vf[c]|0,h=(Jd(t,2)^Jd(t,13)^Jd(t,22))+mpe(t,n,i)|0;l=d,d=a,a=o,o=s+f|0,s=i,i=n,n=t,t=f+h|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,d=d+this.G|0,l=l+this.H|0,this.set(t,n,i,s,o,a,d,l)}roundClean(){Vf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Kb=upe(()=>new wpe);bpe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},HF=class{static digest(r){return bpe(this,arguments,void 0,function*({data:e}){return Kb(e)})}},xpe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},n7="urn:jwk:";no=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},_pe=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},ao=class Zd{static adjustSignatureToLowS(e){return no(this,arguments,void 0,function*({signature:t}){let n=aa.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return no(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Zd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Zd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static compressPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){return aa.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return no(this,arguments,void 0,function*({key:t}){let n=yield Zd.privateKeyToBytes({privateKey:t}),i=yield Zd.getCurvePoint({keyBytes:n}),s={kty:"EC",crv:"secp256k1",x:ot.uint8Array(i.x).toBase64Url(),y:ot.uint8Array(i.y).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertDerToCompactSignature(e){return no(this,arguments,void 0,function*({derSignature:t}){return aa.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){return aa.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return no(this,void 0,void 0,function*(){let e=aa.utils.randomPrivateKey(),t=yield Zd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return no(this,arguments,void 0,function*({key:t}){var n;if(!(Vp(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,s=_pe(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return no(this,arguments,void 0,function*({privateKey:t}){if(!Vp(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return no(this,arguments,void 0,function*({publicKey:t}){if(!(y5(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ot.base64Url(t.x).toUint8Array(),s=ot.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...s])})}static sharedSecret(e){return no(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 Zd.privateKeyToBytes({privateKey:t}),s=yield Zd.publicKeyToBytes({publicKey:n});return aa.getSharedSecret(i,s,!0).slice(1)})}static sign(e){return no(this,arguments,void 0,function*({data:t,key:n}){let i=yield Zd.privateKeyToBytes({privateKey:n}),s=Kb(t);return aa.sign(s,i).toCompactRawBytes()})}static validatePrivateKey(e){return no(this,arguments,void 0,function*({privateKeyBytes:t}){return aa.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){try{aa.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return no(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield Zd.publicKeyToBytes({publicKey:t}),o=Kb(i);return aa.verify(n,o,s,{lowS:!1})})}static getCurvePoint(e){return no(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=aa.getPublicKey(t));let n=aa.ProjectivePoint.fromHex(t),i=nl(n.x,32),s=nl(n.y,32);return{x:i,y:s}})}},VF=p5(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Epe=VF.create(BigInt("-3")),Spe=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Tpe=zF({a:Epe,b:Spe,Fp:VF,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},BF),Fa=Tpe,io=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Dpe=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},Ao=class Qd{static adjustSignatureToLowS(e){return io(this,arguments,void 0,function*({signature:t}){let n=Fa.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return io(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Qd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Qd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static compressPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){return Fa.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return io(this,arguments,void 0,function*({key:t}){let n=yield Qd.privateKeyToBytes({privateKey:t}),i=yield Qd.getCurvePoint({keyBytes:n}),s={kty:"EC",crv:"P-256",x:ot.uint8Array(i.x).toBase64Url(),y:ot.uint8Array(i.y).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertDerToCompactSignature(e){return io(this,arguments,void 0,function*({derSignature:t}){return Fa.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){return Fa.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return io(this,void 0,void 0,function*(){let e=Fa.utils.randomPrivateKey(),t=yield Qd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return io(this,arguments,void 0,function*({key:t}){var n;if(!(Vp(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,s=Dpe(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return io(this,arguments,void 0,function*({privateKey:t}){if(!Vp(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return io(this,arguments,void 0,function*({publicKey:t}){if(!(y5(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ot.base64Url(t.x).toUint8Array(),s=ot.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...s])})}static sharedSecret(e){return io(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 Qd.privateKeyToBytes({privateKey:t}),s=yield Qd.publicKeyToBytes({publicKey:n});return Fa.getSharedSecret(i,s,!0).slice(1)})}static sign(e){return io(this,arguments,void 0,function*({data:t,key:n}){let i=yield Qd.privateKeyToBytes({privateKey:n}),s=Kb(t);return Fa.sign(s,i).toCompactRawBytes()})}static validatePrivateKey(e){return io(this,arguments,void 0,function*({privateKeyBytes:t}){return Fa.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){try{Fa.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return io(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield Qd.publicKeyToBytes({publicKey:t}),o=Kb(i);return Fa.verify(n,o,s,{lowS:!1})})}static getCurvePoint(e){return io(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Fa.getPublicKey(t));let n=Fa.ProjectivePoint.fromHex(t),i=nl(n.x,32),s=nl(n.y,32);return{x:i,y:s}})}},du=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},i7=class extends pE{bytesToPrivateKey(r){return du(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ao.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ao.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return du(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ao.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ao.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return du(this,arguments,void 0,function*({key:e}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ao.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield Ao.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return du(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield ao.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield Ao.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return du(this,arguments,void 0,function*({key:e}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ao.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield Ao.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return du(this,arguments,void 0,function*({key:e,data:t}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield ao.sign({key:e,data:t});case"P-256":return yield Ao.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return du(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!y5(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield ao.verify({key:e,signature:t,data:n});case"P-256":return yield Ao.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return du(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield ao.privateKeyToBytes({privateKey:e});case"P-256":return yield Ao.privateKeyToBytes({privateKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return du(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield ao.publicKeyToBytes({publicKey:e});case"P-256":return yield Ao.publicKeyToBytes({publicKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},T2=BigInt(4294967295),G6=BigInt(32);Ape=(r,e)=>BigInt(r>>>0)<<G6|BigInt(e>>>0),Ipe=(r,e,t)=>r>>>t,Rpe=(r,e,t)=>r<<32-t|e>>>t,Cpe=(r,e,t)=>r>>>t|e<<32-t,$pe=(r,e,t)=>r<<32-t|e>>>t,Ope=(r,e,t)=>r<<64-t|e>>>t-32,Bpe=(r,e,t)=>r>>>t-32|e<<64-t,jpe=(r,e)=>e,Npe=(r,e)=>r,Mpe=(r,e,t)=>r<<t|e>>>32-t,Upe=(r,e,t)=>e<<t|r>>>32-t,Kpe=(r,e,t)=>e<<t-32|r>>>64-t,Lpe=(r,e,t)=>r<<t-32|e>>>64-t;zpe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Fpe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gpe=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Wpe=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Hpe=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Vpe=(r,e,t,n,i,s)=>e+t+n+i+s+(r/2**32|0)|0,Jpe={fromBig:JF,split:kpe,toBig:Ape,shrSH:Ipe,shrSL:Rpe,rotrSH:Cpe,rotrSL:$pe,rotrBH:Ope,rotrBL:Bpe,rotr32H:jpe,rotr32L:Npe,rotlSH:Mpe,rotlSL:Upe,rotlBH:Kpe,rotlBL:Lpe,add:qpe,add3L:zpe,add3H:Fpe,add4L:Gpe,add4H:Wpe,add5H:Vpe,add5L:Hpe},Kt=Jpe,[Ype,Zpe]=Kt.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))),Jf=new Uint32Array(80),Yf=new Uint32Array(80),Qpe=class extends OF{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:s,Dh:o,Dl:a,Eh:d,El:l,Fh:c,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[r,e,t,n,i,s,o,a,d,l,c,u,f,h,p,m]}set(r,e,t,n,i,s,o,a,d,l,c,u,f,h,p,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=s|0,this.Dh=o|0,this.Dl=a|0,this.Eh=d|0,this.El=l|0,this.Fh=c|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)Jf[w]=r.getUint32(e),Yf[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let b=Jf[w-15]|0,T=Yf[w-15]|0,D=Kt.rotrSH(b,T,1)^Kt.rotrSH(b,T,8)^Kt.shrSH(b,T,7),I=Kt.rotrSL(b,T,1)^Kt.rotrSL(b,T,8)^Kt.shrSL(b,T,7),M=Jf[w-2]|0,C=Yf[w-2]|0,z=Kt.rotrSH(M,C,19)^Kt.rotrBH(M,C,61)^Kt.shrSH(M,C,6),L=Kt.rotrSL(M,C,19)^Kt.rotrBL(M,C,61)^Kt.shrSL(M,C,6),B=Kt.add4L(I,L,Yf[w-7],Yf[w-16]),H=Kt.add4H(B,D,z,Jf[w-7],Jf[w-16]);Jf[w]=H|0,Yf[w]=B|0}let{Ah:t,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:d,Dl:l,Eh:c,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let b=Kt.rotrSH(c,u,14)^Kt.rotrSH(c,u,18)^Kt.rotrBH(c,u,41),T=Kt.rotrSL(c,u,14)^Kt.rotrSL(c,u,18)^Kt.rotrBL(c,u,41),D=c&f^~c&p,I=u&h^~u&m,M=Kt.add5L(v,T,I,Zpe[w],Yf[w]),C=Kt.add5H(M,y,b,D,Ype[w],Jf[w]),z=M|0,L=Kt.rotrSH(t,n,28)^Kt.rotrBH(t,n,34)^Kt.rotrBH(t,n,39),B=Kt.rotrSL(t,n,28)^Kt.rotrBL(t,n,34)^Kt.rotrBL(t,n,39),H=t&i^t&o^i&o,ee=n&s^n&a^s&a;y=p|0,v=m|0,p=f|0,m=h|0,f=c|0,h=u|0,{h:c,l:u}=Kt.add(d|0,l|0,C|0,z|0),d=o|0,l=a|0,o=i|0,a=s|0,i=t|0,s=n|0;let R=Kt.add3L(z,B,ee);t=Kt.add3H(R,C,L,H),n=R|0}({h:t,l:n}=Kt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:s}=Kt.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:o,l:a}=Kt.add(this.Ch|0,this.Cl|0,o|0,a|0),{h:d,l}=Kt.add(this.Dh|0,this.Dl|0,d|0,l|0),{h:c,l:u}=Kt.add(this.Eh|0,this.El|0,c|0,u|0),{h:f,l:h}=Kt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Kt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:v}=Kt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,s,o,a,d,l,c,u,f,h,p,m,y,v)}roundClean(){Jf.fill(0),Yf.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)}},YF=$F(()=>new Qpe),zc=BigInt(0),oa=BigInt(1),D2=BigInt(2),Xpe=BigInt(8),eme={zip215:!0};yb=BigInt(0),$6=BigInt(1);Lb=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),o7=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),F9e=BigInt(0),ime=BigInt(1),W6=BigInt(2),ome=BigInt(5),s7=BigInt(10),sme=BigInt(20),ame=BigInt(40),a7=BigInt(80);Xa=p5(Lb,void 0,!0),qb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Xa,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:YF,randomBytes:h5,adjustScalarBytes:QF,uvRatio:cme},Kp=w5(qb);G9e=w5({...qb,domain:XF}),W9e=w5({...qb,domain:XF,prehash:YF}),Pb=nme({P:Lb,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=Lb,{pow_p_5_8:t,b2:n}=ZF(r);return en(Dn(t,BigInt(3),e)*n,e)},adjustScalarBytes:QF,randomBytes:h5});ume=(Xa.ORDER+BigInt(3))/BigInt(8),H9e=Xa.pow(W6,ume),V9e=Xa.sqrt(Xa.neg(Xa.ONE)),J9e=(Xa.ORDER-BigInt(5))/BigInt(8),Y9e=BigInt(486662),Z9e=Jhe(Xa,Xa.neg(BigInt(486664))),Q9e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),X9e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eze=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),tze=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),rze=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ga=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},fme=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},co=class th{static bytesToPrivateKey(e){return Ga(this,arguments,void 0,function*({privateKeyBytes:t}){let n=Kp.getPublicKey(t),i={crv:"Ed25519",d:ot.uint8Array(t).toBase64Url(),kty:"OKP",x:ot.uint8Array(n).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return Ga(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:ot.uint8Array(t).toBase64Url()};return n.kid=yield Tr({jwk:n}),n})}static computePublicKey(e){return Ga(this,arguments,void 0,function*({key:t}){let n=yield th.privateKeyToBytes({privateKey:t}),i=Kp.getPublicKey(n),s={kty:"OKP",crv:"Ed25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertPrivateKeyToX25519(e){return Ga(this,arguments,void 0,function*({privateKey:t}){let n=yield th.privateKeyToBytes({privateKey:t}),i=lme(n),s=Pb.getPublicKey(i),o={kty:"OKP",crv:"X25519",d:ot.uint8Array(i).toBase64Url(),x:ot.uint8Array(s).toBase64Url()};return o.kid=yield Tr({jwk:o}),o})}static convertPublicKeyToX25519(e){return Ga(this,arguments,void 0,function*({publicKey:t}){let n=yield th.publicKeyToBytes({publicKey:t});if(!(yield th.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=dme(n),s={kty:"OKP",crv:"X25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static generateKey(){return Ga(this,void 0,void 0,function*(){let e=Kp.utils.randomPrivateKey(),t=yield th.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return Ga(this,arguments,void 0,function*({key:t}){var n;if(!(gu(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,s=fme(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return Ga(this,arguments,void 0,function*({privateKey:t}){if(!gu(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ga(this,arguments,void 0,function*({publicKey:t}){if(!g5(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ot.base64Url(t.x).toUint8Array()})}static sign(e){return Ga(this,arguments,void 0,function*({key:t,data:n}){let i=yield th.privateKeyToBytes({privateKey:t});return Kp.sign(n,i)})}static validatePublicKey(e){return Ga(this,arguments,void 0,function*({publicKeyBytes:t}){try{Kp.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ga(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield th.publicKeyToBytes({publicKey:t});return Kp.verify(n,i,s)})}},lu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},hme=class extends pE{bytesToPrivateKey(r){return lu(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield co.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return lu(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield co.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return lu(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield co.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return lu(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield co.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return lu(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield co.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return lu(this,arguments,void 0,function*({key:e,data:t}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield co.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return lu(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!g5(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield co.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return lu(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield co.privateKeyToBytes({privateKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return lu(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield co.publicKeyToBytes({publicKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},pme=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},mme=class extends pE{digest(r){return pme(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield HF.digest({data:t})}})}},Zf=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},yme=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},Rg=class _b{static bytesToPrivateKey(e){return Zf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=Pb.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return Zf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:ot.uint8Array(t).toBase64Url()};return n.kid=yield Tr({jwk:n}),n})}static computePublicKey(e){return Zf(this,arguments,void 0,function*({key:t}){let n=yield _b.privateKeyToBytes({privateKey:t}),i=Pb.getPublicKey(n),s={kty:"OKP",crv:"X25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static generateKey(){return Zf(this,void 0,void 0,function*(){let e=Pb.utils.randomPrivateKey(),t=yield _b.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return Zf(this,arguments,void 0,function*({key:t}){var n;if(!(gu(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,s=yme(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return Zf(this,arguments,void 0,function*({privateKey:t}){if(!gu(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Zf(this,arguments,void 0,function*({publicKey:t}){if(!g5(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return ot.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return Zf(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 _b.privateKeyToBytes({privateKey:t}),s=yield _b.publicKeyToBytes({publicKey:n});return Pb.getSharedSecret(i,s)})}},gb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},gme=class extends pE{bytesToPrivateKey(r){return gb(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Rg.bytesToPrivateKey({privateKeyBytes:t});default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return gb(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Rg.computePublicKey({key:e});default:throw new Qa(ks.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return gb(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Rg.generateKey();default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return gb(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Rg.getPublicKey({key:e});default:throw new Qa(ks.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return gb(this,arguments,void 0,function*({privateKey:e}){return Rg.privateKeyToBytes({privateKey:e})})}},uu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},O6={Ed25519:{implementation:hme,names:["Ed25519"]},secp256k1:{implementation:i7,names:["ES256K","secp256k1"]},secp256r1:{implementation:i7,names:["ES256","secp256r1"]},"SHA-256":{implementation:mme,names:["SHA-256"]},X25519:{implementation:gme,names:["X25519"]}},Wc=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new fhe}digest(r){return uu(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return uu(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return uu(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=`${n7}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return uu(this,arguments,void 0,function*({key:e}){let t=yield Tr({jwk:e});return`${n7}${t}`})}getPublicKey(r){return uu(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 uu(this,arguments,void 0,function*({key:e}){var t;if(!Ppe(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 Tr({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return uu(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 uu(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=O6[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 O6){let i=O6[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 uu(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})}},wme=class eG{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 fpe(e)}static randomUuid(){return B2.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),n=Math.ceil(Math.log2(t)/8),i=Math.pow(2,n*8),s=i-i%t,o;do{o=0;let a=eG.randomBytes(n);for(let d of a)o=o*256+d}while(o>=s);return(o%t).toString().padStart(e,"0")}},vme=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];_e=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}};_e.uint=new _e(0,"uint",!0);_e.negint=new _e(1,"negint",!0);_e.bytes=new _e(2,"bytes",!0);_e.string=new _e(3,"string",!0);_e.array=new _e(4,"array",!1);_e.map=new _e(5,"map",!1);_e.tag=new _e(6,"tag",!1);_e.float=new _e(7,"float",!0);_e.false=new _e(7,"false",!0);_e.true=new _e(7,"true",!0);_e.null=new _e(7,"null",!0);_e.undefined=new _e(7,"undefined",!0);_e.break=new _e(7,"break",!0);nt=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}`}},Vb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Pme=new TextEncoder;_me=24,Eme=200,Sme=Vb?r=>r.length>=_me?globalThis.Buffer.from(r):c7(r):r=>r.length>=Eme?Pme.encode(r):c7(r),fu=r=>Uint8Array.from(r),Tme=Vb?(r,e,t)=>nE(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Dme=Vb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),tG(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},kme=Vb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);Ame=256,nG=class{constructor(r=Ame){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=kme(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=Tme(t,0,this.cursor)}else e=Dme(this.chunks,this.cursor);return r&&this.reset(),e}},Ime=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:",iG="CBOR encode error:",Jb=[];Jb[23]=1;Jb[24]=2;Jb[25]=3;Jb[26]=5;Jb[27]=9;lo=[24,256,65536,4294967296,BigInt("18446744073709551616")];om.encodedSize=function(r){return tc.encodedSize(r.value)};tc.encodedSize=function(r){return r<lo[0]?1:r<lo[1]?2:r<lo[2]?3:r<lo[3]?5:9};om.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};v5=BigInt(-1),oG=BigInt(1);b5.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*v5-oG:e*-1-1;return t<lo[0]?1:t<lo[1]?2:t<lo[2]?3:t<lo[3]?5:9};b5.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};yE.encodedSize=function(r){let e=iE(r);return tc.encodedSize(e.length)+e.length};yE.compareTokens=function(r,e){return Fme(iE(r),iE(e))};d7=new TextDecoder,Gme=32;Qme=yE;x5.compareTokens=om.compareTokens;x5.encodedSize=function(r){return tc.encodedSize(r.value)};P5.compareTokens=om.compareTokens;P5.encodedSize=function(r){return tc.encodedSize(r.value)};_5.compareTokens=om.compareTokens;_5.encodedSize=function(r){return tc.encodedSize(r.value)};sG=20,aG=21,cG=22,dG=23;S5.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){uG(t);let n=T5(Fc,1);if(t===n||Number.isNaN(t))return 3;if(fG(t),n=D5(Fc,1),t===n)return 5}return 9};lG=new ArrayBuffer(9),Ha=new DataView(lG,1),Fc=new Uint8Array(lG,0);S5.compareTokens=om.compareTokens;Be=[];for(let r=0;r<=23;r++)Be[r]=mr;Be[24]=Rme;Be[25]=Cme;Be[26]=$me;Be[27]=Ome;Be[28]=mr;Be[29]=mr;Be[30]=mr;Be[31]=mr;for(let r=32;r<=55;r++)Be[r]=mr;Be[56]=Bme;Be[57]=jme;Be[58]=Nme;Be[59]=Mme;Be[60]=mr;Be[61]=mr;Be[62]=mr;Be[63]=mr;for(let r=64;r<=87;r++)Be[r]=Ume;Be[88]=Kme;Be[89]=Lme;Be[90]=qme;Be[91]=zme;Be[92]=mr;Be[93]=mr;Be[94]=mr;Be[95]=gE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Be[r]=Hme;Be[120]=Vme;Be[121]=Jme;Be[122]=Yme;Be[123]=Zme;Be[124]=mr;Be[125]=mr;Be[126]=mr;Be[127]=gE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Be[r]=Xme;Be[152]=eye;Be[153]=tye;Be[154]=rye;Be[155]=nye;Be[156]=mr;Be[157]=mr;Be[158]=mr;Be[159]=iye;for(let r=160;r<=183;r++)Be[r]=oye;Be[184]=sye;Be[185]=aye;Be[186]=cye;Be[187]=dye;Be[188]=mr;Be[189]=mr;Be[190]=mr;Be[191]=lye;for(let r=192;r<=215;r++)Be[r]=uye;Be[216]=fye;Be[217]=hye;Be[218]=pye;Be[219]=mye;Be[220]=mr;Be[221]=mr;Be[222]=mr;Be[223]=mr;for(let r=224;r<=243;r++)Be[r]=gE("simple values are not supported");Be[244]=mr;Be[245]=mr;Be[246]=mr;Be[247]=yye;Be[248]=gE("simple values are not supported");Be[249]=wye;Be[250]=vye;Be[251]=bye;Be[252]=mr;Be[253]=mr;Be[254]=mr;Be[255]=gye;vu=[];for(let r=0;r<24;r++)vu[r]=new nt(_e.uint,r,1);for(let r=-1;r>=-24;r--)vu[31-r]=new nt(_e.negint,r,1);vu[64]=new nt(_e.bytes,new Uint8Array(0),1);vu[96]=new nt(_e.string,"",1);vu[128]=new nt(_e.array,0,1);vu[160]=new nt(_e.map,0,1);vu[244]=new nt(_e.false,!1,1);vu[245]=new nt(_e.true,!0,1);vu[246]=new nt(_e.null,null,1);_ye=Object.freeze({float64:!0,mapSorter:kye,quickEncodeToken:Pye});Sye=Eye(),Tye=new nG,l7=class pG{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(`${iG} object contains circular references`);return new pG(t,e)}},Qf={null:new nt(_e.null,null),undefined:new nt(_e.undefined,void 0),true:new nt(_e.true,!0),false:new nt(_e.false,!1),emptyArray:new nt(_e.array,0),emptyMap:new nt(_e.map,0)},ah={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new nt(_e.float,r):r>=0?new nt(_e.uint,r):new nt(_e.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new nt(_e.uint,r):new nt(_e.negint,r)},Uint8Array(r,e,t,n){return new nt(_e.bytes,r)},string(r,e,t,n){return new nt(_e.string,r)},boolean(r,e,t,n){return r?Qf.true:Qf.false},null(r,e,t,n){return Qf.null},undefined(r,e,t,n){return Qf.undefined},ArrayBuffer(r,e,t,n){return new nt(_e.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new nt(_e.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Qf.emptyArray,new nt(_e.break)]:Qf.emptyArray;n=l7.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=j2(o,t,n);return t.addBreakTokens?[new nt(_e.array,r.length),i,new nt(_e.break)]:[new nt(_e.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length,a;if(o){a=new Array(o),n=l7.createCheck(n,r);let d=!i&&t.ignoreUndefinedProperties,l=0;for(let c of s){let u=i?r.get(c):r[c];d&&u===void 0||(a[l++]=[j2(c,t,n),j2(u,t,n)])}l<o&&(a.length=l)}return a?.length?(Dye(a,t),t.addBreakTokens?[new nt(_e.map,a.length),a,new nt(_e.break)]:[new nt(_e.map,a.length),a]):t.addBreakTokens===!0?[Qf.emptyMap,new nt(_e.break)]:Qf.emptyMap}};ah.Map=ah.Object;ah.Buffer=ah.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ah[`${r}Array`]=ah.DataView;nze=_e.uint.majorEncoded,ize=_e.negint.majorEncoded,oze=_e.bytes.majorEncoded,sze=_e.string.majorEncoded,aze=_e.array.majorEncoded,cze=_e.float.majorEncoded|sG,dze=_e.float.majorEncoded|aG,lze=_e.float.majorEncoded|cG,uze=_e.float.majorEncoded|dG,fze=BigInt(-1),hze=BigInt(1);pze=Symbol.for("DONE"),mze=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(f7||(f7={}));(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"})(Io||(Io={}));(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"})(Za||(Za={}));(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"})(h7||(h7={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(p7||(p7={}));yze={"P-256":Io.P256,"P-384":Io.P384,"P-521":Io.P521,X25519:Io.X25519,Ed25519:Io.Ed25519,Ed448:Io.Ed448,secp256k1:Io.Secp256k1},gze={[Io.P256]:"P-256",[Io.P384]:"P-384",[Io.P521]:"P-521",[Io.X25519]:"X25519",[Io.Ed25519]:"Ed25519",[Io.Ed448]:"Ed448",[Io.Secp256k1]:"secp256k1"},wze={EdDSA:Za.EdDSA,ES256:Za.ES256,ES384:Za.ES384,ES512:Za.ES512,ES256K:Za.ES256K},vze={[Za.EdDSA]:"EdDSA",[Za.ES256]:"ES256",[Za.ES384]:"ES384",[Za.ES512]:"ES512",[Za.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(m7||(m7={}));(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"})(y7||(y7={}));(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"})(g7||(g7={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(w7||(w7={}));k5={};o5(k5,{extractDidFragment:()=>rs,getServices:()=>Iye,getVerificationMethodByKey:()=>Rye,getVerificationMethodTypes:()=>yG,getVerificationMethods:()=>wE,getVerificationRelationshipsById:()=>gG,isDidService:()=>wG,isDidVerificationMethod:()=>oE,isDwnDidService:()=>Cye,isPortableDid:()=>Zg,keyBytesToMultibaseId:()=>vG,multibaseIdToKeyBytes:()=>bG});Ro=class xG{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}),s=await this.keyManager.exportKey({keyUri:i});t.push({...s})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(o=>rs(o.id)===(rs(e?.methodId)??rs(this.document.assertionMethod?.[0])));if(!t?.publicKeyJwk)throw new rt("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}),s=this.keyManager;return{algorithm:wme.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:o}){return await s.sign({data:o,keyUri:n})},async verify({data:o,signature:a}){return await s.verify({data:o,key:i,signature:a})}}}static async import({portableDid:e,keyManager:t=new Wc}){let n=wE({didDocument:e.document});if(n.length===0)throw new rt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let s=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:s}).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 s=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:s})}return new xG({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},Qb=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()")}},PG=(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))(PG||{}),A5=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(A5||{}),_G=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(_G||{}),v7="0123456789abcdef",EG=[],b7=[];for(let r=0;r<256;r++)EG[r]=v7[r>>4&15]+v7[r&15],r<16&&(r<10?b7[48+r]=r:b7[87+r]=r);$ye=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=EG[r[n++]];return t},Oye=(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,s=t;for(;s--;)i-=r[s].length,n.set(r[s],i);return n},x7="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bye=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(wb=0;wb<x7.length;wb++)Bye[x7.charCodeAt(wb)]=wb;jye=new TextDecoder,SG=(r,e)=>e?new TextDecoder(e).decode(r):jye.decode(r),Nye=new TextEncoder,wu=r=>Nye.encode(r),P7=typeof window<"u"?window:self,_7=P7.crypto||P7.msCrypto||{},bze=_7.subtle||_7.webkitSubtle;br.bytes=-1;br._floatConversionDetected=!1;br._encode=function(r,e){if(e!=null)switch(TG(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}};vE=new Uint8Array([101]),DG=new Uint8Array([100]),kG=new Uint8Array([108]);br.buffer=function(r,e){r.push(wu(e.length+":"),e)};br.string=function(r,e){r.push(wu(wu(e).byteLength+":"+e))};br.number=function(r,e){if(Number.isInteger(e))return r.push(wu("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,s=n*t+i;r.push(wu("i"+s+"e")),s!==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 "'+s+'"'),console.trace())};br.dict=function(r,e){r.push(DG);let t=0,n,i=Object.keys(e).sort(),s=i.length;for(;t<s;t++)n=i[t],e[n]!=null&&(br.string(r,n),br._encode(r,e[n]));r.push(vE)};br.dictMap=function(r,e){r.push(DG);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(vE)};br.list=function(r,e){let t=0,n=e.length;for(r.push(kG);t<n;t++)e[t]!=null&&br._encode(r,e[t]);r.push(vE)};br.listSet=function(r,e){r.push(kG);for(let t of e)t!=null&&br._encode(r,t);r.push(vE)};Mye=br,Uye=105,Kye=58,Lye=100,qye=108,I5=101;vt.bytes=0;vt.position=0;vt.data=null;vt.encoding=null;vt.next=function(){switch(vt.data[vt.position]){case Lye:return vt.dictionary();case qye:return vt.list();case Uye:return vt.integer();default:return vt.buffer()}};vt.find=function(r){let e=vt.position,t=vt.data.length,n=vt.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)+"]")};vt.dictionary=function(){vt.position++;let r={};for(;vt.data[vt.position]!==I5;){let e=vt.buffer(),t=SG(e);t.includes("\uFFFD")&&(t=$ye(e)),r[t]=vt.next()}return vt.position++,r};vt.list=function(){vt.position++;let r=[];for(;vt.data[vt.position]!==I5;)r.push(vt.next());return vt.position++,r};vt.integer=function(){let r=vt.find(I5),e=AG(vt.data,vt.position+1,r);return vt.position+=r+1-vt.position,e};vt.buffer=function(){let r=vt.find(Kye),e=AG(vt.data,vt.position,r),t=++r+e;return vt.position=t,vt.encoding?SG(vt.data.slice(r,t)):vt.data.slice(r,t)};zye=vt;IG=bE,Jye=IG,RG={encode:Mye,decode:zye,byteLength:IG,encodingLength:Jye},Yye=/^(\d{1,3}\.){3,3}\d{1,3}$/,Zye=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,tl={name:"v4",size:4,isFormat:r=>Yye.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let s=0;s<n;){let o=r.charCodeAt(s++);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]}`}},sh={name:"v6",size:16,isFormat:r=>r.length>0&&Zye.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,s=0,o=0,a=!0,d=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let c=r.charCodeAt(l);c===58?(a?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(d===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=s>>8),t<n-1&&(e[t+1]=s&255),t+=2),s=0,o=0),a=!0,d=!1):c===46?(t<n&&(e[t]=o),t++,o=0,s=0,a=!1,d=!0):(a=!1,c>=97?c-=87:c>=65?c-=55:(c-=48,o=o*10+c),s=(s<<4)+c)}if(a===!1)d===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=s>>8),t<n-1&&(e[t+1]=s&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}/,"::")}};Fb.bytes=0;e1.bytes=0;Qp=r=>r instanceof Uint8Array;Eb={},jG=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),s=i.toUpperCase(),o=r<<4|n,a=`${e}${i}`;jG[o]=a,Eb[a]=o,Eb[`${t}${i}`]=o,Eb[`${e}${s}`]=o,Eb[`${t}${s}`]=o}}sge=Math.pow(2,24),age=Math.pow(2,16),cge=Math.pow(2,8),mu=(r,e)=>r[e]*sge+r[e+1]*age+r[e+2]*cge+r[e+3],Lt=(r,e)=>r[e]<<8|r[e+1],yu=(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),st=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);lge=0,T7=32768,H6=32768,uge=~H6,NG=32768,fge=~NG;Ve=Hr({encode(r,e,t){e||(e=new Uint8Array(Ve.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let s=i.split(".");for(let o=0;o<s.length;o++){let a=C5(e,s[o],t+1);e[t]=a,t+=a+1}}return e[t++]=0,Ve.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,s=0,o=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let a=r[e++];if(s+=o?0:1,a===0)break;if(a&192)if((a&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let d=Lt(r,e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,s+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+a>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=a+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(e1(r,e,e+a)),e+=a,s+=o?0:a}}return Ve.decode.bytes=s,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:ch(r.replace(/^\.|\.$/gm,""))+2}}),bi=Hr({encode(r,e,t){e||(e=new Uint8Array(bi.encodingLength(r))),t||(t=0);let n=C5(e,r,t+1);return e[t]=n,bi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=e1(r,e+1,e+1+t);return bi.decode.bytes=t+1,n},encodingLength(r){return ch(r)+1}}),Cg=Hr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(Cg.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?T7:lge;return st(e,r.id||0,t),st(e,n|i,t+2),st(e,r.questions.length,t+4),st(e,r.answers.length,t+6),st(e,r.authorities.length,t+8),st(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=Lt(r,e+2);return{id:Lt(r,e),type:t&T7?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:rge(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:tge(t&15),questions:new Array(Lt(r,e+4)),answers:new Array(Lt(r,e+6)),authorities:new Array(Lt(r,e+8)),additionals:new Array(Lt(r,e+10))}},encodingLength(){return 12}}),N2=Hr({encode(r,e,t){e||(e=new Uint8Array(N2.encodingLength(r))),t||(t=0);let n=r.length;return st(e,n,t),la(r,e,t+2,0,n),N2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n=r.slice(e+2,e+2+t);return N2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),M2=Hr({encode(r,e,t){return e||(e=new Uint8Array(M2.encodingLength(r))),t||(t=0),Ve.encode(r,e,t+2),st(e,Ve.encode.bytes,t),M2.encode.bytes=Ve.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n=Ve.decode(r,e+2);return M2.decode.bytes=t+2,n},encodingLength(r){return Ve.encodingLength(r)+2}}),U2=Hr({encode(r,e,t){e||(e=new Uint8Array(U2.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.mname,e,t),t+=Ve.encode.bytes,Ve.encode(r.rname,e,t),t+=Ve.encode.bytes,yu(e,r.serial||0,t),t+=4,yu(e,r.refresh||0,t),t+=4,yu(e,r.retry||0,t),t+=4,yu(e,r.expire||0,t),t+=4,yu(e,r.minimum||0,t),t+=4,st(e,t-n-2,n),U2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=Ve.decode(r,e),e+=Ve.decode.bytes,n.rname=Ve.decode(r,e),e+=Ve.decode.bytes,n.serial=mu(r,e),e+=4,n.refresh=mu(r,e),e+=4,n.retry=mu(r,e),e+=4,n.expire=mu(r,e),e+=4,n.minimum=mu(r,e),e+=4,U2.decode.bytes=e-t,n},encodingLength(r){return 22+Ve.encodingLength(r.mname)+Ve.encodingLength(r.rname)}}),K2=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]=R5(r[i])),!Qp(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(K2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,la(i,e,t,0,i.length),t+=i.length}),st(e,t-n-2,n),K2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Lt(r,e);e+=2;let i=[];for(;n>0;){let s=r[e++];if(--n,n<s)throw new Error("Buffer overflow");i.push(r.slice(e,e+s)),e+=s,n-=s}return K2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=ch(t)+1:e+=t.length+1}),e}}),L2=Hr({encode(r,e,t){e||(e=new Uint8Array(L2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=R5(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return la(r,e,t,0,i),t+=i,st(e,t-n-2,n),L2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Lt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,L2.decode.bytes=e-t,i},encodingLength(r){return r?(Qp(r)?r.length:ch(r))+2:2}}),q2=Hr({encode(r,e,t){e||(e=new Uint8Array(q2.encodingLength(r))),t||(t=0);let n=t;return t+=2,bi.encode(r.cpu,e,t),t+=bi.encode.bytes,bi.encode(r.os,e,t),t+=bi.encode.bytes,st(e,t-n-2,n),q2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=bi.decode(r,e),e+=bi.decode.bytes,n.os=bi.decode(r,e),e+=bi.decode.bytes,q2.decode.bytes=e-t,n},encodingLength(r){return bi.encodingLength(r.cpu)+bi.encodingLength(r.os)+2}}),Ug=Hr({encode(r,e,t){return e||(e=new Uint8Array(Ug.encodingLength(r))),t||(t=0),Ve.encode(r,e,t+2),st(e,Ve.encode.bytes,t),Ug.encode.bytes=Ve.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Ve.decode(r,e+2);return Ug.decode.bytes=Ve.decode.bytes+2,t},encodingLength(r){return Ve.encodingLength(r)+2}}),z2=Hr({encode(r,e,t){e||(e=new Uint8Array(z2.encodingLength(r))),t||(t=0),st(e,r.priority||0,t+2),st(e,r.weight||0,t+4),st(e,r.port||0,t+6),Ve.encode(r.target,e,t+8);let n=Ve.encode.bytes+6;return st(e,n,t),z2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n={};return n.priority=Lt(r,e+2),n.weight=Lt(r,e+4),n.port=Lt(r,e+6),n.target=Ve.decode(r,e+8),z2.decode.bytes=t+2,n},encodingLength(r){return 8+Ve.encodingLength(r.target)}}),nh=Hr({encode(r,e,t){let n=nh.encodingLength(r);return e||(e=new Uint8Array(nh.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=nh.ISSUER_CRITICAL),st(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,bi.encode(r.tag,e,t),t+=bi.encode.bytes,C5(e,r.value,t),t+=ch(r.value),nh.encode.bytes=n,e},decode(r,e){e||(e=0);let t=Lt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=bi.decode(r,e),e+=bi.decode.bytes,i.value=e1(r,e,n+t),i.issuerCritical=!!(i.flags&nh.ISSUER_CRITICAL),nh.decode.bytes=t+2,i},encodingLength(r){return bi.encodingLength(r.tag)+bi.encodingLength(r.value)+2}});nh.ISSUER_CRITICAL=128;F2=Hr({encode(r,e,t){e||(e=new Uint8Array(F2.encodingLength(r))),t||(t=0);let n=t;return t+=2,st(e,r.preference||0,t),t+=2,Ve.encode(r.exchange,e,t),t+=Ve.encode.bytes,st(e,t-n-2,n),F2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=Lt(r,e),e+=2,n.exchange=Ve.decode(r,e),e+=Ve.decode.bytes,F2.decode.bytes=e-t,n},encodingLength(r){return 4+Ve.encodingLength(r.exchange)}}),MG=Hr({encode(r,e,t){return e||(e=new Uint8Array(MG.encodingLength(r))),t||(t=0),st(e,4,t),t+=2,tl.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,tl.decode(r,e)},bytes:6}),G2=Hr({encode(r,e,t){return e||(e=new Uint8Array(G2.encodingLength(r))),t||(t=0),st(e,16,t),t+=2,sh.encode(r,e,t),G2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=sh.decode(r,e);return G2.decode.bytes=18,t},bytes:18}),D7=r=>new Uint8Array(r),hu=Hr({encode(r,e,t){e||(e=new Uint8Array(hu.encodingLength(r))),t||(t=0);let n=t,i=E7(r.code);if(st(e,i,t),t+=2,r.data)st(e,r.data.length,t),t+=2,la(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let s=r.sourcePrefixLength||0,o=r.family||Qye(r.ip,D7),a=Xye(r.ip,D7),d=Math.ceil(s/8);st(e,d+4,t),t+=2,st(e,o,t),t+=2,e[t++]=s,e[t++]=r.scopePrefixLength||0,la(a,e,t,0,d),t+=d}break;case 11:r.timeout?(st(e,2,t),t+=2,st(e,r.timeout,t),t+=2):(st(e,0,t),t+=2);break;case 12:{let s=r.length||0;st(e,s,t),t+=2,e.fill(0,t,t+s),t+=s}break;case 14:{let s=r.tags.length*2;st(e,s,t),t+=2;for(let o of r.tags)st(e,o,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return hu.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=Lt(r,e),t.type=nge(t.code),e+=2;let n=Lt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=Lt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);la(r,i,0,e,e+n-4),t.ip=ege(i)}break;case 11:n>0&&(t.timeout=Lt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(Lt(r,e)),e+=2}return hu.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(E7(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}`)}}),ih=Hr({encode(r,e,t){e||(e=new Uint8Array(ih.encodingLength(r))),t||(t=0);let n=t,i=Ng(r,hu);return st(e,i,t),t=Ib(r,hu,e,t+2),ih.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=Lt(r,e);e+=2;let s=0;for(;i>0;)n[s++]=hu.decode(r,e),e+=hu.decode.bytes,i-=hu.decode.bytes;return ih.decode.bytes=e-t,n},encodingLength(r){return 2+Ng(r||[],hu)}}),el=Hr({encode(r,e,t){e||(e=new Uint8Array(el.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!Qp(i))throw new Error("Key must be a Buffer");return t+=2,st(e,r.flags,t),t+=2,e[t]=el.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,la(i,e,t,0,i.length),t+=i.length,el.encode.bytes=t-n,st(e,el.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);if(e+=2,n.flags=Lt(r,e),e+=2,r[e]!==el.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,el.decode.bytes=e-t,n},encodingLength(r){return 6+ch(r.key)}});el.PROTOCOL_DNSSEC=3;el.ZONE_KEY=128;el.SECURE_ENTRYPOINT=32768;Sb=Hr({encode(r,e,t){e||(e=new Uint8Array(Sb.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!Qp(i))throw new Error("Signature must be a Buffer");return t+=2,st(e,zb(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,yu(e,r.originalTTL,t),t+=4,yu(e,r.expiration,t),t+=4,yu(e,r.inception,t),t+=4,st(e,r.keyTag,t),t+=2,Ve.encode(r.signersName,e,t),t+=Ve.encode.bytes,la(i,e,t,0,i.length),t+=i.length,Sb.encode.bytes=t-n,st(e,Sb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.typeCovered=xE(Lt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=mu(r,e),e+=4,n.expiration=mu(r,e),e+=4,n.inception=mu(r,e),e+=4,n.keyTag=Lt(r,e),e+=2,n.signersName=Ve.decode(r,e),e+=Ve.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,Sb.decode.bytes=e-t,n},encodingLength(r){return 20+Ve.encodingLength(r.signersName)+ch(r.signature)}}),Tb=Hr({encode(r,e,t){e||(e=new Uint8Array(Tb.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.mbox||".",e,t),t+=Ve.encode.bytes,Ve.encode(r.txt||".",e,t),t+=Ve.encode.bytes,Tb.encode.bytes=t-n,st(e,Tb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=Ve.decode(r,e)||".",e+=Ve.decode.bytes,n.txt=Ve.decode(r,e)||".",e+=Ve.decode.bytes,Tb.decode.bytes=e-t,n},encodingLength(r){return 2+Ve.encodingLength(r.mbox||".")+Ve.encodingLength(r.txt||".")}}),da=Hr({encode(r,e,t){e||(e=new Uint8Array(da.encodingLength(r))),t||(t=0);let n=t,i=[];for(let s=0;s<r.length;s++){let o=zb(r[s]);i[o>>8]===void 0&&(i[o>>8]=[]),i[o>>8][o>>3&31]|=1<<7-(o&7)}for(let s=0;s<i.length;s++)if(i[s]!==void 0){let o=R5(i[s]);e[t]=s,t+=1,e[t]=o.length,t+=1,la(o,e,t,0,o.length),t+=o.length}return da.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let s=r[e];e+=1;let o=r[e];e+=1;for(let a=0;a<o;a++){let d=r[e+a];for(let l=0;l<8;l++)if(d&1<<7-l){let c=xE(s<<8|a<<3|l);i.push(c)}}e+=o}return da.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=zb(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}}),Db=Hr({encode(r,e,t){e||(e=new Uint8Array(Db.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.nextDomain,e,t),t+=Ve.encode.bytes,da.encode(r.rrtypes,e,t),t+=da.encode.bytes,Db.encode.bytes=t-n,st(e,Db.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.nextDomain=Ve.decode(r,e),e+=Ve.decode.bytes,n.rrtypes=da.decode(r,e,i-(e-t)),e+=da.decode.bytes,Db.decode.bytes=e-t,n},encodingLength(r){return 2+Ve.encodingLength(r.nextDomain)+da.encodingLength(r.rrtypes)}}),kb=Hr({encode(r,e,t){e||(e=new Uint8Array(kb.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!Qp(i))throw new Error("salt must be a Buffer");let s=r.nextDomain;if(!Qp(s))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,st(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,la(i,e,t,0,i.length),t+=i.length,e[t]=s.length,t+=1,la(s,e,t,0,s.length),t+=s.length,da.encode(r.rrtypes,e,t),t+=da.encode.bytes,kb.encode.bytes=t-n,st(e,kb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=Lt(r,e),e+=2;let s=r[e];e+=1,n.salt=r.slice(e,e+s),e+=s;let o=r[e];return e+=1,n.nextDomain=r.slice(e,e+o),e+=o,n.rrtypes=da.decode(r,e,i-(e-t)),e+=da.decode.bytes,kb.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+da.encodingLength(r.rrtypes)}}),Ab=Hr({encode(r,e,t){e||(e=new Uint8Array(Ab.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!Qp(i))throw new Error("Digest must be a Buffer");return t+=2,st(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,la(i,e,t,0,i.length),t+=i.length,Ab.encode.bytes=t-n,st(e,Ab.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.keyTag=Lt(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,Ab.decode.bytes=e-t,n},encodingLength(r){return 6+ch(r.digest)}}),jg=Hr({encode(r,e,t){e||(e=new Uint8Array(jg.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=S7(r.fingerprint),s=V6(r.hash);if(i!==s)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${s}`);return oge(e,r.fingerprint,t,t+=i),jg.encode.bytes=t-n,st(e,jg.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=V6(n.hash);return n.fingerprint=ige(r,e,e+i),e+=i,jg.decode.bytes=e-t,n},encodingLength(r){return 4+S7(r.fingerprint)}});jg.getFingerprintLengthForHashType=V6;Va=Hr({encode(r,e,t){e||(e=new Uint8Array(Va.encodingLength(r))),t||(t=0);let n=t;if(Ve.encode(r.name,e,t),t+=Ve.encode.bytes,st(e,zb(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");st(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,st(e,r.flags||0,t+6),t+=8,ih.encode(r.options||[],e,t),t+=ih.encode.bytes}else{let i=OG(r.class===void 0?"IN":r.class);r.flush&&(i|=H6),st(e,i,t+2),yu(e,r.ttl||0,t+4),t+=8;let s=B6(r.type);s.encode(r.data,e,t),t+=s.encode.bytes}return Va.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=Ve.decode(r,e),e+=Ve.decode.bytes,t.type=xE(Lt(r,e)),t.type==="OPT")t.udpPayloadSize=Lt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=Lt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=ih.decode(r,e+8),e+=8+ih.decode.bytes;else{let i=Lt(r,e+2);t.ttl=mu(r,e+4),t.class=$G(i&uge),t.flush=!!(i&H6);let s=B6(t.type);t.data=s.decode(r,e+8),e+=8+s.decode.bytes}return Va.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return Ve.encodingLength(r.name)+8+B6(r.type).encodingLength(e)}}),Kg=Hr({encode(r,e,t){e||(e=new Uint8Array(Kg.encodingLength(r))),t||(t=0);let n=t;return Ve.encode(r.name,e,t),t+=Ve.encode.bytes,st(e,zb(r.type),t),t+=2,st(e,OG(r.class===void 0?"IN":r.class),t),t+=2,Kg.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=Ve.decode(r,e),e+=Ve.decode.bytes,n.type=xE(Lt(r,e)),e+=2,n.class=$G(Lt(r,e)),e+=2,n.class&NG&&(n.class&=fge),Kg.decode.bytes=e-t,n},encodingLength(r){return Ve.encodingLength(r.name)+4}}),hge=1024,uo={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(pge(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),Cg.encode(r,e,t),t+=Cg.encode.bytes,t=Ib(r.questions,Kg,e,t),t=Ib(r.answers,Va,e,t),t=Ib(r.authorities,Va,e,t),t=Ib(r.additionals,Va,e,t),uo.encode.bytes=t-i,n&&dE.bytes!==e.length?e.slice(0,dE.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=Cg.decode(r,e);return e+=Cg.decode.bytes,e=k2(n.questions,Kg,r,e),e=k2(n.answers,Va,r,e),e=k2(n.authorities,Va,r,e),e=k2(n.additionals,Va,r,e),uo.decode.bytes=e-t,n},encodingLength:function(r){return Cg.encodingLength(r)+Ng(r.questions||[],Kg)+Ng(r.answers||[],Va)+Ng(r.authorities||[],Va)+Ng(r.additionals||[],Va)}};uo.encode.bytes=0;uo.decode.bytes=0;aE={encode:function(r,e,t){return e=uo.encode(sE(r,"query"),e,t),aE.encode.bytes=uo.encode.bytes,e},decode:function(r,e){let t=uo.decode(r,e);return aE.decode.bytes=uo.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return uo.encodingLength(sE(r,"query"))}};aE.encode.bytes=0;aE.decode.bytes=0;cE={encode:function(r,e,t){return e=uo.encode(sE(r,"response"),e,t),cE.encode.bytes=uo.encode.bytes,e},decode:function(r,e){let t=uo.decode(r,e);return cE.decode.bytes=uo.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return uo.encodingLength(sE(r,"response"))}};cE.encode.bytes=0;cE.decode.bytes=0;dE=uo.encode,J6=uo.decode,pge=uo.encodingLength;UG.bytes=0;KG.bytes=0;zG="dht";bge=0,Xf=7200,W2=";",ts=",",WG={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},HG={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};_ge="https://enbox-did-dht.fly.dev";JG=class Y6 extends Qb{static async create({keyManager:e=new Wc,options:t={}}={}){if(t.verificationMethods?.some(c=>!(c.algorithm in WG)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(c=>"id"in c).map(c=>c.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(c=>!c.id||!c.type||!c.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),s=await e.getPublicKey({keyUri:i}),o=await Mg.identityKeyToIdentifier({identityKey:s}),a={id:o,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},d=[...t.verificationMethods??[]];d?.some(c=>c.id?.split("#").pop()==="0")||d.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let c of d){let u=c.id?.split("#").pop()==="0"?i:await e.generateKey({algorithm:c.algorithm}),f=await e.getPublicKey({keyUri:u}),h=c.id??f.kid??await Tr({jwk:f});h=`${o}#${rs(h)}`,a.verificationMethod??=[],a.verificationMethod.push({id:h,type:"JsonWebKey",controller:c.controller??o,publicKeyJwk:f});for(let p of c.purposes??[])a[p]??=[],a[p].push(h)}t.services?.forEach(c=>{a.service??=[],c.id=`${o}#${c.id.split("#").pop()}`,a.service.push(c)});let l=new Ro({uri:o,document:a,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let c=await Y6.publish({did:l,gatewayUri:t.gatewayUri,allowPrivateGatewayUri:t.allowPrivateGatewayUri});l.metadata=c.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Wc}){if(Qn.parse(e.uri)?.method!==Y6.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new rt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(s=>rs(s.id)===(rs(t)??rs(e.assertionMethod?.[0])));if(!i?.publicKeyJwk)throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t,allowPrivateGatewayUri:n}){let i=A7(t,n);return I7.put({did:e,...i})}static async resolve(e,t={}){let{gatewayUri:n,allowPrivateGatewayUri:i}=A7(t.gatewayUri,t.allowPrivateGatewayUri);try{await Mg.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:o}=await I7.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:i});return{...fo,didDocument:s,didDocumentMetadata:o}}catch(s){if(!(s instanceof rt))throw new Error(s);return{...fo,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};JG.methodName="dht";fa=JG,I7=class Cb{static async get({didUri:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=Mg.identifierToIdentityKeyBytes({didUri:e}),s=await Cb.pkarrGet({gatewayUri:t,publicKeyBytes:i,allowPrivateGatewayUri:n}),o=await Mg.parseBep44GetMessage({bep44Message:s}),a=await Cb.fromDnsPacket({didUri:e,dnsPacket:o});return a.didDocumentMetadata.versionId=s.seq.toString(),a}static async put({did:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=await Cb.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),s=await Mg.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Mg.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),o=await Cb.pkarrPut({gatewayUri:t,bep44Message:s,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return mge(e)}static async pkarrPut(e){return yge(e)}static async fromDnsPacket(e){return xge(e)}static async toDnsPacket(e){return Pge(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Mg=class{static async createBep44PutMessage(r){return gge(r)}static async identifierToIdentityKey(r){return FG(r)}static identifierToIdentityKeyBytes(r){return $5(r)}static async identityKeyToIdentifier(r){return vge(r)}static keyConverter(r){return O5(r)}static async parseBep44GetMessage(r){return wge(r)}static parseTxtDataToObject(r){return Rb(r)}static parseTxtDataToString(r){return Gb(r)}static async validatePreviousDidProof(r){return GG(r)}static chunkDataIfNeeded(r){return VG(r)}},Jn={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"},Yn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},xze=new Uint8Array(0),Tge=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")},Dge=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")}},kge=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 YG(this,r)}},Age=class{constructor(r){this.decoders=r}or(r){return YG(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`)}},YG=(r,e)=>new Age({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Ige=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Dge(r,e,t),this.decoder=new kge(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rge=({name:r,prefix:e,encode:t,decode:n})=>new Ige(r,e,t,n),Cge=(r,e,t,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,d=0,l=0;for(let c=0;c<s;++c){let u=i[r[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&d>>a)}if(a>=t||255&d<<8-a)throw new SyntaxError("Unexpected end of data");return o},$ge=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let d=0;d<r.length;++d)for(a=a<<8|r[d],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},PE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rge({prefix:e,name:r,encode(i){return $ge(i,n,t)},decode(i){return Cge(i,n,t,r)}}),Pze=PE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_ze=PE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),R7=PE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Eze=PE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Fg=class H2{static encode(e){return R7.baseEncode(e)}static decodeAsBytes(e,t){if(!H2.isBase64UrlString(e))throw new Yn(Jn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return R7.baseDecode(e)}static decodeAsString(e,t){let n=H2.decodeAsBytes(e,t);return H2.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)}},Oge=Xp(xfe(),1);(function(r){r.Public="public",r.Private="private"})(Z6||(Z6={}));Xd=Z6,sa=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Xd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Yn(Jn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Yn(Jn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Yn(Jn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Xd.Private&&(r.d===void 0||r.d.length!==43))throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Yn(Jn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!Fg.isBase64UrlString(r))throw new Yn(Jn.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 Yn(Jn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},B5=class{};B5.hashAlgorithmInMultihashCode=18;B5.maxCanonicalizedDeltaSizeInBytes=1e3;Gc=B5,Bge=Xp(Pfe(),1),Wb=class Q6{static canonicalizeAsBytes(e){let t=Q6.removeAllUndefinedProperties(e),n=Bge.default(t);return Fg.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?Q6.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},jge=ZG,C7=128,Nge=127,Mge=~Nge,Uge=Math.pow(2,31);Kge=X6,Lge=128,$7=127;qge=Math.pow(2,7),zge=Math.pow(2,14),Fge=Math.pow(2,21),Gge=Math.pow(2,28),Wge=Math.pow(2,35),Hge=Math.pow(2,42),Vge=Math.pow(2,49),Jge=Math.pow(2,56),Yge=Math.pow(2,63),Zge=function(r){return r<qge?1:r<zge?2:r<Fge?3:r<Gge?4:r<Wge?5:r<Hge?6:r<Vge?7:r<Jge?8:r<Yge?9:10},Qge={encode:jge,decode:Kge,encodingLength:Zge},Xge=Qge,lE=Xge,O7=(r,e=0)=>[lE.decode(r,e),lE.decode.bytes],B7=(r,e,t=0)=>(lE.encode(r,e,t),e),j7=r=>lE.encodingLength(r),N7=(r,e)=>{let t=e.byteLength,n=j7(r),i=n+j7(t),s=new Uint8Array(i+t);return B7(r,s,0),B7(t,s,n),s.set(e,i),new QG(r,t,e,s)},ewe=r=>{let e=Tge(r),[t,n]=O7(e),[i,s]=O7(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new QG(t,i,o,e)},QG=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},XG=({name:r,code:e,encode:t})=>new twe(r,e,t),twe=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?N7(this.code,e):e.then(t=>N7(this.code,t))}else throw Error("Unknown type, must be binary type")}},eW=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),M7=XG({name:"sha2-256",code:18,encode:eW("SHA-256")}),Sze=XG({name:"sha2-512",code:19,encode:eW("SHA-512")}),vb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},ca=class $b{static hash(e,t){return vb(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield M7.digest(e)).bytes;break;default:throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return vb(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield M7.encode(e);break;default:throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=Wb.canonicalizeAsBytes(e);return yield $b.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=Wb.canonicalizeAsBytes(e),i=yield $b.hashAsNonMultihashBytes(n,t);return yield $b.hashThenEncode(i,t)})}static hashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=yield $b.hash(e,t);return Fg.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=Fg.decodeAsBytes(e,t);try{n=ewe(i)}catch{throw new Yn(Jn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let s=Gc.hashAlgorithmInMultihashCode;if(s!==n.code)throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${s} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(e5||(e5={}));A2=e5;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(t5||(t5={}));Ig=t5,I2=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},tW=class Wa{static createCreateRequest(e){return I2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,s=e.document.services;sa.validateEs256kOperationKey(t,Xd.Public),sa.validateEs256kOperationKey(n,Xd.Public),Wa.validateDidDocumentKeys(i),Wa.validateServices(s);let o=Gc.hashAlgorithmInMultihashCode,a=[{action:Ig.Replace,document:e.document}],d={updateCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(n,o),patches:a};Wa.validateDeltaSize(d);let l={deltaHash:yield ca.canonicalizeThenHashThenEncode(d,o),recoveryCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(t,o)};return{type:A2.Create,suffixData:l,delta:d}})}static createDeactivateRequest(e){return I2(this,void 0,void 0,function*(){Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.recoveryPublicKey,Xd.Public);let t=Gc.hashAlgorithmInMultihashCode,n=yield ca.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},s=yield e.signer.sign({alg:"ES256K"},i);return{type:A2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:s}})}static createRecoverRequest(e){return I2(this,void 0,void 0,function*(){Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.recoveryPublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextRecoveryPublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextUpdatePublicKey,Xd.Public),Wa.validateDidDocumentKeys(e.document.publicKeys),Wa.validateServices(e.document.services);let t=Gc.hashAlgorithmInMultihashCode,n=yield ca.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:Ig.Replace,document:e.document}],s=yield ca.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),o={patches:i,updateCommitment:s},a=yield ca.canonicalizeThenHashThenEncode(o,t),d={recoveryCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:a},l=yield e.signer.sign({alg:"ES256K"},d);return{type:A2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:l}})}static createUpdateRequest(e){return I2(this,void 0,void 0,function*(){if(Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.updatePublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextUpdatePublicKey,Xd.Public),Wa.validateServices(e.servicesToAdd),Wa.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)sa.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)sa.validateId(p);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Ig.AddServices,services:n};t.push(p)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let p={action:Ig.RemoveServices,ids:i};t.push(p)}let s=e.publicKeysToAdd;if(s!==void 0&&s.length>0){let p={action:Ig.AddPublicKeys,publicKeys:s};t.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Ig.RemovePublicKeys,ids:o};t.push(p)}let a=Gc.hashAlgorithmInMultihashCode,d=yield ca.canonicalizeThenHashThenEncode(e.updatePublicKey,a),l=yield ca.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,a),c={patches:t,updateCommitment:l},u=yield ca.canonicalizeThenHashThenEncode(c,a),f={updateKey:e.updatePublicKey,deltaHash:u},h=yield e.signer.sign({alg:"ES256K"},f);return{type:A2.Update,didSuffix:e.didSuffix,revealValue:d,delta:c,signedData:h}})}static validateDidSuffix(e){ca.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 Yn(Jn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(sa.validateId(n.id),t.has(n.id))throw new Yn(Jn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),sa.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Wa.validateService(n),t.has(n.id))throw new Yn(Jn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){sa.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 Yn(Jn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Yn(Jn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Oge.parse(e.serviceEndpoint).error!==void 0)throw new Yn(Jn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=Wb.canonicalizeAsBytes(e);if(t.length>Gc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Gc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Yn(Jn.DeltaExceedsMaximumSize,n)}}},U7=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},rwe=class rW{static createLongFormDid(e){return U7(this,void 0,void 0,function*(){let t=yield tW.createCreateRequest(e),n=yield rW.computeDidUniqueSuffix(t.suffixData),i;Gc.network===void 0||Gc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Gc.network}:${n}`;let s={suffixData:t.suffixData,delta:t.delta},o=Wb.canonicalizeAsBytes(s),a=Fg.encode(o);return`${i}:${a}`})}static computeDidUniqueSuffix(e){return U7(this,void 0,void 0,function*(){let t=Wb.canonicalizeAsBytes(e),n=yield ca.hash(t,Gc.hashAlgorithmInMultihashCode);return Fg.encode(n)})}},so=2n**255n-19n,V2=2n**252n+27742317777372353535851937790883648493n,r5=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,n5=0x6666666666666666666666666666666666666666666666666666666666666658n,R2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:so,n:V2,h:8,Gx:r5,Gy:n5},Ds=(r="")=>{throw new Error(r)},nW=r=>typeof r=="string",j5=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ds("Uint8Array expected"):r,Gg=r=>new Uint8Array(r),nwe=(r,e)=>j5(nW(r)?M5(r):Gg(r),e),dt=(r,e=so)=>{let t=r%e;return t>=0n?t:e+t},K7=r=>r instanceof Wg?r:Ds("Point expected"),Wg=class $g{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new $g(e.x,e.y,1n,dt(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=R2;e=nwe(e,32);let i=e.slice();i[31]=e[31]&-129;let s=owe(i);s===0n||(t&&!(0n<s&&s<so)&&Ds("bad y coord 1"),!t&&!(0n<s&&s<2n**256n)&&Ds("bad y coord 2"));let o=dt(s*s),a=dt(o-1n),d=dt(n*o+1n),{isValid:l,value:c}=awe(a,d);l||Ds("bad y coordinate 3");let u=(c&1n)===1n;return(e[31]&128)!==0!==u&&(c=dt(-c)),new $g(c,s,1n,dt(c*s))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:s,ey:o,ez:a}=K7(e),d=dt(t*a),l=dt(s*i),c=dt(n*a),u=dt(o*i);return d===l&&c===u}is0(){return this.equals(J2)}negate(){return new $g(dt(-this.ex),this.ey,this.ez,dt(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=R2,s=dt(e*e),o=dt(t*t),a=dt(2n*dt(n*n)),d=dt(i*s),l=e+t,c=dt(dt(l*l)-s-o),u=d+o,f=u-a,h=d-o,p=dt(c*f),m=dt(u*h),y=dt(c*h),v=dt(f*u);return new $g(p,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:s}=this,{ex:o,ey:a,ez:d,et:l}=K7(e),{a:c,d:u}=R2,f=dt(t*o),h=dt(n*a),p=dt(s*u*l),m=dt(i*d),y=dt((t+n)*(o+a)-f-h),v=dt(m-p),w=dt(m+p),b=dt(h-c*f),T=dt(y*v),D=dt(w*b),I=dt(y*b),M=dt(v*w);return new $g(T,D,M,I)}mul(e,t=!0){if(e===0n)return t===!0?Ds("cannot multiply by 0"):J2;if(typeof e=="bigint"&&0n<e&&e<V2||Ds("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(uE))return lwe(e).p;let n=J2,i=uE;for(let s=this;e>0n;s=s.double(),e>>=1n)e&1n?n=n.add(s):t&&(i=i.add(s));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(R2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(V2/2n,!1).double();return V2%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=oW(n);return dt(n*i)!==1n&&Ds("invalid inverse"),{x:dt(e*i),y:dt(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=iwe(t);return n[31]|=e&1n?128:0,n}toHex(){return N5(this.toRawBytes())}};Wg.BASE=new Wg(r5,n5,1n,dt(r5*n5));Wg.ZERO=new Wg(0n,1n,1n,0n);({BASE:uE,ZERO:J2}=Wg),iW=(r,e)=>r.toString(16).padStart(e,"0"),N5=r=>Array.from(r).map(e=>iW(e,2)).join(""),M5=r=>{let e=r.length;(!nW(r)||e%2)&&Ds("hex invalid 1");let t=Gg(e/2);for(let n=0;n<t.length;n++){let i=n*2,s=r.slice(i,i+2),o=Number.parseInt(s,16);(Number.isNaN(o)||o<0)&&Ds("hex invalid 2"),t[n]=o}return t},iwe=r=>M5(iW(r,32*2)).reverse(),owe=r=>BigInt("0x"+N5(Gg(j5(r)).reverse())),q7=(...r)=>{let e=Gg(r.reduce((n,i)=>n+j5(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},oW=(r,e=so)=>{(r===0n||e<=0n)&&Ds("no inverse n="+r+" mod="+e);let t=dt(r,e),n=e,i=0n,s=1n,o=1n,a=0n;for(;t!==0n;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}return n===1n?dt(i,e):Ds("no inverse")},Yd=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=so;return t},swe=r=>{let e=r*r%so*r%so,t=Yd(e,2n)*e%so,n=Yd(t,1n)*r%so,i=Yd(n,5n)*n%so,s=Yd(i,10n)*i%so,o=Yd(s,20n)*s%so,a=Yd(o,40n)*o%so,d=Yd(a,80n)*a%so,l=Yd(d,80n)*a%so,c=Yd(l,10n)*i%so;return{pow_p_5_8:Yd(c,2n)*r%so,b2:e}},z7=19681161376707505956807079304988542015446066515923890162744021073123829784752n,awe=(r,e)=>{let t=dt(e*e*e),n=dt(t*t*e),i=swe(r*n).pow_p_5_8,s=dt(r*t*i),o=dt(e*s*s),a=s,d=dt(s*z7),l=o===r,c=o===dt(-r),u=o===dt(-r*z7);return l&&(s=a),(c||u)&&(s=d),(dt(s)&1n)===1n&&(s=dt(-s)),{isValid:l||c,value:s}},F7=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,cwe={bytesToHex:N5,hexToBytes:M5,concatBytes:q7,mod:dt,invert:oW,randomBytes:r=>{let e=F7();return e||Ds("crypto.getRandomValues must be defined"),e.getRandomValues(Gg(r))},sha512Async:async(...r)=>{let e=F7();e||Ds("crypto.subtle or etc.sha512Async must be defined");let t=q7(...r);return Gg(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(cwe,{sha512Sync:{configurable:!1,get(){return j6},set(r){j6||(j6=r)}}});zp=8,dwe=()=>{let r=[],e=256/zp+1,t=uE,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let s=1;s<2**(zp-1);s++)n=n.add(t),r.push(n);t=n.double()}return r},lwe=r=>{let e=L7||(L7=dwe()),t=(c,u)=>{let f=u.negate();return c?f:u},n=J2,i=uE,s=1+256/zp,o=2**(zp-1),a=BigInt(2**zp-1),d=2**zp,l=BigInt(zp);for(let c=0;c<s;c++){let u=c*o,f=Number(r&a);r>>=l,f>o&&(f-=d,r+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(t(m,e[h])):n=n.add(t(y,e[p]))}return{p:n,f:i}},U5=2n**256n,Jp=U5-0x1000003d1n,K5=U5-0x14551231950b75fc4402da1732fc9bebfn,sW=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,aW=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,cW={p:Jp,n:K5,a:0n,b:7n,Gx:sW,Gy:aW},Lg=32,G7=r=>tt(tt(r*r)*r+cW.b),Bi=(r="")=>{throw new Error(r)},_E=r=>typeof r=="bigint",dW=r=>typeof r=="string",N6=r=>_E(r)&&0n<r&&r<Jp,lW=r=>_E(r)&&0n<r&&r<K5,uW=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Bi("Uint8Array expected"):r,Hb=r=>new Uint8Array(r),L5=(r,e)=>uW(dW(r)?EE(r):Hb(r),e),tt=(r,e=Jp)=>{let t=r%e;return t>=0n?t:e+t},W7=r=>r instanceof Hg?r:Bi("Point expected"),Hg=class Og{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Og(e.x,e.y,1n)}static fromHex(e){e=L5(e);let t,n=e[0],i=e.subarray(1),s=V7(i,0,Lg),o=e.length;if(o===33&&[2,3].includes(n)){N6(s)||Bi("Point hex invalid: x not FE");let a=uwe(G7(s)),d=(a&1n)===1n;(n&1)===1!==d&&(a=tt(-a)),t=new Og(s,a,1n)}return o===65&&n===4&&(t=new Og(s,V7(i,Lg,2*Lg),1n)),t?t.ok():Bi("Point is not on curve")}static fromPrivateKey(e){return Nb.mul(fwe(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:s,py:o,pz:a}=W7(e),d=tt(t*a),l=tt(s*i),c=tt(n*a),u=tt(o*i);return d===l&&c===u}negate(){return new Og(this.px,tt(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:s,py:o,pz:a}=W7(e),{a:d,b:l}=cW,c=0n,u=0n,f=0n,h=tt(l*3n),p=tt(t*s),m=tt(n*o),y=tt(i*a),v=tt(t+n),w=tt(s+o);v=tt(v*w),w=tt(p+m),v=tt(v-w),w=tt(t+i);let b=tt(s+a);return w=tt(w*b),b=tt(p+y),w=tt(w-b),b=tt(n+i),c=tt(o+a),b=tt(b*c),c=tt(m+y),b=tt(b-c),f=tt(d*w),c=tt(h*y),f=tt(c+f),c=tt(m-f),f=tt(m+f),u=tt(c*f),m=tt(p+p),m=tt(m+p),y=tt(d*y),w=tt(h*w),m=tt(m+y),y=tt(p-y),y=tt(d*y),w=tt(w+y),p=tt(m*w),u=tt(u+p),p=tt(b*w),c=tt(v*c),c=tt(c-p),p=tt(v*m),f=tt(b*f),f=tt(f+p),new Og(c,u,f)}mul(e,t=!0){if(!t&&e===0n)return Y2;if(lW(e)||Bi("invalid scalar"),this.equals(Nb))return ywe(e).p;let n=Y2,i=Nb;for(let s=this;e>0n;s=s.double(),e>>=1n)e&1n?n=n.add(s):t&&(i=i.add(s));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(Y2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=hW(n);return tt(n*i)!==1n&&Bi("invalid inverse"),{x:tt(e*i),y:tt(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!N6(e)||!N6(t))&&Bi("Point invalid: x or y"),tt(t*t)===G7(e)?this:Bi("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")+J7(t)+(e?"":J7(n))}toRawBytes(e=!0){return EE(this.toHex(e))}};Hg.BASE=new Hg(sW,aW,1n);Hg.ZERO=new Hg(0n,1n,0n);({BASE:Nb,ZERO:Y2}=Hg),fW=(r,e)=>r.toString(16).padStart(e,"0"),q5=r=>Array.from(r).map(e=>fW(e,2)).join(""),EE=r=>{let e=r.length;(!dW(r)||e%2)&&Bi("hex invalid 1");let t=Hb(e/2);for(let n=0;n<t.length;n++){let i=n*2,s=r.slice(i,i+2),o=Number.parseInt(s,16);(Number.isNaN(o)||o<0)&&Bi("hex invalid 2"),t[n]=o}return t},SE=r=>BigInt("0x"+(q5(r)||"0")),V7=(r,e,t)=>SE(r.slice(e,t)),z5=r=>_E(r)&&r>=0n&&r<U5?EE(fW(r,2*Lg)):Bi("bigint expected"),J7=r=>q5(z5(r)),Y7=(...r)=>{let e=Hb(r.reduce((n,i)=>n+uW(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},hW=(r,e=Jp)=>{(r===0n||e<=0n)&&Bi("no inverse n="+r+" mod="+e);let t=tt(r,e),n=e,i=0n,s=1n,o=1n,a=0n;for(;t!==0n;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}return n===1n?tt(i,e):Bi("no inverse")},uwe=r=>{let e=1n;for(let t=r,n=(Jp+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%Jp),t=t*t%Jp;return tt(e*e)===r?e:Bi("sqrt invalid")},fwe=r=>(_E(r)||(r=SE(L5(r,Lg))),lW(r)?r:Bi("private key out of range")),Z7=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;pwe={hexToBytes:EE,bytesToHex:q5,concatBytes:Y7,bytesToNumberBE:SE,numberToBytesBE:z5,mod:tt,invert:hW,hmacSha256Async:async(r,...e)=>{let t=Z7();if(!t)return Bi("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Hb(await n.sign("HMAC",i,Y7(...e)))},hmacSha256Sync:Z2,hashToPrivateKey:hwe,randomBytes:r=>{let e=Z7();return e||Bi("crypto.getRandomValues must be defined"),e.getRandomValues(Hb(r))}};Object.defineProperties(pwe,{hmacSha256Sync:{configurable:!1,get(){return Z2},set(r){Z2||(Z2=r)}}});Fp=8,mwe=()=>{let r=[],e=256/Fp+1,t=Nb,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let s=1;s<2**(Fp-1);s++)n=n.add(t),r.push(n);t=n.double()}return r},ywe=r=>{let e=H7||(H7=mwe()),t=(c,u)=>{let f=u.negate();return c?f:u},n=Y2,i=Nb,s=1+256/Fp,o=2**(Fp-1),a=BigInt(2**Fp-1),d=2**Fp,l=BigInt(Fp);for(let c=0;c<s;c++){let u=c*o,f=Number(r&a);r>>=l,f>o&&(f-=d,r+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(t(m,e[h])):n=n.add(t(y,e[p]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(Q7||(Q7={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(X7||(X7={}));bb=class Lp{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 s=await Lp.createIonDocument({services:n,verificationMethods:i}),o=Lp.normalizeJwk(e),a=Lp.normalizeJwk(t);return await rwe.createLongFormDid({document:s,recoveryKey:o,updateKey:a})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await tW.createCreateRequest({document:e,recoveryKey:Lp.normalizeJwk(t),updateKey:Lp.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let s of t){let o=s.id??s.publicKeyJwk.kid??await Tr({jwk:s.publicKeyJwk});o=`${o.split("#").pop()}`;let a={id:o,publicKeyJwk:Lp.normalizeJwk(s.publicKeyJwk),purposes:s.purposes,type:"JsonWebKey2020"};n.push(a)}let i=e.map(s=>({...s,id:`${s.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}},gwe=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(gwe||{}),wwe={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},eF="https://ion.tbd.engineering",vwe=class Ob extends Qb{static async create({keyManager:e=new Wc,options:t={}}={}){if(t.verificationMethods?.some(p=>!(p.algorithm in wwe)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(p=>"id"in p).map(p=>p.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(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},s=[];for(let p of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});s.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),a=await e.getPublicKey({keyUri:o}),d=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:d}),c=await bb.computeLongFormDidUri({recoveryKey:a,updateKey:l,services:t.services??[],verificationMethods:s}),{didDocument:u,didResolutionMetadata:f}=await Ob.resolve(c,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ro({uri:c,document:u,metadata:{published:!1,canonicalId:c.split(":",3).join(":"),recoveryKey:a,updateKey:l},keyManager:e});if(t.publish??!0){let p=await Ob.publish({did:h,gatewayUri:t.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:t}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(s=>s.id===(t??e.assertionMethod?.[0]));if(!i?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==Ob.methodName)throw new rt("methodNotSupported","Method not supported");return await Ro.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=eF}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:gG({didDocument:e.document,methodId:o.id})}))??[],i=await bb.createIonDocument({services:e.document.service??[],verificationMethods:n}),s=await bb.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=bb.appendPathToUrl({baseUrl:t,path:"/operations"}),a=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a.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=Qn.parse(e);if(!n)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Ob.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??eF;try{let s=bb.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),o=await fetch(s,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new rt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:a,didDocumentMetadata:d}=await o.json();return{...fo,...a&&{didDocument:a},didDocumentMetadata:{published:d?.method?.published,...d}}}catch(s){if(!(s instanceof rt))throw new Error(s);return{...fo,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};vwe.methodName="ion";pW=class Bb extends Qb{static async create({keyManager:e=new Wc,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}),s=await e.getPublicKey({keyUri:i}),o=ot.object(s).toBase64Url(),a=`did:${Bb.methodName}:${o}`,d=(await Bb.resolve(a)).didDocument;return new Ro({uri:a,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Qn.parse(e.id);if(t&&t.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==Bb.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Qn.parse(e),i;try{i=n?ot.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Bb.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let s={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${s.id}#0`;switch(s.verificationMethod=[{id:o,type:"JsonWebKey",controller:s.id,publicKeyJwk:i}],s.authentication=[o],s.assertionMethod=[o],s.capabilityInvocation=[o],s.capabilityDelegation=[o],s.keyAgreement=[o],i.use){case"sig":{delete s.keyAgreement;break}case"enc":{delete s.authentication,delete s.assertionMethod,delete s.capabilityInvocation,delete s.capabilityDelegation;break}}return{...fo,didDocument:s}}};pW.methodName="jwk";ns=pW,bwe={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Q2=class Bg{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=Bg.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:ec.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":Ao.compressPublicKey,secp256k1:ao.compressPublicKey}[e];if(!t)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:co,"P-256":Ao,secp256k1:ao}[e];if(!t)throw new rt("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?ec.getNameFromCode({code:e}):t;let n=t,i=Bg.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 bwe))throw new rt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Bg.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Bg.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Bg.jwkToMulticodec({jwk:e});return vG({keyBytes:t,multicodecName:n})}};Q2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},Q2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},Q2.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:""}};C2=Q2,xwe=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(xwe||{}),tF={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},mW=class rh extends Qb{static async create({keyManager:e=new Wc,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}),s=await e.getPublicKey({keyUri:i}),o=await C2.publicKeyToMultibaseId({publicKey:s}),a=`did:${rh.methodName}:${o}`,d=(await rh.resolve(a,t)).didDocument;return new Ro({uri:a,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Qn.parse(e.id);if(t&&t.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(s=>s.id===n);if(!i?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==rh.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await rh.createDocument({didUri:e,options:t});return{...fo,didDocument:n}}catch(n){if(!(n instanceof rt))throw new Error(n);return{...fo,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:s="JsonWebKey2020"}=t,o={id:""},a=Qn.parse(e);if(!a)throw new rt("invalidDid",`Invalid DID URI: ${e}`);let d=a.id;if(a.method!==rh.methodName)throw new rt("methodNotSupported",`Method not supported: ${a.method}`);if(!rh.validateIdentifier(a))throw new rt("invalidDid",`Invalid DID URI: ${e}`);let l=await rh.createSignatureMethod({didUri:e,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:s}});o.id=a.uri,o.verificationMethod=[l],o.authentication=[l.id],o.assertionMethod=[l.id],o.capabilityInvocation=[l.id],o.capabilityDelegation=[l.id];let c=[n];return yG({didDocument:o}).forEach(u=>{let f=tF[u];c.push(f)}),o["@context"]=c,o}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:s}=n,o={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:d,multicodecName:l}=bG({multibaseKeyId:t}),c=a.byteLength,u=C2.MULTICODEC_PUBLIC_KEY_LENGTH[d];if(c!==u)throw new rt("invalidPublicKeyLength",`Expected ${c} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await ao.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":f=await co.validatePublicKey({publicKeyBytes:a});break}if(!f)throw new rt("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${t}`;try{new URL(o.id)}catch{throw new rt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(s in tF))throw new rt("unsupportedPublicKeyType",`Unsupported format: ${s}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new rt("invalidPublicKeyType",`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=s,o.controller=e,s==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=t),s==="JsonWebKey2020"){let{crv:h}=await C2.multicodecToJwk({code:d});o.publicKeyJwk=await C2.keyConverter(h).bytesToPublicKey({publicKeyBytes:a})}return o}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&M6(n)==="String"&&n.startsWith("z")}};mW.methodName="key";sm=mW,Pwe=3e4,yW=class X2 extends Qb{static async create({keyManager:e=new Wc,options:t}){if(!t.domain)throw new rt("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:${X2.methodName}:${n}`;if(!Qn.parse(i))throw new rt("invalidDid",`The constructed DID URI is invalid: ${i}`);let s=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let a=0;a<s.length;a++){let d=s[a],l=await e.generateKey({algorithm:d.algorithm}),c=await e.getPublicKey({keyUri:l}),u=d.id?.split("#").pop()??`key-${a}`,f=`${i}#${u}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:d.controller??i,publicKeyJwk:c});for(let h of d.purposes??[])o[h]??=[],o[h].push(f)}return t.services&&(o.service=t.services.map(a=>({...a,id:`${i}#${a.id.split("#").pop()}`}))),new Ro({uri:i,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=rs(t)??rs(e.assertionMethod?.[0]),s=i?e.verificationMethod?.find(o=>rs(o.id)===i):e.verificationMethod?.[0];if(!s?.publicKeyJwk)throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:t=new Wc}){if(Qn.parse(e.uri)?.method!==X2.methodName)throw new rt("methodNotSupported","Method not supported");return await Ro.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Qn.parse(e);if(!n)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==X2.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let s=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let o=await xF(s,{signal:AbortSignal.timeout(Pwe)},{description:"did:web document URL"});if(!o.ok)throw new Error("HTTP error status code returned");let a=await o.json();return{...fo,didDocument:a}}catch{return{...fo,didResolutionMetadata:{error:"notFound"}}}}};yW.methodName="web";TE=yW,_we=Xp(uF(),1),Ewe=Xp(fF(),1),DE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new _we.Level(e),this.ttl=(0,Ewe.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()}},Swe=Xp(fF(),1),t1=class{constructor({ttl:r="15m"}={}){this.cache=new Efe.default({ttl:(0,Swe.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(){}},Twe={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()}},dh=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=r||Twe;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=Qn.parse(r);if(!t)return{...fo,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...fo,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};if(e!==void 0)return n.resolve(t.uri,e);let i=await this.cache.get(t.uri);if(i)return i;let s=this._inFlight.get(t.uri);if(s)return s;let o=(async()=>{let a=await n.resolve(t.uri,e);if(!a.didResolutionMetadata.error)try{await this.cache.set(t.uri,a)}catch{}return a})();this._inFlight.set(t.uri,o);try{return await o}finally{this._inFlight.delete(t.uri)}}async dereference(r,e){let t=Qn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:s}=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:s};let{service:o=[],verificationMethod:a=[]}=n,d=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let c of a)if(d.has(c.id)){l=c;break}for(let c of o)if(d.has(c.id)){l=c;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var Qg,gW=G(()=>{"use strict";g();PR();xR();vr();na();bL();PL();EL();ia();vz();bz();$z();Oz();Bz();jz();Nz();Mz();w2();D6();is();lr();Qg=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 Ag({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new g2(e.resumableTaskStore,this.storageController),this._coreProtocols=new dg,this._coreProtocols.register(new Qe);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={[xe.Messages+me.Read]:new E_(t),[xe.Messages+me.Subscribe]:new D_(t),[xe.Messages+me.Sync]:new A_(t),[xe.Protocols+me.Configure]:new h2(t),[xe.Protocols+me.Query]:new m2(t),[xe.Records+me.Count]:new y2(t),[xe.Records+me.Delete]:new v2(t),[xe.Records+me.Query]:new b2(t),[xe.Records+me.Read]:new x2(t),[xe.Records+me.Subscribe]:new _2(t),[xe.Records+me.Write]:new E2(t)}}static async create(e){e.didResolver||(e.didResolver=new dh({didResolvers:[fa,ns,sm,TE],cache:new t1}),e.ownsResolver=!0),e.tenantGate??=new lg;let t=new r(e);return await t.open(),t}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.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();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.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:s,subscriptionHandler:o}=n,a=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[a].handle({tenant:e,message:t,dataStream:s,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 gt(i,400)}}}});function Dwe(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Xn(r,e){return e?Promise.race([r,Dwe(e)]):r}var kE=G(()=>{"use strict";g()});import{Level as kwe}from"level";async function os(r,e){return new kwe(r,{...e,keyEncoding:"utf8"})}var rc,lh=G(()=>{"use strict";g();kE();rc=class r{config;db;constructor(e,t){this.config={createLevelDatabase:os,...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 Xn(this.createLevelDatabase(),t?.signal);try{return await Xn(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 Xn(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 Xn(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 Xn(this.createLevelDatabase(),n?.signal),Xn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Xn(this.createLevelDatabase(),t?.signal),Xn(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 Xn(this.createLevelDatabase(),t?.signal),Xn(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 Xn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Xn(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 uh,AE=G(()=>{"use strict";g();v0();lh();uh=class r{config;db;constructor(e,t){this.config={createLevelDatabase:os,...e},this.db=t??new rc({...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),er.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:er.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 Awe(r){return r[Symbol.asyncIterator]!=null}function Iwe(r){if(Awe(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 wW,vW=G(()=>{g();wW=Iwe});var bW,Rwe,xW,Cwe,PW,_W=G(()=>{g();Eh();Vm();bW=0,Rwe="identity",xW=cc,Cwe=r=>Ih(bW,xW(r)),PW={code:bW,name:Rwe,encode:xW,digest:Cwe}});var EW,$we,SW,TW=G(()=>{g();xy();EW=Rn(_a(),1);Ol();$we=async(r,e,t,n,i,s,o,a)=>{let d=await o.get(r,a),l=ck(d),c=l,u=t;for(;n.length>0;){let f=n[0];if(f in c){n.shift(),u=`${u}/${f}`;let h=er.asCID(c[f]);if(h!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:d,depth:s,size:BigInt(d.length),content:async function*(){yield l}},next:{cid:h,name:f,path:u,toResolve:n}};c=c[f]}else throw(0,EW.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:d,depth:s,size:BigInt(d.length),content:async function*(){yield l}}}},SW=$we});function Owe(r,e,t,n){let i=BigInt(r.length),s=BigInt(e+i);return t>=s||n<e?new Uint8Array(0):(n>=e&&n<s&&(r=r.subarray(0,Number(n-e))),t>=e&&t<s&&(r=r.subarray(Number(t-e))),r)}var am,IE=G(()=>{g();am=Owe});var r1,Bwe,Xg,RE=G(()=>{g();r1=Rn(_a(),1),Bwe=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),s=BigInt(t);if(s!==n&&(s=i+s),s>n&&(s=n),i<0n)throw(0,r1.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,r1.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(s<0n)throw(0,r1.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,r1.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:s}},Xg=Bwe});var DW,jwe,Nwe,kW,AW=G(()=>{g();DW=Rn(_a(),1);Vm();jl();IE();RE();jwe=r=>{async function*e(t={}){let{start:n,end:i}=Xg(r.length,t.offset,t.length),s=am(r,0n,n,i);t.onProgress?.(new Bn("unixfs:exporter:progress:identity",{bytesRead:BigInt(s.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield s}return e},Nwe=async(r,e,t,n,i,s,o,a)=>{if(n.length>0)throw(0,DW.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let d=nx(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:jwe(d.digest),depth:s,size:BigInt(d.digest.length),node:d.digest}}},kW=Nwe});var IW,Mwe,Uwe,RW,CW=G(()=>{g();IW=Rn(_a(),1);jl();IE();RE();Mwe=r=>{async function*e(t={}){let{start:n,end:i}=Xg(r.length,t.offset,t.length),s=am(r,0n,n,i);t.onProgress?.(new Bn("unixfs:exporter:progress:raw",{bytesRead:BigInt(s.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield s}return e},Uwe=async(r,e,t,n,i,s,o,a)=>{if(n.length>0)throw(0,IW.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let d=await o.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:Mwe(d),depth:s,size:BigInt(d.length),node:d}}},RW=Uwe});var Kwe,Lwe,$W,qwe,OW,BW,jW=G(()=>{g();Ea();cA();dA();Kwe=async function(r){return(await oP.encode(r)).slice(0,8).reverse()},Lwe=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 pd({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},$W=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),qwe=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},OW=async(r,e,t,n,i)=>{if(n==null){let c=cP({hashFn:Kwe});n={rootBucket:c,hamtDepth:1,lastBucket:c}}await Lwe(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),o=$W(s.pos),a=qwe(s);a.length>n.hamtDepth&&(n.lastBucket=a[n.hamtDepth],o=$W(n.lastBucket._posAtParent));let d=r.Links.find(c=>{if(c.Name==null)return!1;let u=c.Name.substring(0,2),f=c.Name.substring(2);return!(u!==o||f!==""&&f!==e)});if(d==null)return;if(d.Name!=null&&d.Name.substring(2)===e)return d.Hash;n.hamtDepth++;let l=await t.get(d.Hash,i);return r=Bl(l),OW(r,e,t,n,i)},BW=OW});function zwe(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 CE,F5=G(()=>{g();CE=zwe});function Fwe(r){return r[Symbol.asyncIterator]!=null}function Gwe(r,e){let t=0;if(Fwe(r))return async function*(){for await(let d of r)await e(d,t++)&&(yield d)}();let n=CE(r),{value:i,done:s}=n.next();if(s===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){await o&&(yield i);for(let d of n)await e(d,t++)&&(yield d)}();let a=e;return function*(){o===!0&&(yield i);for(let d of n)a(d,t++)&&(yield d)}()}var NW,MW=G(()=>{g();F5();NW=Gwe});function Wwe(r){return r[Symbol.asyncIterator]!=null}function Hwe(r,e){let t=0;if(Wwe(r))return async function*(){for await(let d of r)yield e(d,t++)}();let n=CE(r),{value:i,done:s}=n.next();if(s===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){yield await o;for(let d of n)yield e(d,t++)}();let a=e;return function*(){yield o;for(let d of n)yield a(d,t++)}()}var ew,$E=G(()=>{g();F5();ew=Hwe});function As(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var OE=G(()=>{g()});async function*cm(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,s=[],o=As(),a=As(),d=!1,l,c=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(o=As(),await o.promise),c)break;let m={done:!1};s.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new BE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new BE("task-complete"))})}d=!0,i.dispatchEvent(new BE("task-complete"))}catch(p){l=p,i.dispatchEvent(new BE("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*f(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw c=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw c=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(u()||(a=As(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(d&&s.length===0)break}}var BE,jE=G(()=>{g();OE();BE=globalThis.CustomEvent??Event});var NE,tw,UW=G(()=>{g();NE=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}},tw=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new NE(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 NE(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 ME(r={}){return Vwe(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 Vwe(r,e){e=e??{};let t=e.onEnd,n=new tw,i,s,o,a=As(),d=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,v)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){v(b)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=As()})}},l=y=>s!=null?s(y):(n.push(y),i),c=y=>(n=new tw,s!=null?s({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?c(y):l({done:!0})),h=()=>(n=new tw,f(),{done:!0}),p=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:d,return:h,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,b;v!=null&&(w=new Promise((T,D)=>{b=()=>{D(new G5)},v.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&v!=null&&v?.removeEventListener("abort",b)}}},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 G5,W5=G(()=>{g();OE();UW();G5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function Jwe(r){return r.reason}async function KW(r,e,t){if(e==null)return r;let n=t?.translateError??Jwe;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((s,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var LW=G(()=>{g()});function qW(){return new H5}var H5,zW=G(()=>{g();OE();LW();H5=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=As(),this.haveNext=As()}[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=As(),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=As(),await KW(this.readNext.promise,t?.signal,t)}}});function Ywe(r){return r[Symbol.asyncIterator]!=null}async function Zwe(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*Qwe(r){let e=new AbortController,t=qW();Zwe(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Xwe(r){for(let e of r)yield*e}function e0e(...r){let e=[];for(let t of r)Ywe(t)||e.push(t);return e.length===r.length?Xwe(e):Qwe(r)}var FW,GW=G(()=>{g();zW();FW=e0e});function rw(r,...e){if(r==null)throw new Error("Empty pipeline");if(V5(r)){let n=r;r=()=>n.source}else if(HW(r)||WW(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&V5(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++)V5(t[n])&&(t[n]=r0e(t[n]));return t0e(...t)}var t0e,WW,HW,V5,r0e,UE=G(()=>{g();W5();GW();t0e=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},WW=r=>r?.[Symbol.asyncIterator]!=null,HW=r=>r?.[Symbol.iterator]!=null,V5=r=>r==null?!1:r.sink!=null&&r.source!=null,r0e=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=ME({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(WW(s))i=async function*(){yield*s,n.end()};else if(HW(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return FW(n,i())}return r.source}});var n0e,VW,JW=G(()=>{g();MW();$E();jE();UE();jl();n0e=(r,e,t,n,i,s,o)=>{async function*a(d={}){let l=d.offset??0,c=d.length??e.Links.length,u=e.Links.slice(l,c);d.onProgress?.(new Bn("unixfs:exporter:walk:directory",{cid:r})),yield*rw(u,f=>ew(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await i(h.Hash,p,m,[],s+1,o,d)).entry}),f=>cm(f,{ordered:!0}),f=>NW(f,h=>h!=null))}return a},VW=n0e});var ZW=Te(($Ge,J5)=>{"use strict";g();var i0e=Object.prototype.hasOwnProperty,ss="~";function n1(){}Object.create&&(n1.prototype=Object.create(null),new n1().__proto__||(ss=!1));function o0e(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function YW(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new o0e(t,n||r,i),o=ss?ss+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function KE(r,e){--r._eventsCount===0?r._events=new n1:delete r._events[e]}function Co(){this._events=new n1,this._eventsCount=0}Co.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)i0e.call(t,n)&&e.push(ss?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Co.prototype.listeners=function(e){var t=ss?ss+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Co.prototype.listenerCount=function(e){var t=ss?ss+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Co.prototype.emit=function(e,t,n,i,s,o){var a=ss?ss+e:e;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,c,u;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,n),!0;case 4:return d.fn.call(d.context,t,n,i),!0;case 5:return d.fn.call(d.context,t,n,i,s),!0;case 6:return d.fn.call(d.context,t,n,i,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var f=d.length,h;for(u=0;u<f;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,n);break;case 4:d[u].fn.call(d[u].context,t,n,i);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0};Co.prototype.on=function(e,t,n){return YW(this,e,t,n,!1)};Co.prototype.once=function(e,t,n){return YW(this,e,t,n,!0)};Co.prototype.removeListener=function(e,t,n,i){var s=ss?ss+e:e;if(!this._events[s])return this;if(!t)return KE(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&KE(this,s);else{for(var a=0,d=[],l=o.length;a<l;a++)(o[a].fn!==t||i&&!o[a].once||n&&o[a].context!==n)&&d.push(o[a]);d.length?this._events[s]=d.length===1?d[0]:d:KE(this,s)}return this};Co.prototype.removeAllListeners=function(e){var t;return e?(t=ss?ss+e:e,this._events[t]&&KE(this,t)):(this._events=new n1,this._eventsCount=0),this};Co.prototype.off=Co.prototype.removeListener;Co.prototype.addListener=Co.prototype.on;Co.prefixed=ss;Co.EventEmitter=Co;typeof J5<"u"&&(J5.exports=Co)});var Y5,QW=G(()=>{g();Y5=Rn(ZW(),1)});function Q5(r,e,t,n){let i,s=new Promise((o,a)=>{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:d}=n;d.aborted&&a(eH(d)),d.addEventListener("abort",()=>{a(eH(d))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(c){a(c)}return}let d=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new i1(d);typeof r.cancel=="function"&&r.cancel(),a(l)},e),(async()=>{try{o(await r)}catch(d){a(d)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}var i1,Z5,XW,eH,tH=G(()=>{g();i1=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Z5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},XW=r=>globalThis.DOMException===void 0?new Z5(r):new DOMException(r),eH=r=>{let e=r.reason===void 0?XW("This operation was aborted."):r.reason;return e instanceof Error?e:XW(e)}});function X5(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var rH=G(()=>{g()});var dm,bu,e$,nH,iH=G(()=>{g();rH();dm=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)},e$=class{constructor(){bu.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&dm(this,bu,"f")[this.size-1].priority>=t.priority){dm(this,bu,"f").push(n);return}let i=X5(dm(this,bu,"f"),n,(s,o)=>o.priority-s.priority);dm(this,bu,"f").splice(i,0,n)}dequeue(){let e=dm(this,bu,"f").shift();return e?.run}filter(e){return dm(this,bu,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return dm(this,bu,"f").length}};bu=new WeakMap;nH=e$});var An,Je,ei,s1,a1,hh,WE,c1,LE,Hc,o1,ha,qE,pa,d1,fh,zE,oH,sH,dH,aH,cH,FE,t$,r$,HE,lH,GE,VE,n$,uH,fH=G(()=>{g();QW();tH();iH();An=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},Je=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)},VE=class extends Error{},n$=class extends Y5.default{constructor(e){var t,n,i,s;if(super(),ei.add(this),s1.set(this,void 0),a1.set(this,void 0),hh.set(this,0),WE.set(this,void 0),c1.set(this,void 0),LE.set(this,0),Hc.set(this,void 0),o1.set(this,void 0),ha.set(this,void 0),qE.set(this,void 0),pa.set(this,0),d1.set(this,void 0),fh.set(this,void 0),zE.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:nH,...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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);An(this,s1,e.carryoverConcurrencyCount,"f"),An(this,a1,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),An(this,WE,e.intervalCap,"f"),An(this,c1,e.interval,"f"),An(this,ha,new e.queueClass,"f"),An(this,qE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,An(this,zE,e.throwOnTimeout===!0,"f"),An(this,fh,e.autoStart===!1,"f")}get concurrency(){return Je(this,d1,"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})`);An(this,d1,e,"f"),Je(this,ei,"m",HE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Je(this,zE,"f"),...t},new Promise((n,i)=>{Je(this,ha,"f").enqueue(async()=>{var s,o,a;An(this,pa,(o=Je(this,pa,"f"),o++,o),"f"),An(this,hh,(a=Je(this,hh,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new VE("The task was aborted.");let d=e({signal:t.signal});t.timeout&&(d=Q5(Promise.resolve(d),t.timeout)),t.signal&&(d=Promise.race([d,Je(this,ei,"m",lH).call(this,t.signal)]));let l=await d;n(l),this.emit("completed",l)}catch(d){if(d instanceof i1&&!t.throwOnTimeout){n();return}i(d),this.emit("error",d)}finally{Je(this,ei,"m",dH).call(this)}},t),this.emit("add"),Je(this,ei,"m",FE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Je(this,fh,"f")?(An(this,fh,!1,"f"),Je(this,ei,"m",HE).call(this),this):this}pause(){An(this,fh,!0,"f")}clear(){An(this,ha,new(Je(this,qE,"f")),"f")}async onEmpty(){Je(this,ha,"f").size!==0&&await Je(this,ei,"m",GE).call(this,"empty")}async onSizeLessThan(e){Je(this,ha,"f").size<e||await Je(this,ei,"m",GE).call(this,"next",()=>Je(this,ha,"f").size<e)}async onIdle(){Je(this,pa,"f")===0&&Je(this,ha,"f").size===0||await Je(this,ei,"m",GE).call(this,"idle")}get size(){return Je(this,ha,"f").size}sizeBy(e){return Je(this,ha,"f").filter(e).length}get pending(){return Je(this,pa,"f")}get isPaused(){return Je(this,fh,"f")}};s1=new WeakMap,a1=new WeakMap,hh=new WeakMap,WE=new WeakMap,c1=new WeakMap,LE=new WeakMap,Hc=new WeakMap,o1=new WeakMap,ha=new WeakMap,qE=new WeakMap,pa=new WeakMap,d1=new WeakMap,fh=new WeakMap,zE=new WeakMap,ei=new WeakSet,oH=function(){return Je(this,a1,"f")||Je(this,hh,"f")<Je(this,WE,"f")},sH=function(){return Je(this,pa,"f")<Je(this,d1,"f")},dH=function(){var e;An(this,pa,(e=Je(this,pa,"f"),e--,e),"f"),Je(this,ei,"m",FE).call(this),this.emit("next")},aH=function(){Je(this,ei,"m",r$).call(this),Je(this,ei,"m",t$).call(this),An(this,o1,void 0,"f")},cH=function(){let e=Date.now();if(Je(this,Hc,"f")===void 0){let t=Je(this,LE,"f")-e;if(t<0)An(this,hh,Je(this,s1,"f")?Je(this,pa,"f"):0,"f");else return Je(this,o1,"f")===void 0&&An(this,o1,setTimeout(()=>{Je(this,ei,"m",aH).call(this)},t),"f"),!0}return!1},FE=function(){if(Je(this,ha,"f").size===0)return Je(this,Hc,"f")&&clearInterval(Je(this,Hc,"f")),An(this,Hc,void 0,"f"),this.emit("empty"),Je(this,pa,"f")===0&&this.emit("idle"),!1;if(!Je(this,fh,"f")){let e=!Je(this,ei,"a",cH);if(Je(this,ei,"a",oH)&&Je(this,ei,"a",sH)){let t=Je(this,ha,"f").dequeue();return t?(this.emit("active"),t(),e&&Je(this,ei,"m",t$).call(this),!0):!1}}return!1},t$=function(){Je(this,a1,"f")||Je(this,Hc,"f")!==void 0||(An(this,Hc,setInterval(()=>{Je(this,ei,"m",r$).call(this)},Je(this,c1,"f")),"f"),An(this,LE,Date.now()+Je(this,c1,"f"),"f"))},r$=function(){Je(this,hh,"f")===0&&Je(this,pa,"f")===0&&Je(this,Hc,"f")&&(clearInterval(Je(this,Hc,"f")),An(this,Hc,void 0,"f")),An(this,hh,Je(this,s1,"f")?Je(this,pa,"f"):0,"f"),Je(this,ei,"m",HE).call(this)},HE=function(){for(;Je(this,ei,"m",FE).call(this););},lH=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new VE("The task was aborted."))},{once:!0})})},GE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};uH=n$});async function hH(r,e,t,n,i,s,o){if(e instanceof Uint8Array){let l=am(e,n,i,s);t.push(l);return}if(e.Data==null)throw(0,lm.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=Ti.unmarshal(e.Data)}catch(l){throw(0,lm.default)(l,"ERR_NOT_UNIXFS")}if(a.data!=null){let l=a.data,c=am(l,n,i,s);t.push(c),n+=BigInt(c.byteLength)}let d=[];if(e.Links.length!==a.blockSizes.length)throw(0,lm.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let c=e.Links[l],u=n,f=u+a.blockSizes[l];if((i>=u&&i<f||s>=u&&s<=f||i<u&&s>f)&&d.push({link:c,blockStart:n}),n=f,n>s)break}await rw(d,l=>ew(l,c=>async()=>{let u=await r.get(c.link.Hash,o);return{...c,block:u}}),l=>cm(l,{ordered:!0}),async l=>{for await(let{link:c,block:u,blockStart:f}of l){let h;switch(c.Hash.code){case E0:h=Bl(u);break;case of:h=u;break;default:t.end((0,lm.default)(new Error(`Unsupported codec: ${c.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new uH({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{o.onProgress?.(new Bn("unixfs:exporter:walk:file",{cid:c.Hash})),await hH(r,h,t,f,i,s,o)}),await p.onIdle()}}),n>=s&&t.end()}var lm,s0e,i$,pH=G(()=>{g();Ea();lm=Rn(_a(),1);nf();$E();jE();UE();W5();C0();fH();jl();IE();RE();s0e=(r,e,t,n,i,s,o)=>{async function*a(d={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:c,end:u}=Xg(l,d.offset,d.length);if(u===0n)return;let f=0n,h=u-c,p=ME();d.onProgress?.(new Bn("unixfs:exporter:walk:file",{cid:r})),hH(o,e,p,0n,c,u,d).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),(0,lm.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===h&&p.end(),d.onProgress?.(new Bn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw(0,lm.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},i$=s0e});async function*mH(r,e,t,n,i,s){let o=r.Links,a=rw(o,d=>ew(d,l=>async()=>{let c=l.Name!=null?l.Name.substring(2):null;if(c!=null&&c!==""){let u=await t(l.Hash,c,`${e}/${c}`,[],n+1,i,s);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,s);return r=Bl(u),s.onProgress?.(new Bn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:mH(r,e,t,n,i,s)}}}),d=>cm(d,{ordered:!0}));for await(let{entries:d}of a)yield*d}var a0e,yH,gH=G(()=>{g();Ea();$E();jE();UE();jl();a0e=(r,e,t,n,i,s,o)=>{function a(d={}){return d.onProgress?.(new Bn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),mH(e,n,i,s,o,d)}return a};yH=a0e});var l1,c0e,d0e,l0e,wH,vH=G(()=>{g();Ea();l1=Rn(_a(),1);nf();jW();JW();pH();gH();c0e=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,d0e={raw:i$,file:i$,directory:VW,"hamt-sharded-directory":yH,metadata:(r,e,t,n,i,s,o)=>()=>[],symlink:(r,e,t,n,i,s,o)=>()=>[]},l0e=async(r,e,t,n,i,s,o,a)=>{let d=await o.get(r,a),l=Bl(d),c,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,l1.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{c=Ti.unmarshal(l.Data)}catch(h){throw(0,l1.default)(h,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let h;if(c?.type==="hamt-sharded-directory"?h=await BW(l,n[0],o):h=c0e(l,n[0]),h==null)throw(0,l1.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${t}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=d0e[c.type](r,l,c,t,i,s,o);if(f==null)throw(0,l1.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return c.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:c,depth:s,node:l,size:c.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:c,depth:s,node:l,size:c.fileSize()},next:u}},wH=l0e});var bH,u0e,xH,PH,_H=G(()=>{g();xy();Ea();bH=Rn(_a(),1);C0();_W();TW();AW();CW();vH();u0e={[E0]:wH,[of]:RW,[Xu]:SW,[PW.code]:kW},xH=async(r,e,t,n,i,s,o)=>{let a=u0e[r.code];if(a==null)throw(0,bH.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,xH,i,s,o)},PH=xH});async function*p0e(r,e,t={}){let{cid:n,toResolve:i}=h0e(r),s=n.toString(),o=s,a=i.length;for(;;){let d=await PH(n,s,o,i,a,e,t);if(d.entry==null&&d.next==null)throw(0,JE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(d.entry!=null&&(yield d.entry),d.next==null)return;i=d.next.toResolve,n=d.next.cid,s=d.next.name,o=d.next.path}}async function EH(r,e,t={}){let n=await wW(p0e(r,e,t));if(n==null)throw(0,JE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var JE,f0e,h0e,SH=G(()=>{g();JE=Rn(_a(),1);vW();Ol();_H();f0e=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),h0e=r=>{if(r instanceof Uint8Array)return{cid:er.decode(r),toResolve:[]};let e=er.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=f0e(r);return{cid:er.parse(t[0]),toResolve:t.slice(1)}}throw(0,JE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var o$,YE,um,TH=G(()=>{"use strict";g();AE();lh();ef();SH();fA();o$=new TextEncoder,YE=new TextDecoder,um=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:os,...e},this.blockstore=new uh({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 s=await this.getRefsPartition(e,t),o=await s.get(n);if(o){await i.cancel();let{dataSize:u}=JSON.parse(YE.decode(o));return{dataSize:u}}let a=await this.getRefcountsPartition(),d=await a.get(n),l=d?JSON.parse(YE.decode(d)):{count:0,dataSize:0},c;if(l.count>0)await i.cancel(),c=l.dataSize;else{let u=await this.getBlocksPartition(n),f=B0([{content:Et.asAsyncIterable(i)}],u,{cidVersion:1}),h;for await(h of f);c=Number(h.unixfs?.fileSize()??h.size)}return await s.put(n,o$.encode(JSON.stringify({dataSize:c}))),await a.put(n,o$.encode(JSON.stringify({count:l.count+1,dataSize:c}))),{dataSize:c}}async get(e,t,n){let s=await(await this.getRefsPartition(e,t)).get(n);if(!s)return;let{dataSize:o}=JSON.parse(YE.decode(s)),a=await this.getBlocksPartition(n);if(!await a.has(n))return;let c=(await EH(n,a)).content(),u=new ReadableStream({async pull(f){let h=await c.next();h.done?f.close():f.enqueue(h.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(),a=await o.get(n);if(!a)return;let d=JSON.parse(YE.decode(a)),l=d.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,o$.encode(JSON.stringify({count:l,dataSize:d.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 DH(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function kH(r,e,t,n,i){let s=[];for(let l of t.properties){let c=e[l];if(c===void 0||Array.isArray(c))return;s.push(n(c))}let o=e[t.sortProperty];if(o===void 0||Array.isArray(o))return;let a=s.join(ZE),d=n(o);return a+ZE+d+i+r}function AH(r,e,t){let n=[];for(let i of e.properties){let s=r[i];if(s===void 0||typeof s=="object")return;n.push(t(s))}return n.join(ZE)+ZE}function IH(r,e,t,n,i,s){let o=kH(t.messageCid,t.indexes,n,i,s);if(o!==void 0)return CH(r,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(t)})}function RH(r,e,t,n,i,s,o){let a=kH(t,n,i,s,o);if(a!==void 0)return CH(r,e,`__compound:${i.name}__`,{type:"del",key:a})}async function CH(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function s$(r,e,t){let n,i=0;for(let s of t){if(s.sortProperty!==e.sortProperty)continue;let o=!0;for(let a of s.properties){let d=r[a];if(d===void 0||typeof d=="object"){o=!1;break}}o&&s.properties.length>i&&(n=s,i=s.properties.length)}return n}async function $H(r,e,t,n,i,s,o,a,d){let{sortDirection:l=It.Ascending,cursor:c,limit:u}=n,f=AH(t,i,s);if(f===void 0)return a(e,[t],n,d);let h=await DH(r,e,i),p={};if(c===void 0)l===It.Ascending?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);else{let b=s(c.value),T=f+b+o+c.messageCid;l===It.Ascending?(p.gt=T,p.lt=f+"\xFF"):(p.lt=T,p.gt=f,p.reverse=!0)}let m=new Set(i.properties),y={},v=!1;for(let b in t)m.has(b)||(y[b]=t[b],v=!0);let w=[];for await(let[b,T]of h.iterator(p,d)){if(u!==void 0&&w.length===u)break;let D=JSON.parse(T);v&&!tr.matchFilter(D.indexes,y)||w.push(D)}return w}async function OH(r,e,t,n,i,s,o){let a=AH(t,n,i);if(a===void 0)return(await s(e,[t],{sortProperty:n.sortProperty},o)).length;let d=await DH(r,e,n),l=new Set(n.properties),c=!1,u={};for(let p in t)l.has(p)||(u[p]=t[p],c=!0);let f={gt:a,lt:a+"\xFF"},h=0;if(c)for await(let[p,m]of d.iterator(f,o)){let y=JSON.parse(m);tr.matchFilter(y.indexes,u)&&h++}else for await(let[p,m]of d.iterator(f,o))h++;return h}var ZE,BH=G(()=>{"use strict";g();$c();Ed();ZE=""});var jH,fm,a$=G(()=>{"use strict";g();He();pA();Ed();BH();lh();xt();$c();jH="index",fm=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:os,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new rc({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(Ml(n))throw new ne(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let s={messageCid:t,indexes:n},o=[];for(let c in n){let u=n[c];if(Array.isArray(u))for(let f of u){let h=this.createPutIndexedItemOperation(e,s,c,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,s,c,u);o.push(f)}}for(let c of this._compoundIndexes){let u=IH(this.db,e,s,c,r.encodeValue,r.delimiter);u!==void 0&&o.push(u)}let a=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});o.push(a);let d=await Promise.all(o);await(await this.db.partition(e)).batch(d,i)}async delete(e,t,n){let i=[],s=await this.getIndexes(e,t);if(s===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(o);for(let l in s){let c=s[l];if(Array.isArray(c))for(let u of c){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,c);i.push(u)}}for(let l of this._compoundIndexes){let c=RH(this.db,e,t,s,l,r.encodeValue,r.delimiter);c!==void 0&&i.push(c)}let a=await Promise.all(i);await(await this.db.partition(e)).batch(a,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:s}=t,o=r.keySegmentJoin(r.encodeValue(i),s);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let s=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:s})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),s=r.getIndexPartitionName(t);return i.createPartitionOperation(s,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(jH,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(jH)}async query(e,t,n,i){if(t.length===1&&!Ml(t[0])){let s=s$(t[0],n,this._compoundIndexes);if(s!==void 0)return $H(this.db,e,t[0],n,s,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&&!Ml(t[0])){let o=s$(t[0],{...n},this._compoundIndexes);if(o!==void 0)return OH(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:s,limit:o}=n,a=s?this.createStartingKeyFromCursor(s):"",d=[];for await(let l of this.getIndexIterator(e,a,n,i)){if(o!==void 0&&o===d.length)break;let{indexes:c}=l;tr.matchAnyFilter(c,t)&&d.push(l)}return d}async*getIndexIterator(e,t,n,i){let{sortProperty:s,sortDirection:o=It.Ascending,cursor:a}=n,d={gt:t};o===It.Descending&&(d.reverse=!0,a!==void 0&&(d.lt=t,delete d.gt));let l=await this.getIndexPartition(e,s);for await(let[c,u]of l.iterator(d,i)){let{indexes:f,messageCid:h}=JSON.parse(u);yield{indexes:f,messageCid:h}}}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,s=i[t];if(s===void 0)throw new ne(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof s=="boolean"||Array.isArray(s))throw new ne(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof s} was given.`);return{messageCid:n,value:s}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:s,sortDirection:o=It.Ascending,cursor:a,limit:d}=n,l=a?this.createStartingKeyFromCursor(a):void 0,c=new Map;t.length===0&&(t=[{}]);try{for(let p of t)await this.executeSingleFilterQuery(e,p,s,c,i)}catch(p){if(p.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...c.values()].sort((p,m)=>this.sortItems(p,m,s,o)),f=l===void 0?0:this.findCursorStartingIndex(u,o,s,l);if(f<0)return[];let h=d===void 0?void 0:f+d;return u.slice(f,h)}async executeSingleFilterQuery(e,t,n,i,s){let o=d=>{for(let l of d)if(!(i.has(l.messageCid)||!tr.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ne(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(Ml(t)){let d=await this.getAllItems(e,n);o(d);return}let a=$P.reduceFilter(t);for(let d in a){let l=a[d];if(tr.isEqualFilter(l)){let c=await this.filterExactMatches(e,d,l,s);o(c)}else if(tr.isOneOfFilter(l))for(let c of new Set(l)){let u=await this.filterExactMatches(e,d,c,s);o(u)}else if(tr.isRangeFilter(l)){let c=await this.filterRangeMatches(e,d,l,s);o(c)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[s,o]of n.iterator())i.push(JSON.parse(o));return i}async filterExactMatches(e,t,n,i){let s=r.keySegmentJoin(r.encodeValue(n)),o={gt:s},a=await this.getIndexPartition(e,t),d=[];for await(let[l,c]of a.iterator(o,i)){if(!l.startsWith(s))break;d.push(JSON.parse(c))}return d}async filterRangeMatches(e,t,n,i){let s={};for(let d in n){let l=d,c=r.encodeValue(n[l]);l==="lte"?s[l]=c+"\xFF":s[l]=c}s.gt===void 0&&s.gte===void 0&&(s.reverse=!0);let o=[],a=await this.getIndexPartition(e,t);for await(let[d,l]of a.iterator(s,i))"gt"in n&&this.extractIndexValueFromKey(d)===r.encodeValue(n.gt)||o.push(JSON.parse(l));return o}sortItems(e,t,n,i){let s=e.indexes[n],o=t.indexes[n],a=r.encodeValue(s)+e.messageCid,d=r.encodeValue(o)+t.messageCid;return i===It.Ascending?j0(a,d):j0(d,a)}findCursorStartingIndex(e,t,n,i){let s=d=>{let{messageCid:l,indexes:c}=d,u=c[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===It.Ascending?f>i:f<i},o=0,a=e.length;for(;o<a;){let d=o+a>>>1;s(e[d])?a=d:o=d+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,s=e<0?n:"",o=e<0?t:0;return s+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 QE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*m0e(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],s=er.asCID(n);s?yield[i.join("/"),s]:typeof n=="object"&&(yield*c$(n,i))}else{let t=er.asCID(e);t?yield[r.join("/"),t]:yield*c$(e,r)}}function*c$(r,e){if(r==null||r instanceof Uint8Array)return;let t=er.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let s=[...e,n];yield*m0e(s,i)}}function*y0e(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!er.asCID(n)&&(yield*d$(n,i))}else yield*d$(e,r)}function*d$(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"&&!er.asCID(n)&&(yield*y0e(i,n))}}function g0e(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 s=er.asCID(t);if(s)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}async function NH({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),s=er.create(1,e.code,i);return new XE({value:r,bytes:n,cid:s})}async function MH({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),s=er.create(1,e.code,i);return new XE({value:n,bytes:r,cid:s})}var XE,UH=G(()=>{g();v0();pk();XE=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:QE(),bytes:QE(),value:QE(),asBlock:QE()})}links(){return c$(this.value,[])}tree(){return d$(this.value,[])}get(e="/"){return g0e(this.value,e.split("/").filter(Boolean))}}});var v0e,hm,KH=G(()=>{"use strict";g();UH();xy();AE();Nl();Ol();lh();kE();a$();vr();Bu();Ed();v0e=[{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"}],hm=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:os,...e},this.blockstore=new uh({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new fm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??v0e})}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 Xn(this.blockstore.partition(e),n?.signal),s=er.parse(t),o=await i.get(s,n);return o?(await Xn(MH({bytes:o,codec:$l,hasher:Kn}),n?.signal)).value:void 0}async query(e,t,n,i,s){s?.signal?.throwIfAborted();let o=r.buildQueryOptions(n,i),a=await this.index.query(e,t,o,s),d;i?.limit!==void 0&&i.limit<a.length&&(a.splice(-1),d=fm.createCursorFromLastArrayItem(a,o.sortProperty));let l=[];for(let c=0;c<a.length;c++){let{messageCid:u}=a[c],f=await this.get(e,u,s);f&&l.push(f)}return{messages:l,cursor:d}}async count(e,t,n,i){i?.signal?.throwIfAborted();let s=r.buildQueryOptions(n);return this.index.count(e,t,s,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:s,datePublished:o,messageTimestamp:a}=e,d=It.Ascending,l="messageTimestamp";return s!==void 0?l="dateCreated":o!==void 0?l="datePublished":a!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(d=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:d,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Xn(this.blockstore.partition(e),n?.signal),s=er.parse(t);await i.delete(s,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let s=await Xn(this.blockstore.partition(e),i?.signal),o=await Xn(NH({value:t,codec:$l,hasher:Kn}),i?.signal),a=pr.parseCid(await ye.getCid(t));await s.put(a,o.bytes,i);let d=a.toString();await this.index.put(e,d,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var pm,LH=G(()=>{"use strict";g();Nl();lh();pm=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:os,...e},this.db=new rc({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 pr.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 s=JSON.parse(i);if(Date.now()>=s.timeout&&(s.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,s.retryCount++,await this.db.put(s.id,JSON.stringify(s)),t.push(s)),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 qH(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 zH=G(()=>{g()});var FH,mm,GH=G(()=>{"use strict";g();zH();$c();xt();FH="events",mm=class r{emitter=qH();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),s=>s.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){let d=this.tenantLogs.get(e);if(d!==void 0&&d.size>0){let l=d.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}else i="epoch_mismatch";let s=await this.getReplayBounds(e),o={requested:t,oldestAvailable:s?.oldest??t,latestAvailable:s?.latest??t,reason:i},a=new ne(re.EventLogProgressGap,`progress token gap: ${i}`);throw a.gapInfo=o,a}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 ne(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let a=this.tenantLogs.get(e);if(a===void 0&&(a=new Map,this.tenantLogs.set(e,a)),a.set(o,{event:t,indexes:n,messageCid:i}),a.size>this.maxEventsPerTenant){let l=a.size-this.maxEventsPerTenant,c=0;for(let u of a.keys()){if(c>=l)break;a.delete(u),c++}}let d=`${e}_${FH}`;return this.emitter.emit(d,{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:s}=t;n!==void 0&&await this.validateCursor(e,n);let o=n===void 0?void 0:r.parsePosition(n.position),a=this.tenantLogs.get(e);if(a===void 0||a.size===0)return{events:[],cursor:n};let d=[],l=i??Number.MAX_SAFE_INTEGER;for(let[c,u]of a)if(!(o!==void 0&&c<=o)&&!(s!==void 0&&s.length>0&&!tr.matchAnyFilter(u.indexes,s))&&(d.push({seq:c,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),d.length>=l))break;if(d.length>0){let c=d[d.length-1],u=await this.buildToken(e,c.seq,c.messageCid);return{events:d,cursor:u}}return{events:d,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ne?t:new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let s=`${e}_${FH}`,{cursor:o,filters:a}=i??{},d=async c=>this.buildToken(e,c.seq,c.messageCid);if(o!==void 0){await this.validateCursor(e,o);let c=r.parsePosition(o.position),u=[],f=!1,h=v=>{a!==void 0&&a.length>0&&!tr.matchAnyFilter(v.indexes,a)||(f?d(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(s,h);let p=await this.read(e,{cursor:o,filters:a}),m=p.cursor??o,y=p.cursor===void 0?c:r.parsePosition(p.cursor.position);for(let v of p.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(s,h)}}}let l=c=>{a!==void 0&&a.length>0&&!tr.matchAnyFilter(c.indexes,a)||d(c).then(u=>{n({type:"event",cursor:u,event:c.event})})};return this.emitter.on(s,l),{id:t,close:async()=>{this.emitter.off(s,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],s=n[n.length-1],o=t.get(i),a=t.get(s),d=await this.buildToken(e,i,o.messageCid),l=await this.buildToken(e,s,a.messageCid);return{oldest:d,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,s]of n)(s.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var nw,l$=G(()=>{"use strict";g();Rf();nw=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=dn(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=dn(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=dn(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return If(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",dn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:dn(e.leftHash),rightHash:dn(e.rightHash)}:{type:"leaf",keyHash:dn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:If(e.leftHash),rightHash:If(e.rightHash)}:{type:"leaf",keyHash:If(e.keyHash),valueCid:e.valueCid}}}});var iw,u$=G(()=>{"use strict";g();Rf();iw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await tu()}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 Af(e),n=await fg(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let s=await this.getRoot(),o=await this.insertAtNode(s,t,n,i,0);return await this.store.setRoot(o),o}async delete(e){let t=await Af(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 Af(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Af(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(cn(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?.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let s=i;e[n]?t=s.rightHash:t=s.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(cn(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 s=i;e[n]?t=s.rightHash:t=s.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(cn(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],s=[];return await this.diffAtNode(t,n,0,this,e,i,s),{onlyLocal:i,onlyRemote:s}}async insertAtNode(e,t,n,i,s){if(s>=_o||cn(e,this.defaultHashes[s]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return cn(o.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,i,n,s);let a=o,d=xs(t,s),l,c;d?(l=a.leftHash,c=await this.insertAtNode(a.rightHash,t,n,i,s+1)):(l=await this.insertAtNode(a.leftHash,t,n,i,s+1),c=a.rightHash);let u=await ru(l,c);if(!cn(u,e)){let f={type:"internal",leftHash:l,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,s){let o=s;for(;o<_o&&xs(e.keyHash,o)===xs(n.keyHash,o);)o++;if(o>=_o)return i;let a=xs(e.keyHash,o),d,l;a?(d=i,l=t):(d=t,l=i);let c=await ru(d,l);await this.store.putNode(c,{type:"internal",leftHash:d,rightHash:l});for(let u=o-1;u>=s;u--){let f=xs(e.keyHash,u),h=this.defaultHashes[u+1],p,m;f?(p=h,m=c):(p=c,m=h),c=await ru(p,m),await this.store.putNode(c,{type:"internal",leftHash:p,rightHash:m})}return c}async deleteAtNode(e,t,n){if(n>=_o)return this.defaultHashes[_o];if(cn(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 cn(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let s=i,o=xs(t,n),a,d;if(o?(a=s.leftHash,d=await this.deleteAtNode(s.rightHash,t,n+1)):(a=await this.deleteAtNode(s.leftHash,t,n+1),d=s.rightHash),cn(a,this.defaultHashes[n+1])&&cn(d,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=cn(a,this.defaultHashes[n+1]),c=cn(d,this.defaultHashes[n+1]);if(l||c){let f=l?d:a;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let u=await ru(a,d);if(!cn(u,e)){let f={type:"internal",leftHash:a,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=_o||cn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return cn(i.keyHash,t);let s=i;return xs(t,n)?this.existsAtNode(s.rightHash,t,n+1):this.existsAtNode(s.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=_o)return{siblings:[],leafNode:void 0,depth:n};if(cn(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 s=i,o=xs(t,n),a,d;o?(a=s.rightHash,d=s.leftHash):(a=s.leftHash,d=s.rightHash);let l=await this.generateProof(a,t,n+1);return l.siblings.unshift(d),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(xs(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await fg(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(xs(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=_o||cn(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,s=await this.collectLeaves(i.leftHash,t+1),o=await this.collectLeaves(i.rightHash,t+1);return[...s,...o]}async diffAtNode(e,t,n,i,s,o,a){if(cn(e,t)||n>=_o)return;let d=cn(e,this.defaultHashes[n]),l=cn(t,this.defaultHashes[n]);if(d&&!l){let f=await s.collectLeaves(t,n);a.push(...f);return}if(!d&&l){let f=await i.collectLeaves(e,n);o.push(...f);return}let c=await i.store.getNode(e),u=await s.store.getNode(t);if(c?.type==="leaf"&&u?.type==="leaf"){cn(c.keyHash,u.keyHash)?c.valueCid!==u.valueCid&&(o.push(c.valueCid),a.push(u.valueCid)):(o.push(c.valueCid),a.push(u.valueCid));return}if(c?.type==="leaf"){let f=await s.collectLeaves(t,n),h=c.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&a.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),h=u.valueCid;new Set(f).has(h)||a.push(h);for(let m of f)m!==h&&o.push(m);return}if(c?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(c.leftHash,u.leftHash,n+1,i,s,o,a),await this.diffAtNode(c.rightHash,u.rightHash,n+1,i,s,o,a);return}if(c===void 0){let f=await s.collectLeaves(t,n);a.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);o.push(...f)}}}});var ym,WH=G(()=>{"use strict";g();Rf();l$();u$();lh();ym=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:os,...e}}async open(){this.db=new rc({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await tu()}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 s=n.protocol;s!==void 0&&await(await this.getProtocolTree(e,s)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let s=await this.getStoredIndexes(e,i);if(await n.delete(i),s!==void 0){let o=s.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 nw(n),s=new iw(i);return await s.initialize(),s}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),s={protocol:n.protocol};await i.put(t,JSON.stringify(s))}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 eS,HH=G(()=>{"use strict";g();Rf();eS=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(dn(e))}async putNode(e,t){this.nodes.set(dn(e),t)}async deleteNode(e){this.nodes.delete(dn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var b0e,tS,VH=G(()=>{"use strict";g();xy();Ol();ef();is();yT();Cn();sd();__();T_();ia();Px();f2();p2();ni();b_();hb();x_();P2();Zo();He();ix();Bu();Yo();gn();nv();lr();jy();b0e={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},tS=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}`,s=e?.keyPair??await dc.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let d=await kt.generateKey();o={publicJwk:await kt.getPublicKey({key:d}),privateJwk:d}}return{did:t,keyId:i,keyPair:s,encryptionKeyPair:o,signer:new Al({privateJwk:s.privateJwk,algorithm:s.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await Ka.create({definition:b0e,signer:lt.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 a="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[a]={schema:"test-object",dataFormats:["text/plain"]},n.structure[a]={}}let i=lt.createSigner(t),s={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await Ka.create(s);return{author:t,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=lt.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Mt(i);let s=await La.create(i);return{author:t,message:s.message,protocolsQuery:s}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??At.createOffsetTimestamp({seconds:10}),s=e?.scope??{interface:xe.Messages,method:me.Read},o=lt.createSigner(t),a=n.did,d={signer:o,grantedTo:a,dateExpires:i,scope:s,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await Qe.createGrant(d);return{dataStream:Et.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=lt.createSigner(t),i=lt.createSigners(e?.attesters??[]),s=e?.dataCid,o=e?.dataSize,a,d;s===void 0&&o===void 0&&(a=e?.data??r.randomBytes(32),d=Et.fromBytes(a));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:a,dataCid:s,dataSize:o,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},c=await _t.create(l),u=c.message;return{author:t,message:u,dataCid:s,dataSize:o,dataBytes:a,dataStream:d,recordsWrite:c}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:s,protocolPath:o,protocolParentContextId:a,protocolContextDerivingRootKeyId:d,protocolContextDerivedPublicKeyJwk:l}=e,c=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:h}=await Ai.aeadEncrypt(pi.A256GCM,u,c,t),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:s.protocol,protocolPath:o,parentContextId:a,schema:s.types[m].schema,dataFormat:s.types[m].dataFormats?.[0],data:f}),b={initializationVector:c,key:u,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let T=s.structure;for(let C of p)T=T[C];let D=T.$encryption?.publicKeyJwk,M={publicKeyId:T.$encryption?.rootKeyId,publicKey:D,derivationScheme:St.ProtocolPath};b.keyEncryptionInputs.push(M)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let T;if(a===void 0){let D={rootKeyId:n.keyId,derivationScheme:St.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},I=await _t.getEntryId(n.did,y.descriptor),M=ke.constructKeyDerivationPathUsingProtocolContextScheme(I),C=await zi.derivePublicKey(D,M);T={publicKeyId:n.keyId,publicKey:C,derivationScheme:St.ProtocolContext}}else{if(d===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");T={publicKeyId:d,publicKey:l,derivationScheme:St.ProtocolContext}}b.keyEncryptionInputs.push(T)}return await w.encryptSymmetricEncryptionKey(b),await w.sign({signer:lt.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:b}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=At.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),s=e.datePublished??(i?n:void 0),o=e.data??r.randomBytes(32),a=Et.fromBytes(o),d={recordsWriteMessage:e.existingWrite.message,data:o,published:i,datePublished:s,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:lt.createSigner(e.author)},l=await _t.createFrom(d);return{message:l.message,recordsWrite:l,dataBytes:o,dataStream:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Mt(s);let a=(await $a.create(s)).message;return{author:t,message:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Mt(s);let a=(await za.create(s)).message;return{author:t,message:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};Mt(s);let a=(await Md.create(s)).message;return{author:t,message:a}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await qa.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:lt.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=lt.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Mt(i);let s=await Kd.create(i),o=s.message;return{author:t,messagesSubscribe:s,message:o}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:lt.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},s=await Ud.create(i);return{author:t,messagesRead:s,message:s.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Cw.generateKeyPair(),t=await Cw.sign(r.randomBytes(32),e.privateJwk);return Ie.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 Kn.digest(e);return(await er.createV1(Xu,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:s,minute:o,second:a,millisecond:d,microsecond:l}=e||{};return At.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:s||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:a||this.randomInt(0,59),millisecond:d||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 sm.create(),t=await sm.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),s={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},o=await kt.generateKey(),d={publicJwk:await kt.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:s,encryptionKeyPair:d,signer:new Al({privateJwk:s.privateJwk,algorithm:s.privateJwk.alg,keyId:n})}}}});var rS,JH=G(()=>{"use strict";g();He();rS=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 yd(t)}}}});var YH={};ir(YH,{AllowAllTenantGate:()=>lg,BlockstoreLevel:()=>uh,Cid:()=>pr,ContentEncryptionAlgorithm:()=>pi,CoreProtocolRegistry:()=>dg,DataStoreLevel:()=>um,DataStream:()=>Et,DateSort:()=>Ut,Dwn:()=>Qg,DwnConstant:()=>bs,DwnError:()=>ne,DwnErrorCode:()=>re,DwnInterfaceName:()=>xe,DwnMethodName:()=>me,Encoder:()=>Ie,Encryption:()=>Ai,EventEmitterEventLog:()=>mm,HdKey:()=>zi,IndexLevel:()=>fm,Jws:()=>lt,KeyAgreementAlgorithm:()=>rv,KeyDerivationScheme:()=>St,LevelWrapper:()=>rc,Message:()=>ye,MessageStoreLevel:()=>hm,MessagesRead:()=>Ud,MessagesSubscribe:()=>Kd,MessagesSync:()=>Cf,PERMISSIONS_REVOCATION_PATH:()=>OP,PermissionConditionPublication:()=>Ny,PermissionGrant:()=>Ht,PermissionRequest:()=>Oa,PermissionsProtocol:()=>Qe,Poller:()=>rS,PrivateKeySigner:()=>Al,ProtocolRecordLimitStrategy:()=>Cu,Protocols:()=>Gd,ProtocolsConfigure:()=>Ka,ProtocolsQuery:()=>La,Records:()=>ke,RecordsCount:()=>Md,RecordsDelete:()=>qa,RecordsQuery:()=>$a,RecordsRead:()=>Hd,RecordsSubscribe:()=>za,RecordsWrite:()=>_t,ResumableTaskStoreLevel:()=>pm,SMTStoreLevel:()=>nw,SMTStoreMemory:()=>eS,SMT_DEPTH:()=>_o,Secp256k1:()=>dc,Secp256r1:()=>kl,SortDirection:()=>It,SparseMerkleTree:()=>iw,StateIndexLevel:()=>ym,TestDataGenerator:()=>tS,Time:()=>At,ZERO_HASH:()=>k_,authenticate:()=>bn,createLevelDatabase:()=>os,executeUnlessAborted:()=>Xn,getBit:()=>xs,getDefaultHashes:()=>ER,getRuleSetAtPath:()=>Wd,hashChildren:()=>ru,hashEquals:()=>cn,hashKey:()=>Af,hashLeaf:()=>fg,hashToHex:()=>dn,hexToHash:()=>If,initDefaultHashes:()=>tu,isCrossProtocolRef:()=>qf,parseCrossProtocolRef:()=>es});var fn=G(()=>{"use strict";g();kw();ra();xR();oI();PR();Nl();b_();x_();ef();jy();gW();ug();xt();lr();Cn();T_();nv();Zo();kE();sd();vr();__();SR();Tc();_R();ia();Px();Np();f2();p2();ni();hb();T6();P2();ix();vD();Ed();Yo();sI();rp();AE();TH();a$();lh();KH();LH();GH();WH();u$();l$();HH();Rf();VH();JH()});var cS=Te((aYe,oV)=>{g();var dw=1e3,lw=dw*60,uw=lw*60,Pm=uw*24,$0e=Pm*7,O0e=Pm*365.25;oV.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return B0e(r);if(t==="number"&&isFinite(r))return e.long?N0e(r):j0e(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function B0e(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*O0e;case"weeks":case"week":case"w":return t*$0e;case"days":case"day":case"d":return t*Pm;case"hours":case"hour":case"hrs":case"hr":case"h":return t*uw;case"minutes":case"minute":case"mins":case"min":case"m":return t*lw;case"seconds":case"second":case"secs":case"sec":case"s":return t*dw;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function j0e(r){var e=Math.abs(r);return e>=Pm?Math.round(r/Pm)+"d":e>=uw?Math.round(r/uw)+"h":e>=lw?Math.round(r/lw)+"m":e>=dw?Math.round(r/dw)+"s":r+"ms"}function N0e(r){var e=Math.abs(r);return e>=Pm?aS(r,e,Pm,"day"):e>=uw?aS(r,e,uw,"hour"):e>=lw?aS(r,e,lw,"minute"):e>=dw?aS(r,e,dw,"second"):r+" ms"}function aS(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();function zbe(r,e){return{definition:r}}g();g();g();fn();fn();var ve;(function(r){r.MessagesRead="MessagesRead",r.MessagesSubscribe="MessagesSubscribe",r.MessagesSync="MessagesSync",r.ProtocolsConfigure="ProtocolsConfigure",r.ProtocolsQuery="ProtocolsQuery",r.RecordsDelete="RecordsDelete",r.RecordsQuery="RecordsQuery",r.RecordsRead="RecordsRead",r.RecordsSubscribe="RecordsSubscribe",r.RecordsWrite="RecordsWrite"})(ve||(ve={}));var gm={[ve.MessagesRead]:Ud,[ve.MessagesSubscribe]:Kd,[ve.MessagesSync]:Cf,[ve.ProtocolsConfigure]:Ka,[ve.ProtocolsQuery]:La,[ve.RecordsDelete]:qa,[ve.RecordsQuery]:$a,[ve.RecordsRead]:Hd,[ve.RecordsSubscribe]:za,[ve.RecordsWrite]:_t};g();var x0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function f$(r){return x0e(this,void 0,void 0,function*(){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort((l,c)=>l.localeCompare(c))),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort((l,c)=>l.localeCompare(c))));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=yield crypto.subtle.digest("SHA-256",n),s=new Uint8Array(i),o="";for(let l of s)o+=String.fromCharCode(l);let a=btoa(o).replaceAll("+","-").replaceAll("/","_"),d=a.length;for(;d>0&&a.codePointAt(d-1)===61;)d--;return d===a.length?a:a.slice(0,d)})}var h$=100;g();var xu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},ZH=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(s){t[s]=r[s]&&function(o){return new Promise(function(a,d){o=r[s](o),i(a,d,o.done,o.value)})}}function i(s,o,a,d){Promise.resolve(d).then(function(l){s({value:l,done:a})},o)}},p$="^",ho=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${p$}${t}${p$}${n}`}getOrCreateLink(e){return xu(this,void 0,void 0,function*(){let t=yield f$(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let s=yield this.sublevel.get(n),o=JSON.parse(s);return delete o.push,o.connectivity="unknown",o}catch(s){if(s.code!=="LEVEL_NOT_FOUND")throw s}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 yield this.sublevel.put(n,JSON.stringify(i)),i})}saveLink(e){return xu(this,void 0,void 0,function*(){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),yield this.sublevel.put(t,JSON.stringify(e))})}deleteLink(e,t,n){return xu(this,void 0,void 0,function*(){let i=r.buildKey(e,t,n);yield this.sublevel.del(i)})}getLinksForTenant(e){return xu(this,void 0,void 0,function*(){var t,n,i,s;let o=`${e}${p$}`,a=[];try{for(var d=!0,l=ZH(this.sublevel.iterator()),c;c=yield l.next(),t=c.done,!t;d=!0){s=c.value,d=!1;let[u,f]=s;u.startsWith(o)&&a.push(JSON.parse(f))}}catch(u){n={error:u}}finally{try{!d&&!t&&(i=l.return)&&(yield i.call(l))}finally{if(n)throw n.error}}return a})}getAllLinks(){return xu(this,void 0,void 0,function*(){var e,t,n,i;let s=[];try{for(var o=!0,a=ZH(this.sublevel.iterator()),d;d=yield a.next(),e=d.done,!e;o=!0){i=d.value,o=!1;let[,l]=i;s.push(JSON.parse(l))}}catch(l){t={error:l}}finally{try{!o&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(t)throw t.error}}return s})}updateDelegateDid(e,t){return xu(this,void 0,void 0,function*(){let n=yield this.getLinksForTenant(e),i=[];for(let s of n)s.delegateDid!==t&&(s.delegateDid=t,yield this.saveLink(s),i.push(s));return i})}setStatus(e,t){return xu(this,void 0,void 0,function*(){e.status=t,yield 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}markNeedsReconcile(e,t){return xu(this,void 0,void 0,function*(){e.needsReconcile||(e.needsReconcile=!0,yield this.saveLink(e))})}clearNeedsReconcile(e){return xu(this,void 0,void 0,function*(){e.needsReconcile&&(e.needsReconcile=!1,yield this.saveLink(e))})}};g();var oi;(function(r){r.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",r.InitialWriteMissing="ClosureInitialWriteMissing",r.ParentChainMissing="ClosureParentChainMissing",r.ContextChainMissing="ClosureContextChainMissing",r.GrantMissing="ClosureGrantMissing",r.GrantNotYetActive="ClosureGrantNotYetActive",r.GrantExpired="ClosureGrantExpired",r.GrantRevocationMissing="ClosureGrantRevocationMissing",r.VisibilityFloorMissing="ClosureVisibilityFloorMissing",r.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",r.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",r.DependencyForbidden="ClosureDependencyForbidden",r.DepthExceeded="ClosureDepthExceeded"})(oi||(oi={}));function nS(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 QH(r,e){var t;let n=e.descriptor;if(n.interface==="Protocols"&&n.method==="Configure"){let i=n.definition?n.definition.protocol:void 0;i&&r.protocolCache.delete(i)}if(n.protocol==="https://identity.foundation/dwn/permissions"){let i=e.recordId,s=n.protocolPath;if(s==="grant"&&i&&(r.grantCache.delete(i),r.satisfiedDeps.delete(`permissionGrant:grantId:${i}`),r.missingDeps.delete(`permissionGrant:grantId:${i}`)),s==="grant/revocation"){let o=n.parentId;o&&(r.grantCache.delete(`revocation:${o}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${o}`),r.missingDeps.delete(`grantRevocation:grantId:${o}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${o}`),r.missingDeps.delete(`permissionGrant:grantId:${o}`))}}if(n.interface==="Records"){let i=e.recordId,s=n.protocol,o=n.protocolPath;if(i){let a=d=>{let l=d.indexOf(i);if(l===-1)return!1;let c=l>0?d[l-1]:":",u=l+i.length<d.length?d[l+i.length]:"|",f=c===":"||c==="|",h=u==="|"||u===void 0;return f&&(l+i.length===d.length||h)};for(let d of r.satisfiedDeps)a(d)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)a(d)&&r.missingDeps.delete(d)}if(s&&o){let a=`filter:${s}|${o}`;for(let d of r.satisfiedDeps)d.includes(a)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)d.includes(a)&&r.missingDeps.delete(d)}if(s==="https://identity.foundation/protocols/key-delivery"){let a=(t=e.descriptor)===null||t===void 0?void 0:t.tags,d=a?.protocol;if(d){let l=`messageCid:${d}|`;for(let c of r.satisfiedDeps)c.includes(l)&&r.satisfiedDeps.delete(c);for(let c of r.missingDeps)c.includes(l)&&r.missingDeps.delete(c)}}else if(s){let a=`messageCid:${s}|`;for(let d of r.satisfiedDeps)d.includes(a)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)d.includes(a)&&r.missingDeps.delete(d)}}}g();fn();g();function XH(r,e){let[t,...n]=e.split("/"),i=r.structure[t];for(let s of n){if(!i)return;i=i[s]}return i}function wm(r,e){let t=XH(r,e);if(!t)return!1;function n(i){for(let s in i)if(!s.startsWith("$")){let o=i[s];if(o.$role===!0||n(o))return!0}return!1}return n(t)?!0:m$(void 0,e,r)}function m$(r,e,t){function n(i){var s;if(i.$actions){for(let o of i.$actions)if(o.who&&o.who!=="anyone"&&(r===void 0||o.who===r)&&o.of===e&&(!((s=o.can)===null||s===void 0)&&s.includes("read")))return!0}for(let o in i)if(!o.startsWith("$")&&n(i[o]))return!0;return!1}for(let i in t.structure)if(n(t.structure[i]))return!0;return!1}function y$({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let s=new Set,o=XH(r,e);return o&&(o.$role===!0&&t&&s.add(t),t&&t!==n&&m$("recipient",e,r)&&s.add(t),i&&i!==n&&m$("author",e,r)&&s.add(i),s.delete(n)),s}var g$=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function P0e(r){let t=r.descriptor.protocol;return t?t===Qe.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function _0e(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 s=r.contextId;if(s&&n&&s!==n){let o=s.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:o,identifierType:"recordId"})}if(n&&e.method==="Write"){let o=e.dateCreated,a=e.messageTimestamp;o&&a&&o!==a&&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 E0e(r){var e;let t=[],n=r.authorization;if(!n)return[];let i=(e=n.signature)===null||e===void 0?void 0:e.payload;if(i)try{let s=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));s.permissionGrantId&&(t.push({dependencyClass:3,label:"permissionGrant",identifier:s.permissionGrantId,identifierType:"grantId"}),t.push({dependencyClass:3,label:"grantRevocation",identifier:s.permissionGrantId,identifierType:"grantId"}))}catch{}return t}function S0e(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let s of t){if(!Object.hasOwn(n,s))return;i=n[s],n=i}return i}function T0e(r,e,t){var n,i,s;let o=r.descriptor;if(o.interface!=="Records")return[];let a=o.protocolPath;if(!a)return[];let d=[],l=S0e(e?.structure,a);if(l?.$encryption){let h=a.split("/").pop(),p=(n=e?.types)===null||n===void 0?void 0:n[h??""];if(p?.encryptionRequired===!0){d.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:o.protocol,identifierType:"protocol"});let m=r.contextId,y=!1;if(m){let w=a.split("/")[0];y=wm(e,w)}if(t&&!y||d.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"}),y&&m){let w=m.split("/")[0];d.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${o.protocol}|${w}`,identifierType:"messageCid"})}}}let c=a.split("/")[0],u=(i=e?.structure)===null||i===void 0?void 0:i[c];if(u?.$ref){let h=u.$ref.indexOf(":");if(h>0){let p=u.$ref.substring(0,h),m=e?.uses,y=m?.[p];if(y){d.push({dependencyClass:6,label:"crossProtocolConfig",identifier:y,identifierType:"protocol"});let v=a.split("/"),w=o.parentId;v.length===2&&w&&d.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${y}|${w}`,identifierType:"recordId"})}}}let f=r.authorization;if(f&&e?.uses){let h=(s=f.signature)===null||s===void 0?void 0:s.payload;if(h)try{let m=JSON.parse(Buffer.from(h,"base64url").toString("utf-8")).protocolRole;if(m?.includes(":")){let y=m.indexOf(":"),v=m.substring(0,y),w=e.uses[v];if(w){d.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:w,identifierType:"protocol"});let b=m.substring(y+1),T=ye.getAuthor(r),D=r.contextId;if(T){let I={interface:"Records",method:"Write",protocol:w,protocolPath:b,recipient:T,isLatestBaseState:!0};if(D){let C=b.split("/").length-1;if(C>0){let L=D.split("/").slice(0,C).join("/");L&&(I.contextId={gte:L,lt:L+"\uFFFF"})}}let M=I.contextId?JSON.stringify(I.contextId):"no-context";d.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${w}|${b}|${T}|${M}`,identifierType:"filter",filter:I})}}}}catch{}}return d}function w$(r,e,t,n){return g$(this,void 0,void 0,function*(){var i;if(t.kind==="full")return{complete:!0,rootMessageCid:yield ye.getCid(r),edges:[],depth:0};let s=yield ye.getCid(r),o=[],a=new Set,d=0,l=[r];for(a.add(s);l.length>0;){if(d>=n.maxDepth)return{complete:!1,rootMessageCid:s,edges:o,failure:{code:oi.DepthExceeded,edge:{dependencyClass:1,label:"depth",identifier:String(d),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:d};let c=l.length;for(let u=0;u<c;u++){let f=l.shift(),h=[...P0e(f),..._0e(f),...E0e(f)],p=yield eV(h,o,e,n,a,l,s,d);if(p)return p;let y=f.descriptor.protocol;if(y){let v=n.protocolCache.get(y),w=(i=v?.descriptor)===null||i===void 0?void 0:i.definition;if(w){let b=T0e(f,w,n.isDelegateSession),T=yield eV(b,o,e,n,a,l,s,d);if(T)return T}}if(d===0){let v=D0e(f,o,n,s,d);if(v)return v}}d++}return{complete:!0,rootMessageCid:s,edges:o,depth:d}})}function D0e(r,e,t,n,i){var s;let o=e.find(p=>p.label==="permissionGrant");if(!o)return null;let a=r.descriptor.messageTimestamp;if(!a)return null;let d=t.grantCache.get(o.identifier);if(!d)return null;let l=d.descriptor.dateCreated,c,u=d.encodedData;if(u)try{c=JSON.parse(Buffer.from(u,"base64url").toString("utf-8")).dateExpires}catch{}if(l&&a<l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantNotYetActive,edge:o,detail:`grant '${o.identifier}' is not yet active at message timestamp ${a} (dateGranted: ${l})`},depth:i};if(c&&a>=c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantExpired,edge:o,detail:`grant '${o.identifier}' expired at ${c}, message timestamp is ${a}`},depth:i};let f=`revocation:${o.identifier}`,h=t.grantCache.get(f);if(h&&h.descriptor.interface!=="Synthetic"){let p=h.descriptor.messageTimestamp;if(p&&p<=a)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantRevocationMissing,edge:(s=e.find(m=>m.label==="grantRevocation"))!==null&&s!==void 0?s:o,detail:`grant '${o.identifier}' was revoked at ${p}, before message timestamp ${a}`},depth:i}}return null}function eV(r,e,t,n,i,s,o,a){return g$(this,void 0,void 0,function*(){for(let d of r){e.push(d);let l=`${d.label}:${d.identifierType}:${d.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:o,edges:e,failure:{code:tV(d),edge:d,detail:`dependency '${d.label}' (${d.identifier}) is missing`},depth:a};let c=yield k0e(d,t,n);if(!c)return n.missingDeps.add(l),{complete:!1,rootMessageCid:o,edges:e,failure:{code:tV(d),edge:d,detail:`dependency '${d.label}' (${d.identifier}) not found locally`},depth:a};if(n.satisfiedDeps.add(l),!(d.identifierType==="grantId"||d.identifierType==="filter"||d.label==="contextKeyRecord")){let f=yield ye.getCid(c);i.has(f)||(i.add(f),s.push(c))}}return null})}function k0e(r,e,t){return g$(this,void 0,void 0,function*(){var n,i,s,o;switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return(n=t.protocolCache.get(r.identifier))!==null&&n!==void 0?n:null;let{messages:a}=yield e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),d=a.length>0?a[0]:null;return t.protocolCache.set(r.identifier,d),d}case"recordId":{if(r.label==="initialWrite"){let{messages:d}=yield e.query(t.tenantDid,[{entryId:r.identifier}]);if(d.length>0)return d[0];let{messages:l}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return l.length>0?l[0]:null}if(r.label==="crossProtocolParent"){let d=r.identifier.indexOf("|");if(d>0){let l=r.identifier.substring(0,d),c=r.identifier.substring(d+1),{messages:u}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:l,recordId:c,isLatestBaseState:!0}]);return u.length>0?u[0]:null}}let{messages:a}=yield e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return a.length>0?a[0]:null}case"grantId":{if(r.label==="grantRevocation"){let l=`revocation:${r.identifier}`;if(t.grantCache.has(l))return(i=t.grantCache.get(l))!==null&&i!==void 0?i:null;let{messages:c}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),u;for(let p of c){let m=p.descriptor.messageTimestamp;(!u||m<u.descriptor.messageTimestamp)&&(u=p)}let h=u??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(l,h),h}if(t.grantCache.has(r.identifier))return(s=t.grantCache.get(r.identifier))!==null&&s!==void 0?s:null;let{messages:a}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),d=a.length>0?a[0]:null;return t.grantCache.set(r.identifier,d),d}case"messageCid":{if(r.label==="contextKeyRecord"){let a=r.identifier.indexOf("|");if(a>0){let d=r.identifier.substring(0,a),l=r.identifier.substring(a+1),{messages:c}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":d,"tag.contextId":l}]);return c.length>0?c[0]:null}}return(o=yield e.get(t.tenantDid,r.identifier))!==null&&o!==void 0?o:null}case"filter":{if(!r.filter)return null;let{messages:a}=yield e.query(t.tenantDid,[r.filter]);return a.length>0?a[0]:null}default:return null}})}function tV(r){switch(r.dependencyClass){case 1:return oi.ProtocolMetadataMissing;case 2:return r.label==="initialWrite"?oi.InitialWriteMissing:r.label==="parentRecord"?oi.ParentChainMissing:r.label==="contextRoot"?oi.ContextChainMissing:oi.ParentChainMissing;case 3:return r.label==="permissionGrant"?oi.GrantMissing:oi.GrantRevocationMissing;case 4:return r.label==="squashContextRoot"?oi.VisibilityFloorMissing:oi.VisibilityFloorMissing;case 5:return oi.EncryptionDependencyMissing;case 6:return oi.CrossProtocolReferenceMissing;default:return oi.DependencyForbidden}}g();is();He();var A0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},vm=class extends DE{constructor({agent:e,db:t,location:n,ttl:i}){super({db:t,location:n,ttl:i}),this._resolving=new Map,this._agent=e}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(e){this._agent=e}get(e){return A0e(this,void 0,void 0,function*(){try{let t=yield this.cache.get(e),n=JSON.parse(t);if(!this._resolving.has(e)&&Date.now()>=n.ttlMillis){this._resolving.set(e,!0);let i=yield this.agent.did.get({didUri:e,tenant:this.agent.agentDid.uri});if(typeof i>"u")this._resolving.delete(e),this.cache.nextTick(()=>this.cache.del(e));else try{let s=yield this.agent.did.resolve(e);if(!s.didResolutionMetadata.error&&s.didDocument){let o=Object.assign(Object.assign({},i),{document:s.didDocument,metadata:s.didDocumentMetadata});try{yield this.agent.did.update({portableDid:o,tenant:this.agent.agentDid.uri,publish:!1})}catch(a){a.message&&!a.message.includes("No changes detected, update aborted")&&ki.error(`Error updating DID: ${a.message}`)}}}finally{this._resolving.delete(e)}}return n.value}catch(t){if(t.notFound)return;throw t}})}};g();var ph=class{constructor(e){this.agent=e.agent,this.did=e.did,this.delegateDid=e.delegateDid,this.recoveryPhrase=e.recoveryPhrase,this.identity=e.identity}};g();fn();g();is();fn();var bm=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function ow(r,e){return bm(this,void 0,void 0,function*(){let t=yield e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(k5.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(s=>typeof s=="string")?n:[];if(i.length>0)return i}return[]})}function Is(r){return ye.getAuthor(r)}function rV(r){let e=lt.decodePlainObjectPayload(r.authorization.signature);return e?.protocolRole}function ol(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===xe.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function I0e(r){return ye.getCid(r)}function nV(r,e){return bm(this,void 0,void 0,function*(){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:yield I0e(r),value:t}})}function iV(r,e=3e3,t=3e5,n){let i=Date.now()+t,s=null,o=!0;return new Promise((a,d)=>{n&&n.addEventListener("abort",()=>{o=!1,s!==null&&clearTimeout(s),console.log("Polling aborted by user"),a(null)});function l(){return bm(this,void 0,void 0,function*(){if(!o)return;let c=i-Date.now();if(c<=0){o=!1,console.log("Polling stopped: TTL reached"),a(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(c/1e3)}s)`);try{let u=yield r();if(u.ok){o=!1,s!==null&&clearTimeout(s),console.log("Polling stopped: Success condition met"),a(u);return}}catch(u){console.error("Error fetching data:",u),d(u)}o&&(s=setTimeout(l,e))})}l()})}function v$(r,e,t){return bm(this,void 0,void 0,function*(){if(!Number.isInteger(e)||e<1)throw new Error(`mapConcurrent: concurrency must be a positive integer, got ${e}`);if(r.length===0)return[];let n=new Array(r.length),i=0,s=()=>bm(this,void 0,void 0,function*(){for(;;){let d=i++;if(d>=r.length)return;n[d]=yield t(r[d],d)}}),o=Math.min(e,r.length),a=[];for(let d=0;d<o;d++)a.push(s());return yield Promise.all(a),n})}function iS(r,e,t){return bm(this,void 0,void 0,function*(){return v$(r,e,(n,i)=>bm(this,void 0,void 0,function*(){try{return{status:"fulfilled",value:yield t(n,i)}}catch(s){return{status:"rejected",reason:s}}}))})}var sw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},oS=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}recordsQuery(e,t){return sw(this,void 0,void 0,function*(){let n=yield $a.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}recordsRead(e,t){return sw(this,void 0,void 0,function*(){let n=yield Hd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}recordsSubscribe(e,t,n){return sw(this,void 0,void 0,function*(){let i=yield za.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,i.message,void 0,n)})}recordsCount(e,t){return sw(this,void 0,void 0,function*(){let n=yield Md.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}protocolsQuery(e,t){return sw(this,void 0,void 0,function*(){let n=yield La.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return yield this.sendRequest(e,n.message)})}sendRequest(e,t,n,i){return sw(this,void 0,void 0,function*(){let s=yield ow(e,this._didResolver),o=[];for(let a of s)try{if(i!==void 0){if(!(yield this._rpcClient.getServerInfo(a)).webSocketSupport){o.push({url:a,message:"WebSocket support is not enabled on the server."});continue}let c=new URL(a);c.protocol=c.protocol==="http:"?"ws:":"wss:",a=c.toString()}return yield this._rpcClient.sendDwnRequest({dwnUrl:a,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(d){o.push({url:a,message:d instanceof Error?d.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(o)}`)})}};g();var R0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},aw=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}export(){return R0e(this,void 0,void 0,function*(){return{portableDid:yield this.did.export(),metadata:Object.assign({},this.metadata)}})}};g();gn();var as=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},b$={"AES-GCM":{implementation:$y,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Oy,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:xd,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:AP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:RP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:Ac,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:Ac,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:pf,names:["SHA-256"],operations:["digest"]},X25519:{implementation:yf,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},ma=class{constructor(){this._algorithmInstances=new Map}bytesToPrivateKey(e){return as(this,arguments,void 0,function*({algorithm:t,privateKeyBytes:n}){let i=this.getAlgorithmName({algorithm:t});return yield this.getAlgorithm({algorithm:i}).bytesToPrivateKey({algorithm:t,privateKeyBytes:n})})}bytesToPublicKey(e){return as(this,arguments,void 0,function*({algorithm:t,publicKeyBytes:n}){let i=this.getAlgorithmName({algorithm:t});return yield this.getAlgorithm({algorithm:i}).bytesToPublicKey({algorithm:t,publicKeyBytes:n})})}decrypt(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.key});return yield this.getAlgorithm({algorithm:t}).decrypt(e)})}deriveKey(e){return as(this,void 0,void 0,function*(){var t,n;let i=this.getAlgorithmName({algorithm:e.algorithm}),s=this.getAlgorithm({algorithm:i}),o;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{o=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{o=e.algorithm.split(/[-+]/)[2];break}default:throw new ze(Ke.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+((n=(t=o.match(/\d+/))===null||t===void 0?void 0:t[0])!==null&&n!==void 0?n:-1);if(a===-1)throw new ze(Ke.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${o}`);let d=yield s.deriveKeyBytes(Object.assign(Object.assign({},e),{length:a}));return yield this.bytesToPrivateKey({algorithm:o,privateKeyBytes:d})})}deriveKeyBytes(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({algorithm:e.algorithm});return yield this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)})}digest(e){return as(this,arguments,void 0,function*({algorithm:t,data:n}){return yield this.getAlgorithm({algorithm:t}).digest({algorithm:t,data:n})})}encrypt(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.key});return yield this.getAlgorithm({algorithm:t}).encrypt(e)})}generateKey(e){return as(this,void 0,void 0,function*(){var t;let n=this.getAlgorithmName({algorithm:e.algorithm}),s=yield this.getAlgorithm({algorithm:n}).generateKey({algorithm:e.algorithm});return(t=s.kid)!==null&&t!==void 0||(s.kid=yield wt({jwk:s})),s})}getPublicKey(e){return as(this,arguments,void 0,function*({key:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}privateKeyToBytes(e){return as(this,arguments,void 0,function*({privateKey:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).privateKeyToBytes({privateKey:t})})}publicKeyToBytes(e){return as(this,arguments,void 0,function*({publicKey:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).publicKeyToBytes({publicKey:t})})}sign(e){return as(this,arguments,void 0,function*({key:t,data:n}){let i=this.getAlgorithmName({key:t});return this.getAlgorithm({algorithm:i}).sign({data:n,key:t})})}unwrapKey(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.decryptionKey});return yield this.getAlgorithm({algorithm:t}).unwrapKey(e)})}verify(e){return as(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=this.getAlgorithmName({key:t});return this.getAlgorithm({algorithm:s}).verify({key:t,signature:n,data:i})})}wrapKey(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.encryptionKey});return yield this.getAlgorithm({algorithm:t}).wrapKey(e)})}getAlgorithm({algorithm:e}){var t;let n=(t=b$[e])===null||t===void 0?void 0:t.implementation;if(!n)throw new ze(Ke.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({algorithm:e,key:t}){var n;let i=(n=t?.alg)!==null&&n!==void 0?n:e,s=t?.crv;for(let o of Object.keys(b$)){let a=b$[o].names;if(i&&a.includes(i))return o;if(s&&a.includes(s))return o}throw new ze(Ke.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${i}, crv=${s}. Please check the documentation for the list of supported algorithms.`)}};g();is();gn();g();He();is();g();var xm={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:{}}},Rs={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"}}}}},u1={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();gn();var cw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},C0e=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},ji="^",sS=class extends Pd{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}addPredefinedKeys(e){return cw(this,arguments,void 0,function*({privateKeys:t}){var n;let i={};for(let s of t){(n=s.kid)!==null&&n!==void 0||(s.kid=yield wt({jwk:s}));let o=yield this.getKeyUri({key:s});i[o]=s}this._predefinedKeys=new Map(Object.entries(i)),this._keyGenerator=this._predefinedKeys.keys()})}exportKey(e){return cw(this,arguments,void 0,function*({keyUri:t}){let n=this._predefinedKeys.get(t);if(!n)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${t}`);return n})}generateKey(e){return cw(this,void 0,void 0,function*(){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t})}getPublicKey(e){return cw(this,arguments,void 0,function*({keyUri:t}){let n=this._predefinedKeys.get(t);if(!n)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${t}`);let{d:i}=n;return C0e(n,["d"])})}sign(e){return cw(this,arguments,void 0,function*({keyUri:t,data:n}){let i=this._predefinedKeys.get(t);if(!i)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${t}`);return yield zn.sign({data:n,key:i})})}};function sl(r){return cw(this,arguments,void 0,function*({agent:e,tenant:t,didUri:n}){if(t)return t;if(e.agentDid)return e.agentDid.uri;if(!n)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return n})}g();var f1=Rn(cS(),1);He();fn();var Cs=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},mh=class{constructor(){this.name="DwnDataStore",this._cache=new Di.default({ttl:(0,f1.default)("15 minutes"),max:100}),this._index=new Di.default({ttl:(0,f1.default)("21 days"),max:1e3}),this._protocolInitializedCache=new Di.default({ttl:(0,f1.default)("1 hour"),max:1e3}),this._tenantEncryptionActive=new Di.default({ttl:(0,f1.default)("1 hour"),max:1e3}),this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}delete(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t}),o=yield this.lookupRecordId({id:t,tenantDid:s,agent:n});if(!o)return!1;let{reply:{status:a}}=yield n.dwn.processRequest({author:s,target:s,messageType:ve.RecordsDelete,messageParams:{recordId:o}});if(a.code===202)return this._index.delete(`${s}${ji}${t}`),this._cache.delete(o),!0;throw new Error(`${this.name}: Failed to delete '${t}' from store: (${a.code}) ${a.detail}`)})}get(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i,useCache:s=!1}){let o=yield sl({agent:n,tenant:i,didUri:t}),a=yield this.lookupRecordId({id:t,tenantDid:o,agent:n});if(a)return yield this.getRecord({recordId:a,tenantDid:o,agent:n,useCache:s})})}list(e){return Cs(this,arguments,void 0,function*({agent:t,tenant:n}){let i=yield sl({tenant:n,agent:t});return yield this.getAllRecords({agent:t,tenantDid:i})})}set(e){return Cs(this,arguments,void 0,function*({id:t,data:n,tenant:i,agent:s,preventDuplicates:o=!0,updateExisting:a=!1,useCache:d=!1}){let l=yield sl({agent:s,tenant:i,didUri:t});yield this.initialize({tenant:l,agent:s});let c=Object.assign({},this._recordProperties);if(a){let m=yield this.getExistingRecordEntry({id:t,tenantDid:l,agent:s});if(!m)throw new Error(`${this.name}: Update failed due to missing entry for: ${t}`);c.recordId=m.recordsWrite.recordId,c.dateCreated=m.recordsWrite.descriptor.dateCreated}else if(o&&(yield this.lookupRecordId({id:t,tenantDid:l,agent:s})))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${t}`);let u=ae.object(n).toUint8Array(),f=this.isEncryptionActive(l),{message:h,reply:{status:p}}=yield s.dwn.processRequest(Object.assign({author:l,target:l,messageType:ve.RecordsWrite,messageParams:Object.assign(Object.assign({},this._recordProperties),c),dataStream:new Blob([u],{type:"application/json"})},f?{encryption:!0}:{}));if(!(h&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${t}: ${p.detail}`);this._index.set(`${l}${ji}${t}`,h.recordId),d&&this._cache.set(h.recordId,n)})}initialize(e){return Cs(this,arguments,void 0,function*({tenant:t,agent:n}){var i,s,o;let a=yield sl({agent:n,tenant:t});if(this._protocolInitializedCache.has(a)&&(!this.encryptionRequired||this._tenantEncryptionActive.has(a)))return;let{reply:{status:d,entries:l}}=yield n.dwn.processRequest({author:a,target:a,messageType:ve.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(d.code!==200)throw new Error(`Failed to query for protocols: ${d.code} - ${d.detail}`);let c=!1;if(l?.length===0)c=(yield this.installProtocol(a,n)).encryptionActive;else if(this.encryptionRequired){let u=(i=l[0].descriptor)===null||i===void 0?void 0:i.definition,f=Object.keys((s=u?.structure)!==null&&s!==void 0?s:{})[0];c=!!(f&&(!((o=u?.structure[f])===null||o===void 0)&&o.$encryption))}this._tenantEncryptionActive.set(a,c),this._protocolInitializedCache.set(a,!0)})}get encryptionRequired(){return this._encryptionRequired===void 0&&(this._encryptionRequired=Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)),this._encryptionRequired}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}getAllRecords(e){return Cs(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")})}getRecord(e){return Cs(this,arguments,void 0,function*({recordId:t,tenantDid:n,agent:i,useCache:s}){var o;if(s){let c=this._cache.get(t);if(c)return c}let a=this.encryptionRequired||this.isEncryptionActive(n),{reply:d}=yield i.dwn.processRequest(Object.assign({author:n,target:n,messageType:ve.RecordsRead,messageParams:{filter:{recordId:t}}},a?{encryption:!0}:{}));if(!(!((o=d.entry)===null||o===void 0)&&o.data))throw new Error(`${this.name}: Failed to read data from DWN for: ${t}`);let l=yield bo.consumeToJson({readableStream:d.entry.data});return s&&this._cache.set(t,l),l})}installProtocol(e,t){return Cs(this,void 0,void 0,function*(){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let o=yield t.dwn.getEncryptionKeyDeriver(e);n=yield Gd.deriveAndInjectPublicEncryptionKeys(n,o),i=!0}let{reply:{status:s}}=yield t.dwn.processRequest({author:e,target:e,messageType:ve.ProtocolsConfigure,messageParams:{definition:n}});if(s.code!==202)throw new Error(`Failed to install protocol: ${s.code} - ${s.detail}`);return{encryptionActive:i}})}lookupRecordId(e){return Cs(this,arguments,void 0,function*({id:t,tenantDid:n,agent:i}){let s=this._index.get(`${n}${ji}${t}`,{updateAgeOnGet:!0});return s||(yield this.getAllRecords({agent:i,tenantDid:n}),s=this._index.get(`${n}${ji}${t}`)),s})}getExistingRecordEntry(e){return Cs(this,arguments,void 0,function*({id:t,tenantDid:n,agent:i}){let s=yield this.lookupRecordId({id:t,tenantDid:n,agent:i});if(s){let{reply:o}=yield i.dwn.processRequest({author:n,target:n,messageType:ve.RecordsRead,messageParams:{filter:{recordId:s}}});return o.entry}})}},yh=class{constructor(){this.name="InMemoryDataStore",this.store=new Map}delete(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t});return this.store.has(`${s}${ji}${t}`)?(this.store.delete(`${s}${ji}${t}`),!0):!1})}get(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t});return this.store.get(`${s}${ji}${t}`)})}list(e){return Cs(this,arguments,void 0,function*({agent:t,tenant:n}){let i=yield sl({tenant:n,agent:t}),s=[];for(let[o,a]of this.store.entries())o.startsWith(`${i}${ji}`)&&s.push(a);return s})}set(e){return Cs(this,arguments,void 0,function*({id:t,data:n,tenant:i,agent:s,preventDuplicates:o,updateExisting:a}){let d=yield sl({agent:s,tenant:i,didUri:t});if(a){if(!this.store.has(`${d}${ji}${t}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${t}`)}else if(o&&this.store.has(`${d}${ji}${t}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${t}`);let l=structuredClone(n);this.store.set(`${d}${ji}${t}`,l)})}};var Pu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},h1=class extends mh{constructor(){super(...arguments),this.name="DwnDidStore",this._recordProtocolDefinition=xm,this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}delete(e){let t=Object.create(null,{delete:{get:()=>super.delete}});return Pu(this,void 0,void 0,function*(){return yield t.delete.call(this,e)})}get(e){let t=Object.create(null,{get:{get:()=>super.get}});return Pu(this,void 0,void 0,function*(){return yield t.get.call(this,e)})}list(e){let t=Object.create(null,{list:{get:()=>super.list}});return Pu(this,void 0,void 0,function*(){return yield t.list.call(this,e)})}set(e){let t=Object.create(null,{set:{get:()=>super.set}});return Pu(this,void 0,void 0,function*(){return yield t.set.call(this,e)})}getAllRecords(e){return Pu(this,arguments,void 0,function*({agent:t,tenantDid:n}){var i;this._index.clear();let{reply:s}=yield t.dwn.processRequest({author:n,target:n,messageType:ve.RecordsQuery,messageParams:{filter:Object.assign({},this._recordProperties)}}),o=[];for(let a of(i=s.entries)!==null&&i!==void 0?i:[]){if(!a.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let d=ae.base64Url(a.encodedData).toObject();if(Zg(d)){let l=`${n}${ji}${d.uri}`;this._index.set(l,a.recordId),this._cache.set(a.recordId,d),o.push(d)}}return o})}},p1=class extends yh{constructor(){super(...arguments),this.name="InMemoryDidStore"}delete(e){let t=Object.create(null,{delete:{get:()=>super.delete}});return Pu(this,void 0,void 0,function*(){return yield t.delete.call(this,e)})}get(e){let t=Object.create(null,{get:{get:()=>super.get}});return Pu(this,void 0,void 0,function*(){return yield t.get.call(this,e)})}list(e){let t=Object.create(null,{list:{get:()=>super.list}});return Pu(this,void 0,void 0,function*(){return yield t.list.call(this,e)})}set(e){let t=Object.create(null,{set:{get:()=>super.set}});return Pu(this,void 0,void 0,function*(){return yield t.set.call(this,e)})}};var _u=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},_m;(function(r){r.Create="Create",r.Resolve="Resolve"})(_m||(_m={}));function sV(r,e){return r.messageType===e}var m1=class extends dh{constructor({agent:e,didMethods:t,resolverCache:n,store:i}){if(!t)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:t,cache:n??new vm({agent:e,location:"DATA/AGENT/DID_CACHE"})}),this._didMethods=new Map,this._agent=e,this._store=i??new p1;for(let s of t)this._didMethods.set(s.methodName,s)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,"agent"in this.cache&&(this.cache.agent=e)}create(e){return _u(this,arguments,void 0,function*({method:t,tenant:n,options:i,store:s}){let a=yield this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(yield this.cache.set(a.uri,{didDocument:a.document,didResolutionMetadata:{},didDocumentMetadata:a.metadata}),s??!0){let{uri:d,document:l,metadata:c}=a,u={uri:d,document:l,metadata:c};yield this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return a})}export(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n}){let i=yield this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return yield i.export()})}get(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n}){let i=yield this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?yield Ro.import({portableDid:i,keyManager:this.agent.keyManager}):void 0})}getSigningMethod(e){return _u(this,arguments,void 0,function*({didUri:t,methodId:n}){let i=Qn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let s=this.getMethod(i.method),{didDocument:o,didResolutionMetadata:a}=yield this.resolve(t);if(!o)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(a)}`);return yield s.getSigningMethod({didDocument:o,methodId:n})})}update(e){return _u(this,arguments,void 0,function*({tenant:t,portableDid:n,publish:i=!0}){let s=yield this.get({didUri:n.uri,tenant:t??n.uri});if(!s)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(G0(n.document)===G0(s.document))throw new Error("AgentDidApi: No changes detected, update aborted");let o=yield Ro.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:a,document:d,metadata:l}=o,c={uri:a,document:d,metadata:l};if(yield this.cache.set(a,{didDocument:d,didResolutionMetadata:{},didDocumentMetadata:l}),yield this._store.set({id:a,data:c,agent:this.agent,tenant:t??a,updateExisting:!0,useCache:!0}),i){let u=Qn.parse(a);u?.method==="dht"&&(yield fa.publish({did:o}))}return o})}import(e){return _u(this,arguments,void 0,function*({portableDid:t,tenant:n}){let i=yield Ro.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:s,document:o,metadata:a}=i,d={uri:s,document:o,metadata:a};return yield this.cache.set(s,{didDocument:o,didResolutionMetadata:{},didDocumentMetadata:a}),yield this._store.set({id:d.uri,data:d,agent:this.agent,tenant:n??d.uri,preventDuplicates:!0,useCache:!0}),i})}delete(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n,deleteKey:i=!0}){let s=yield this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!s)throw new Error("AgentDidApi: Could not delete, DID not found");yield this.cache.delete(t),yield this._store.delete({id:t,agent:this.agent,tenant:n}),i&&(yield this.deleteKeys({portableDid:s}))})}deleteKeys(e){return _u(this,arguments,void 0,function*({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=yield this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});yield this.agent.keyManager.deleteKey({keyUri:i})}})}processRequest(e){return _u(this,void 0,void 0,function*(){var t;if(sV(e,_m.Create))try{let n=yield this.create(Object.assign({},e.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:(t=n.message)!==null&&t!==void 0?t:"Unknown error occurred"}}}if(sV(e,_m.Resolve)){let{didUri:n,options:i}=e.messageParams;return{result:yield this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${e.messageType}`)})}getMethod(e){let t=this._didMethods.get(e);if(t===void 0)throw new Error(`DID Method not supported: ${e}`);return t}};g();fn();He();gn();is();g();fn();He();var al=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},aV=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},Pn=class r{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Di.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return al(this,arguments,void 0,function*({connectedDid:t,delegateDid:n,delegate:i,messageType:s,protocol:o,cached:a=!1}){let d=[t,n,s,o].join("~"),l=a?this._cachedPermissions.get(d):void 0;if(l)return l;let c=yield this.fetchGrants({author:n,target:n,grantor:t,grantee:n}),u=yield r.matchGrantFromArray(t,n,{messageType:s,protocol:o},c,i);if(!u)throw new Error(`CachedPermissions: No permissions found for ${s}: ${o}`);return this._cachedPermissions.set(d,u),u})}fetchGrants(e){return al(this,arguments,void 0,function*({author:t,target:n,grantee:i,grantor:s,protocol:o,remote:a=!1,checkRevoked:d=!0}){let l=o?{protocol:o}:void 0,c={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{author:s,recipient:i,protocol:Qe.uri,protocolPath:Qe.grantPath,tags:l}}},{reply:u}=a?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(u.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${u.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:t,target:n,grantor:s,remote:a,tags:l}):new Set,h=[];for(let p of u.entries){if(f.has(p.recordId))continue;let m=Ht.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return al(this,arguments,void 0,function*({author:t,target:n,grantor:i,remote:s,tags:o}){let a={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{author:i,protocol:Qe.uri,protocolPath:Qe.revocationPath,tags:o}}},{reply:d}=s?yield this.agent.sendDwnRequest(a):yield this.agent.processDwnRequest(a);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let l=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&l.add(c.descriptor.parentId);return l})}fetchRequests(e){return al(this,arguments,void 0,function*({author:t,target:n,protocol:i,remote:s=!1}){let o=i?{protocol:i}:void 0,a={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{protocol:Qe.uri,protocolPath:Qe.requestPath,tags:o}}},{reply:d}=s?yield this.agent.sendDwnRequest(a):yield this.agent.processDwnRequest(a);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let l=[];for(let c of d.entries){let u=Oa.parse(c);l.push({request:u,message:c})}return l})}isGrantRevoked(e){return al(this,arguments,void 0,function*({author:t,target:n,grantRecordId:i,remote:s=!1}){let o={author:t,target:n,messageType:ve.RecordsRead,messageParams:{filter:{parentId:i,protocol:Qe.uri,protocolPath:Qe.revocationPath}}},{reply:a}=s?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(a.status.code===404)return!1;if(a.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${a.status.detail}`)})}createGrant(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,delegated:i=!1}=e,s=aV(e,["author","store","delegated"]),o;Qe.hasProtocolScope(s.scope)&&(o={protocol:s.scope.protocol});let a={dateExpires:s.dateExpires,requestId:s.requestId,description:s.description,delegated:i,scope:s.scope};s.delegateKeyDelivery&&(a.delegateKeyDelivery=s.delegateKeyDelivery);let d=ae.object(a).toUint8Array(),l={recipient:s.grantedTo,protocol:Qe.uri,protocolPath:Qe.grantPath,dataFormat:"application/json",tags:o},{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(d).toBase64Url()});return{grant:Ht.parse(f),message:f}})}createRequest(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,delegated:i=!1}=e,s=aV(e,["author","store","delegated"]),o;Qe.hasProtocolScope(s.scope)&&(o={protocol:s.scope.protocol});let a={description:s.description,delegated:i,scope:s.scope},d=ae.object(a).toUint8Array(),l={protocol:Qe.uri,protocolPath:Qe.requestPath,dataFormat:"application/json",tags:o},{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(d).toBase64Url()});return{request:Oa.parse(f),message:f}})}createRevocation(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,grant:i,description:s}=e,o={description:s},a=ae.object(o).toUint8Array(),d;Qe.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:Qe.uri,protocolPath:Qe.revocationPath,dataFormat:"application/json",tags:d};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([a])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(a).toBase64Url()})}})}clear(){return al(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,t,n,i){return al(this,arguments,void 0,function*(s,o,a,d,l=!1){let c;for(let u of d){let{grant:f,message:h}=u;if(l===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:y,contextId:v}=a;if(this.matchScopeFromGrant(s,o,p,f,m,y,v)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,t,n,i,s,o,a){if(i.grantee!==t||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(d.interface==="Messages"?d.method==="Read"&&(n===ve.MessagesRead||n===ve.MessagesSync||n===ve.MessagesSubscribe):l===n)if(x$(n)){let u=d;if(u.protocol!==s)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===o||u.contextId!==void 0&&a?.startsWith(u.contextId))return!0}else{let u=d;return u.protocol===void 0?!0:u.protocol!==s?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var dS=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},P$="@enbox/dwn-server";function fw(r){return r.endsWith("/")?r.slice(0,-1):r}var Em=class{constructor(e,t=1e4,n){this._rpcClient=e,this._cacheTtlMs=t,this._discoveryFile=n,this._cacheExpiry=0}getEndpoint(){return dS(this,void 0,void 0,function*(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=yield this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)})}setCachedEndpoint(e){return dS(this,void 0,void 0,function*(){let t=fw(e),n=yield this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n})}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}_tryDiscoveryFile(){return dS(this,void 0,void 0,function*(){if(this._discoveryFile)try{let e=yield this._discoveryFile.read();return e&&(yield this._validateEndpoint(e.endpoint))?e.endpoint:void 0}catch{return}})}_validateEndpoint(e){return dS(this,void 0,void 0,function*(){try{return(yield this._rpcClient.getServerInfo(e)).server===P$}catch{return!1}})}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};var hw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function M0e(){try{let r=XS,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{readFile(i){return hw(this,void 0,void 0,function*(){try{return yield e.readFile(i,"utf-8")}catch{return null}})},writeFile(i,s){return hw(this,void 0,void 0,function*(){yield e.mkdir(t.dirname(i),{recursive:!0}),yield e.writeFile(i,s,{encoding:"utf-8",mode:384})})},removeFile(i){return hw(this,void 0,void 0,function*(){try{yield e.unlink(i)}catch{}})},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var U0e=".enbox",K0e="dwn.json",lS=class{constructor(e,t){let n=e??M0e();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 s=XS("node:path");this._filePath=s.join(n.homedir(),U0e,K0e)}}get path(){return this._filePath}read(){return hw(this,void 0,void 0,function*(){let e=yield this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{yield this._fs.removeFile(this._filePath);return}if(!L0e(t)){yield this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){yield this._fs.removeFile(this._filePath);return}let n={endpoint:fw(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n})}write(e){return hw(this,void 0,void 0,function*(){let t={endpoint:fw(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);yield this._fs.writeFile(this._filePath,n)})}remove(){return hw(this,void 0,void 0,function*(){yield this._fs.removeFile(this._filePath)})}};function L0e(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();fn();function nc(r,e){return r.messageType===e}function _$(r,e){return e.descriptor.interface+e.descriptor.method===r}function x$(r){return r===ve.RecordsDelete||r===ve.RecordsQuery||r===ve.RecordsRead||r===ve.RecordsSubscribe||r===ve.RecordsWrite}function Sm(r){return r.interface===xe.Records}g();fn();gn();var Vc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function uS(r){return r===pi.XC20P?24:12}function Tm(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}function fS(r,e,t){return Vc(this,arguments,void 0,function*(n,i,s,o=pi.A256GCM){let{ciphertextStream:a,tag:d}=yield Ai.aeadEncryptStream(o,i,s,Et.fromBytes(n)),l=yield Et.toBytes(a),c=Et.fromBytes(l),u=yield pr.computeDagPbCidFromStream(c);return{encryptedBytes:l,dataCid:u,dataSize:l.length,authenticationTag:d}})}function ic(r,e){return Vc(this,void 0,void 0,function*(){var t;let{didDocument:n,didResolutionMetadata:i}=yield r.did.resolve(e);if(!n)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(i)}`);let s=n.keyAgreement;if(!s||s.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 o=s[0],a;if(typeof o=="string"){let c=o.includes("#")?o.split("#").pop():o;a=(t=n.verificationMethod)===null||t===void 0?void 0:t.find(u=>u.id.endsWith(`#${c}`))}else a=o;if(!a?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let d=a.publicKeyJwk;if(d.crv==="Ed25519")d=yield zn.convertPublicKeyToX25519({publicKey:d});else if(d.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${d.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let l=yield r.keyManager.getKeyUri({key:d});return{keyId:a.id,keyUri:l,publicKeyJwk:d}})}function dV(r,e,t,n,i){return Vc(this,void 0,void 0,function*(){let{keyId:s,keyUri:o}=yield ic(r,e),a=ke.constructKeyDerivationPathUsingProtocolContextScheme(t),d=yield r.keyManager.derivePublicKey({keyUri:o,derivationPath:a});return{encryptionInput:Tm(n,i,s,d,St.ProtocolContext),keyId:s,keyUri:o,contextDerivationPath:a}})}function lV(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:(s,o)=>Vc(this,void 0,void 0,function*(){return i.jweKeyUnwrap({keyUri:t,derivationPath:s,encryptedKey:o.encryptedKey,ephemeralPublicKey:o.ephemeralPublicKey})})}}function g1(r,e){return Vc(this,void 0,void 0,function*(){let{keyId:t,keyUri:n}=yield ic(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:St.ProtocolPath,derivePublicKey:s=>Vc(this,void 0,void 0,function*(){return i.derivePublicKey({keyUri:n,derivationPath:s})})}})}function E$(r,e){return Vc(this,void 0,void 0,function*(){let{keyId:t,keyUri:n}=yield ic(r,e);return lV(r,t,n,St.ProtocolPath)})}function y1(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:(e,t)=>Vc(this,void 0,void 0,function*(){let n=yield ke.derivePrivateKey(r,e),i=yield kt.bytesToPrivateKey({privateKeyBytes:n});return Ai.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)})}}function q0e(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:(e,t)=>Vc(this,void 0,void 0,function*(){var n;let i=(n=r.derivationPath)!==null&&n!==void 0?n:[];if(i.length!==e.length||!i.every((a,d)=>a===e[d]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${i.join(", ")}], record path: [${e.join(", ")}].`);let s=yield ke.derivePrivateKey(r,e),o=yield kt.bytesToPrivateKey({privateKeyBytes:s});return Ai.ecdhEsUnwrapKey(o,t.ephemeralPublicKey,t.encryptedKey)})}}function cV(r,e,t,n,i,s,o,a,d){return Vc(this,void 0,void 0,function*(){let{encryption:l}=t;if(!l?.recipients.some(b=>b.header.derivationScheme===St.ProtocolContext)||!t.contextId){if(o&&a){let b=t.descriptor.protocol,T=t.descriptor.protocolPath;if(b){let D=`ddk~${a}`,I=o.get(D);if(I){let M=I.filter(z=>z.protocol===b);if(T){let z=M.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===T);if(z)return q0e(z.derivedPrivateKey)}let C=M.find(z=>z.scope.kind==="protocol");if(C)return y1(C.derivedPrivateKey)}}}return E$(r,e)}let u=l.recipients.find(b=>b.header.derivationScheme===St.ProtocolContext),f=t.contextId.split("/")[0];if(d&&a){let b=t.descriptor.protocol;if(b){let T=`dctx~${a}~${b}~${f}`,D=d.get(T);if(D)return y1(D);try{let I=yield s({ownerDid:e,requesterDid:a,sourceProtocol:b,sourceContextId:f});if(I)return d.set(T,I),y1(I)}catch{}}throw new Error(`AgentDwnApi: Delegate '${a}' 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:h,keyUri:p}=yield ic(r,e);if(u.header.kid===h)return lV(r,h,p,St.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return y1(y);let v=t.descriptor.protocol,w=yield s({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:b}=yield Promise.resolve().then(()=>(fn(),YH)),T=n??b.getSignerDid(t.authorization.signature.signatures[0]);w=yield s({ownerDid:T,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),y1(w)})}function uV(r,e,t,n,i,s,o){return Vc(this,void 0,void 0,function*(){var a,d,l;if(!("encryption"in r)||!r.encryption)return;let c=r,u=c.granteeDid;if(nc(c,ve.RecordsRead)){let f=e;if(f.status.code===200&&(!((d=(a=f.entry)===null||a===void 0?void 0:a.recordsWrite)===null||d===void 0)&&d.encryption)&&(!((l=f.entry)===null||l===void 0)&&l.data)){let h=yield cV(t,c.author,f.entry.recordsWrite,c.target,n,i,s,u,o);try{f.entry.data=yield ke.decrypt(f.entry.recordsWrite,h,f.entry.data)}catch(p){throw new Error(`AgentDwnApi: Failed to decrypt record '${f.entry.recordsWrite.recordId}'. Original error: ${p.message}`)}}}if(nc(c,ve.RecordsQuery)){let f=e;if(f.status.code===200&&f.entries){for(let h of f.entries)if(h.encryption&&h.encodedData){let p=yield cV(t,c.author,h,c.target,n,i,s,u,o);try{let m=Ie.base64UrlToBytes(h.encodedData),y=Et.fromBytes(m),v=yield ke.decrypt(h,p,y),w=yield Et.toBytes(v);h.encodedData=Ie.bytesToBase64Url(w)}catch(m){throw new Error(`AgentDwnApi: Failed to decrypt record '${h.recordId}'. Original error: ${m.message}`)}}}}})}g();fn();var w1=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function fV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){if(i.get(e))return;let o=Rs.protocol;if(!(yield n(e,o))){let d=yield g1(r,e),l=yield Gd.deriveAndInjectPublicEncryptionKeys(Rs,d),{reply:{status:c}}=yield t({author:e,target:e,messageType:ve.ProtocolsConfigure,messageParams:{definition:l}});if(c.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${c.code} - ${c.detail}`);s.delete(`${e}~${o}`)}i.set(e,!0)})}function hV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){let{tenantDid:o,recipientDid:a,contextKeyData:d,sourceProtocol:l,sourceContextId:c,recipientKeyDeliveryPublicKey:u}=e;yield n(o);let f=Rs.protocol,h=new TextEncoder().encode(JSON.stringify(d)),p={protocol:f,protocolPath:"contextKey",dataFormat:"application/json",recipient:a,tags:{protocol:l,contextId:c}},m,y;if(u){let v=pi.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),b=crypto.getRandomValues(new Uint8Array(uS(v))),{encryptedBytes:T,dataCid:D,dataSize:I,authenticationTag:M}=yield fS(h,w,b,v),C=Object.assign(Object.assign({},Tm(w,b,u.rootKeyId,u.publicKeyJwk,St.ProtocolPath)),{authenticationTag:M});({message:m,reply:{status:y}}=yield t({author:o,target:o,messageType:ve.RecordsWrite,messageParams:Object.assign(Object.assign({},p),{dataCid:D,dataSize:I,encryptionInput:C}),dataStream:new Blob([T])}))}else({message:m,reply:{status:y}}=yield t({author:o,target:o,messageType:ve.RecordsWrite,messageParams:p,dataStream:new Blob([h],{type:"application/json"}),encryption:!0}));if(!(m&&y.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${a}: ${y.code} - ${y.detail}`);return s(i(o,m).catch(v=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${m.recordId}' to remote DWN failed: ${v.message}. Sync will deliver it later.`)})),m.recordId})}function pV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){let o;try{o=yield s(e)}catch{return}if(o.length===0)return;let{data:a}=yield n({author:e,messageType:ve.RecordsWrite,messageCid:yield ye.getCid(t)});yield i({targetDid:e,dwnEndpointUrls:o,message:t,data:a})})}function z0e(r,e,t,n,i){return w1(this,void 0,void 0,function*(){var s,o;try{let{reply:a}=yield r({author:e,target:t,messageType:ve.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!(!((s=a.entries)===null||s===void 0)&&s.length))return;let d=a.entries[0].recordId,{reply:l}=yield r({author:e,target:t,messageType:ve.RecordsRead,messageParams:{filter:{recordId:d}},encryption:!0}),c=l;return!((o=c.entry)===null||o===void 0)&&o.data?i(yield Et.toBytes(c.entry.data)):void 0}catch{return}})}function mV(r,e,t){return w1(this,void 0,void 0,function*(){var n,i;let{ownerDid:s,requesterDid:o,sourceProtocol:a,sourceContextId:d}=e,l=Rs.protocol,c=s===o,u={protocol:l,protocolPath:"contextKey",recipient:o,tags:{protocol:a,contextId:d}},f=h=>JSON.parse(new TextDecoder().decode(h));if(c){let{reply:h}=yield t({author:o,target:s,messageType:ve.RecordsQuery,messageParams:{filter:u}});if(h.status.code!==200||!(!((n=h.entries)===null||n===void 0)&&n.length))return;let p=h.entries[0].recordId,{reply:m}=yield t({author:o,target:s,messageType:ve.RecordsRead,messageParams:{filter:{recordId:p}},encryption:!0}),y=m;return!((i=y.entry)===null||i===void 0)&&i.data?f(yield Et.toBytes(y.entry.data)):void 0}return z0e(t,o,s,u,f)})}g();fn();var S$=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function yV(r,e,t,n,i,s,o){return S$(this,void 0,void 0,function*(){var a;let d=`${r}~${e}`,l=i.get(d);if(l)return l;let u=yield n(s??r),f=yield gm[ve.ProtocolsQuery].create(Object.assign({filter:{protocol:e},signer:u},o?{permissionGrantId:o}:{})),h=yield t.processMessage(r,f.message);if(h.status.code!==200||!(!((a=h.entries)===null||a===void 0)&&a.length))return;let p=h.entries[0].descriptor.definition;return i.set(d,p),p})}function gV(r,e,t,n,i){return S$(this,void 0,void 0,function*(){var s;let o=`remote~${r}~${e}`,a=i.get(o);if(a)return a;let d=yield gm[ve.ProtocolsQuery].create({filter:{protocol:e}}),l=yield n({targetDid:r,dwnEndpointUrls:yield t(r),message:d.message});if(l.status.code!==200||!(!((s=l.entries)===null||s===void 0)&&s.length))throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let c=l.entries[0].descriptor.definition;return i.set(o,c),c})}function wV(r,e,t,n,i,s,o){return S$(this,void 0,void 0,function*(){var a,d;let l=yield s(n),c=yield gm[ve.RecordsQuery].create({signer:l,filter:{protocol:e,contextId:t}}),u=yield i(r),f=yield o({targetDid:r,dwnEndpointUrls:u,message:c.message});if(!(f.status.code!==200||!(!((a=f.entries)===null||a===void 0)&&a.length))){for(let h of f.entries)if(!((d=h.encryption)===null||d===void 0)&&d.recipients){let p=h.encryption.recipients.find(m=>m.header.derivationScheme===St.ProtocolContext&&m.header.derivedPublicKey);if(p?.header.derivedPublicKey)return{rootKeyId:p.header.kid,derivedPublicKey:p.header.derivedPublicKey}}}})}var xr=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Dm=class r{constructor(e){this._protocolDefinitionCache=new Di.default({ttl:30*60*1e3}),this._contextKeyCache=new Di.default({ttl:30*60*1e3}),this._contextDerivedKeyCache=new Di.default({ttl:30*60*1e3}),this._delegateDecryptionKeyCache=new Di.default({ttl:24*60*60*1e3}),this._delegateContextKeyCache=new Di.default({ttl:24*60*60*1e3}),this._delegateContextKeyCacheIndex=new Map,this._delegateMultiPartyProtocols=new Map,this._localManagedDidCache=new Di.default({ttl:30*60*1e3}),this._pendingEagerSends=new Set,this._keyDeliveryProtocolInstalledCache=new Di.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 Em(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 Em(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}setCachedLocalDwnEndpoint(e){return xr(this,void 0,void 0,function*(){var t;return(t=this._localDwnDiscovery)!==null&&t!==void 0||(this._localDwnDiscovery=new Em(this.agent.rpc,1e4,r._tryCreateDiscoveryFile())),this._localDwnDiscovery.setCachedEndpoint(e)})}getDwnEndpointUrlsForTarget(e){return xr(this,void 0,void 0,function*(){if(!(yield this.shouldUseLocalDwnForTarget(e)))return ow(e,this.agent.did);let n=yield 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=yield ow(e,this.agent.did)}catch(o){if(!n)throw o}return n?[...new Set([n,...i])]:i})}getRemoteDwnEndpointUrls(e){return xr(this,void 0,void 0,function*(){return ow(e,this.agent.did)})}getLocalDwnEndpoint(){return xr(this,void 0,void 0,function*(){var e;return this._localDwnEndpoint?this._localDwnEndpoint:((e=this._localDwnDiscovery)!==null&&e!==void 0||(this._localDwnDiscovery=new Em(this.agent.rpc,1e4,r._tryCreateDiscoveryFile())),this._localDwnDiscovery.getEndpoint())})}static _tryCreateDiscoveryFile(){try{return new lS}catch{return}}shouldUseLocalDwnForTarget(e){return xr(this,void 0,void 0,function*(){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=yield 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 s=i.has(e);return s||this._localManagedDidCache.set(e,!1),s})}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 createDwn(e){return xr(this,arguments,void 0,function*({dataPath:t,dataStore:n,didResolver:i,stateIndex:s,eventLog:o,messageStore:a,tenantGate:d,resumableTaskStore:l}){return n??(n=new um({blockstoreLocation:`${t}/DWN_DATASTORE`})),i??(i=new dh({didResolvers:[fa,ns],cache:new DE({location:`${t}/DID_RESOLVERCACHE`})})),s??(s=new ym({location:`${t}/DWN_STATEINDEX`})),a??(a=new hm({blockstoreLocation:`${t}/DWN_MESSAGESTORE`,indexLocation:`${t}/DWN_MESSAGEINDEX`})),l??(l=new pm({location:`${t}/DWN_RESUMABLETASKSTORE`})),o??(o=new mm),yield Qg.create({dataStore:n,didResolver:i,stateIndex:s,eventLog:o,messageStore:a,tenantGate:d,resumableTaskStore:l})})}processRequest(e){return xr(this,void 0,void 0,function*(){let{message:t,dataStream:n}=yield this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,s;if(e.store===!1)s={status:{code:202,detail:"Accepted"}};else if(this._dwn)s=yield this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let o;if(n){let a=yield Et.toBytes(n);o=new Blob([a])}s=yield this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:o,subscriptionHandler:i})}return yield Promise.all([this.postWriteKeyDelivery(e,t,s),this.maybeDecryptReply(e,s)]),{reply:s,message:t,messageCid:yield ye.getCid(t)}})}processRawMessage(e,t,n){return xr(this,void 0,void 0,function*(){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let s=yield Et.toBytes(n.dataStream);i=new Blob([s])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})})}sendRequest(e){return xr(this,void 0,void 0,function*(){let t=yield this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,s,o;if("messageCid"in e)({message:i,data:s}=yield this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=yield this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");s=e.dataStream,o=e.subscriptionHandler}let a;o!==void 0&&!("messageCid"in e)&&(a=l=>xr(this,void 0,void 0,function*(){let c=l===void 0?e.messageParams:Object.assign(Object.assign({},e.messageParams),{cursor:l}),u=Object.assign(Object.assign({},e),{messageParams:c}),{message:f}=yield this.constructDwnMessage({request:u});return f}));let d=yield this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:s,subscriptionHandler:o,resubscribeFactory:a});return yield this.maybeDecryptReply(e,d),n??(n=yield ye.getCid(i)),{reply:d,message:i,messageCid:n}})}postWriteKeyDelivery(e,t,n){return xr(this,void 0,void 0,function*(){var i,s;if(!nc(e,ve.RecordsWrite)||!e.encryption||n.status.code!==202)return;let o=e.messageParams;if(o.protocol!==Rs.protocol)try{let a=yield this.getProtocolDefinition(e.target,o.protocol);if(!a)return;let d=t,l=lt.getSignerDid(d.authorization.signature.signatures[0]),c=l!==e.target,u=!o.parentContextId,f=o.protocolPath.split("/")[0],h=wm(a,f),p=y$({protocolDefinition:a,protocolPath:o.protocolPath,recipient:o.recipient,tenantDid:e.target,authorDid:c?l:void 0}),m=((i=d.contextId)===null||i===void 0?void 0:i.split("/")[0])||d.contextId||d.recordId,y=h&&u&&!c&&this.hasEligibleDelegatesForProtocol(o.protocol),v=h&&u&&!c;if(p.size>0||y||v){let{keyId:w,keyUri:b}=yield ic(this.agent,e.target),T=[St.ProtocolContext,m],D=yield this.agent.keyManager.derivePrivateKeyBytes({keyUri:b,derivationPath:T}),I=yield kt.bytesToPrivateKey({privateKeyBytes:D}),M={rootKeyId:w,derivationScheme:St.ProtocolContext,derivationPath:T,derivedPrivateKey:I};if(p.size>0){let C=(s=d.authorization)===null||s===void 0?void 0:s.authorKeyDeliveryPublicKey;for(let z of p)try{let L=z===l&&C?C:void 0;yield this.writeContextKeyRecord({tenantDid:e.target,recipientDid:z,contextKeyData:M,sourceProtocol:o.protocol,sourceContextId:m,recipientKeyDeliveryPublicKey:L})}catch(L){console.warn(`AgentDwnApi: Key delivery to '${z}' for context '${m}' failed: ${L.message}. The participant may not be able to decrypt records in this context.`)}}y&&this.deliverContextKeyToDelegates(o.protocol,m,M),v&&(yield this.deliverContextKeyToDelegatesViaDwn(e.target,o.protocol,m,M))}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}})}sendDwnRpcRequest(e){return xr(this,arguments,void 0,function*({targetDid:t,dwnEndpointUrls:n,message:i,data:s,subscriptionHandler:o,resubscribeFactory:a}){let d=[];if(i.descriptor.method===me.Subscribe&&o===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let l of n)try{if(o!==void 0){if(!(yield this.agent.rpc.getServerInfo(l)).webSocketSupport){d.push({url:l,message:"WebSocket support is not enabled on the server."});continue}let f=new URL(l);f.protocol=f.protocol==="http:"?"ws:":"wss:",l=f.toString()}return yield this.agent.rpc.sendDwnRequest({dwnUrl:l,targetDid:t,message:i,data:s,subscription:o?{handler:o,resubscribeFactory:a}:void 0})}catch(c){d.push({url:l,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(d)}`)})}constructDwnMessage(e){return xr(this,arguments,void 0,function*({request:t}){var n,i,s;if(t.granteeDid&&!this.hasGrantParams(t.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let o=t.rawMessage,a;if(nc(t,ve.RecordsWrite)){let u=t.messageParams;if(t.dataStream&&!u?.data){let{dataStream:f}=t,h;if(f instanceof Blob){let[p,m]=f.stream().tee();h=p,a=m}else if(f instanceof ReadableStream){let[p,m]=f.tee();h=p,a=m}!o&&u&&(u.dataCid=yield pr.computeDagPbCidFromStream(h),u.dataSize===void 0&&f instanceof Blob&&(u.dataSize=f.size))}}if(nc(t,ve.ProtocolsConfigure)&&t.encryption&&!o){let u=t.messageParams,f=yield g1(this.agent,t.author);u.definition=yield Gd.deriveAndInjectPublicEncryptionKeys(u.definition,f),this._protocolDefinitionCache.delete(`${t.target}~${u.definition.protocol}`)}if(nc(t,ve.ProtocolsConfigure)&&!t.encryption&&!o){let u=(n=t.messageParams)===null||n===void 0?void 0:n.definition;u?.protocol&&this._protocolDefinitionCache.set(`${t.target}~${u.protocol}`,u)}let d;if(nc(t,ve.RecordsWrite)&&t.encryption&&!o){let u=t.messageParams;if(u?.protocol&&u.protocolPath){let f=t.target!==t.author,h;if(f?h=yield this.fetchRemoteProtocolDefinition(t.target,u.protocol):h=yield this.getProtocolDefinition(t.target,u.protocol,t.granteeDid),!h)throw new Error(`AgentDwnApi: Protocol '${u.protocol}' is not installed for '${t.target}'. Install the protocol before writing encrypted records.`);let p=u.protocolPath.split("/"),m=h.structure;for(let R of p)m=m[R];if(!m?.$encryption)throw new Error(`AgentDwnApi: Protocol '${u.protocol}' at path '${u.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let y=u.protocolPath.split("/")[0],w=u.protocol===Rs.protocol?!1:wm(h,y),b=!u.parentContextId,T;if(u.data)T=u.data instanceof Uint8Array?u.data:new TextEncoder().encode(String(u.data));else if(t.dataStream instanceof Blob)T=new Uint8Array(yield t.dataStream.arrayBuffer());else if(t.dataStream instanceof ReadableStream)T=yield Et.toBytes(t.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let D=pi.A256GCM,I=crypto.getRandomValues(new Uint8Array(32)),M=crypto.getRandomValues(new Uint8Array(uS(D))),C,z=()=>Tm(I,M,m.$encryption.rootKeyId,m.$encryption.publicKeyJwk,St.ProtocolPath);if(f&&w&&b)C=z();else if(f&&w&&!b){let R=u.parentContextId.split("/")[0]||u.parentContextId,$=yield this.extractDerivedPublicKey(t.target,u.protocol,R,t.author);$?C=Tm(I,M,$.rootKeyId,$.derivedPublicKey,St.ProtocolContext):C=z()}else if(f)C=z();else if(w&&!b){let R=u.parentContextId.split("/")[0]||u.parentContextId,$=this._contextKeyCache.get(R);if(!$){let{keyId:P,keyUri:_}=yield ic(this.agent,t.author),S=ke.constructKeyDerivationPathUsingProtocolContextScheme(R);$={keyId:P,keyUri:_,contextDerivationPath:S},this._contextKeyCache.set(R,$)}let E=yield this.agent.keyManager.derivePublicKey({keyUri:$.keyUri,derivationPath:$.contextDerivationPath});C=Tm(I,M,$.keyId,E,St.ProtocolContext)}else w&&b?C=void 0:C=z();let{encryptedBytes:L,dataCid:B,dataSize:H,authenticationTag:ee}=yield fS(T,I,M,D);if(u.dataCid=B,u.dataSize=H,delete u.data,a=Et.fromBytes(L),t.dataStream=void 0,C?(C.authenticationTag=ee,u.encryptionInput=C):d={dataEncryptionKey:I,dataEncryptionIV:M,encryptedBytes:L,authenticationTag:ee},f&&w){let{keyId:R,keyUri:$}=yield ic(this.agent,t.author),E=[St.ProtocolPath,Rs.protocol,"contextKey"],P=yield this.agent.keyManager.derivePublicKey({keyUri:$,derivationPath:E});u.authorKeyDeliveryPublicKey={rootKeyId:R,publicKeyJwk:P}}}}let l,c=gm[t.messageType];if(o){if(l=yield c.parse(o),ol(l)&&t.signAsOwner){let u=yield this.getSigner(t.author);yield l.signAsOwner(u)}else if(t.granteeDid&&ol(l)&&t.signAsOwnerDelegate){let u=yield this.getSigner(t.granteeDid),f=t.messageParams;yield l.signAsOwnerDelegate(u,f.delegatedGrant)}}else{if(t.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let u=t.granteeDid?yield this.getSigner(t.granteeDid):yield this.getSigner(t.author),f=Object.assign({},t.messageParams);if(t.granteeDid&&f.permissionGrantId&&!f.delegatedGrant&&nc(t,ve.RecordsWrite)){let{reply:h}=yield this.processRequest({author:t.granteeDid,target:t.author,messageType:ve.RecordsRead,messageParams:{filter:{recordId:f.permissionGrantId}}});if(h.status.code===200&&(!((i=h.entry)===null||i===void 0)&&i.recordsWrite)&&(!((s=h.entry)===null||s===void 0)&&s.data)){let p=yield Et.toBytes(h.entry.data);f.delegatedGrant=Object.assign(Object.assign({},h.entry.recordsWrite),{encodedData:ae.uint8Array(p).toBase64Url()})}}if(l=yield c.create(Object.assign(Object.assign({},f),{signer:u})),d&&nc(t,ve.RecordsWrite)){let h=l,p=h.message.recordId,{encryptionInput:m,keyId:y,keyUri:v,contextDerivationPath:w}=yield dV(this.agent,t.author,p,d.dataEncryptionKey,d.dataEncryptionIV),b=Object.assign(Object.assign({},m),{authenticationTag:d.authenticationTag});yield h.encryptSymmetricEncryptionKey(b),yield h.sign({signer:u}),this._contextKeyCache.set(p,{keyId:y,keyUri:v,contextDerivationPath:w})}}return{message:l.message,dataStream:a}})}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}getSigner(e){return xr(this,void 0,void 0,function*(){if(e===this.agent.agentDid.uri){let t=yield this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:n=>xr(this,void 0,void 0,function*(){return yield t.sign({data:n})})}}else try{let t=yield this.agent.did.get({didUri:e});if(t){let a=yield t.getSigner();return{algorithm:a.algorithm,keyId:a.keyId,sign:d=>xr(this,void 0,void 0,function*(){return yield a.sign({data:d})})}}let n=yield 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=yield this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),s=yield this.agent.keyManager.getPublicKey({keyUri:i}),o=this.agent.keyManager;return{algorithm:Jr.getJoseSignatureAlgorithmFromPublicKey(s),keyId:n.id,sign:a=>xr(this,void 0,void 0,function*(){return yield o.sign({data:a,keyUri:i})})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}})}getEncryptionKeyDeriver(e){return xr(this,void 0,void 0,function*(){return g1(this.agent,e)})}getEncryptionKeyInfo(e){return xr(this,void 0,void 0,function*(){return ic(this.agent,e)})}getKeyDecrypter(e){return xr(this,void 0,void 0,function*(){return E$(this.agent,e)})}detectNewParticipants(e){return y$(e)}getProtocolDefinition(e,t,n){return xr(this,void 0,void 0,function*(){if(!this._dwn)try{return yield this.fetchRemoteProtocolDefinition(e,t)}catch(s){let o=s instanceof Error?s.message:"";if(o.includes("not found")||o.includes("404")||o.includes("No protocol"))return;throw s}let i;if(n)try{let s=new Pn({agent:this.agent}),{grant:o}=yield s.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:ve.ProtocolsQuery});i=o.id}catch{}return yV(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)})}fetchRemoteProtocolDefinition(e,t){return xr(this,void 0,void 0,function*(){return gV(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)})}extractDerivedPublicKey(e,t,n,i){return xr(this,void 0,void 0,function*(){return wV(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))})}maybeDecryptReply(e,t){return xr(this,void 0,void 0,function*(){return uV(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)})}getDwnMessage(e){return xr(this,arguments,void 0,function*({author:t,messageCid:n}){let i=yield this.getSigner(t),s=yield gm[ve.MessagesRead].create({messageCid:n,signer:i}),o;if(this._dwn?o=yield this._dwn.processMessage(t,s.message):o=yield this.sendDwnRpcRequest({targetDid:t,dwnEndpointUrls:[this._localDwnEndpoint],message:s.message}),o.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${o.status.code} - ${o.status.detail}`);let a=o.entry,l={message:a.message};if(ol(a)){let c=a.data;if(c){let u=yield Et.toBytes(c);l.data=new Blob([u],{type:a.message.descriptor.dataFormat})}}return l})}ensureKeyDeliveryProtocol(e){return xr(this,void 0,void 0,function*(){return fV(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 a of i)this._delegateContextKeyCache.delete(a);let s=[];for(let a of t){let d=`dctx~${e}~${a.protocol}~${a.contextId}`;this._delegateContextKeyCache.set(d,a.derivedPrivateKey),s.push(d)}this._delegateContextKeyCacheIndex.set(e,s);let o=new Set(n??[]);for(let a of t)o.add(a.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 s of t){let o=this._delegateContextKeyCache.get(s);if(!o||!s.startsWith(i))continue;let a=s.slice(i.length),d=a.lastIndexOf("~");d!==-1&&n.push({protocol:a.slice(0,d),contextId:a.slice(d+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){var i,s;for(let[o,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let d=`dctx~${o}~${e}~${t}`;if(this._delegateContextKeyCache.get(d))continue;this._delegateContextKeyCache.set(d,n);let l=(i=this._delegateContextKeyCacheIndex.get(o))!==null&&i!==void 0?i:[];l.push(d),this._delegateContextKeyCacheIndex.set(o,l),(s=this._onDelegateContextKeysChanged)===null||s===void 0||s.call(this,o)}}deliverContextKeyToDelegatesViaDwn(e,t,n,i){return xr(this,void 0,void 0,function*(){try{let o=yield new Pn({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),a=new Set(["Read","Query","Subscribe"]),d=Date.now(),l=new Set;for(let c of o){if(!c.grant.delegated||new Date(c.grant.dateExpires).getTime()<=d)continue;let u=c.grant.scope;if(u.interface!=="Records"||!a.has(u.method)||u.protocolPath||u.contextId)continue;let f=c.grant.grantee,h=c.grant.delegateKeyDelivery;if(!h?.rootKeyId||!h?.publicKeyJwk||l.has(f))continue;let p=h.publicKeyJwk;try{yield this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:h.rootKeyId,publicKeyJwk:p}}),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(s){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${s.message}`)}})}trackEagerSend(e){return this._pendingEagerSends.add(e),e.finally(()=>{this._pendingEagerSends.delete(e)}),e}drainPendingEagerSends(){return xr(this,void 0,void 0,function*(){if(this._pendingEagerSends.size===0)return;let e=[...this._pendingEagerSends];yield Promise.allSettled(e)})}writeContextKeyRecord(e){return xr(this,void 0,void 0,function*(){return hV(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this),this.trackEagerSend.bind(this))})}eagerSendContextKeyRecord(e,t){return xr(this,void 0,void 0,function*(){return pV(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))})}fetchContextKeyRecord(e){return xr(this,void 0,void 0,function*(){return mV(this.agent,e,this.processRequest.bind(this))})}};g();function vV(r){try{let e=W0e(r),t=JSON.parse(e);return F0e(t)?t:void 0}catch{return}}function bV(r){let e=r.indexOf("#");if(e===-1)return vV(r);let t=r.slice(e+1);if(t.length!==0)return vV(t)}function F0e(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!G0e(e.endpoint))}function G0e(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 W0e(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 s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return new TextDecoder().decode(i)}g();g();EP();cx();g();px();uc();var H0e=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),PV=Uint8Array.from({length:16},(r,e)=>e),V0e=PV.map(r=>(9*r+5)%16),D$=[PV],k$=[V0e];for(let r=0;r<4;r++)for(let e of[D$,k$])e.push(e[r].map(t=>H0e[t]));var _V=[[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)),J0e=D$.map((r,e)=>r.map(t=>_V[e][t])),Y0e=k$.map((r,e)=>r.map(t=>_V[e][t])),Z0e=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Q0e=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),hS=(r,e)=>r<<e|r>>>32-e;function xV(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 pS=new Uint32Array(16),T$=class extends Ku{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:s}=this;return[e,t,n,i,s]}set(e,t,n,i,s){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(e,t){for(let h=0;h<16;h++,t+=4)pS[h]=e.getUint32(t,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,d=a,l=this.h3|0,c=l,u=this.h4|0,f=u;for(let h=0;h<5;h++){let p=4-h,m=Z0e[h],y=Q0e[h],v=D$[h],w=k$[h],b=J0e[h],T=Y0e[h];for(let D=0;D<16;D++){let I=hS(n+xV(h,s,a,l)+pS[v[D]]+m,b[D])+u|0;n=u,u=l,l=hS(a,10)|0,a=s,s=I}for(let D=0;D<16;D++){let I=hS(i+xV(p,o,d,c)+pS[w[D]]+y,T[D])+f|0;i=f,f=c,c=hS(d,10)|0,d=o,o=I}}this.set(this.h1+a+c|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+o|0,this.h0+s+d|0)}roundClean(){pS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},EV=Qm(()=>new T$);Gw();xP();uc();Ym();var X0e=qw("ed25519 seed"),A$=2147483648,SV=new Uint8Array([0]);function TV(r,...e){return typeof r=="string"&&(r=k8(r)),yl(r,...e),r}var eve=r=>EV(zu(r)),tve=r=>wl(r).getUint32(0,!1),I$=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 wl(e).setUint32(0,r,!1),e},mS=class r{get publicKeyRaw(){return ka.getPublicKey(this.privateKey)}get publicKey(){return Rh(SV,this.publicKeyRaw)}get pubHash(){return eve(this.publicKey)}get fingerprint(){return tve(this.pubHash)}get fingerprintHex(){return AT(I$(this.fingerprint))}get parentFingerprintHex(){return AT(I$(this.parentFingerprint))}static fromMasterSeed(e){if(e=TV(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=Mu(hf,X0e,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(yl(e.privateKey,32),yl(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 s of n){let o=/^(\d+)('?)$/.exec(s);if(!o||o.length!==3)throw new Error(`Invalid child index: ${s}`);let a=+o[1];if(!Number.isSafeInteger(a)||a>=A$)throw new Error("Invalid index");(t||o[2]==="'")&&(a+=A$),i=i.deriveChild(a)}return i}deriveChild(e){if(e<A$)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Rh(SV,this.privateKey,I$(e)),n=Mu(hf,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 ka.sign(e,this.privateKey)}verify(e,t){return t=TV(t,64),ka.verify(t,e,this.publicKeyRaw)}};g();var R$=`abandon
|
|
10
|
+
deps: ${t}}`};var Mde={keyword:"dependencies",type:"object",schemaType:"object",error:Fd.error,code(r){let[e,t]=Ude(r);y9(r,e),g9(r,t)}};function Ude({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 y9(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let d=(0,ab.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(d,()=>{for(let l of a)(0,ab.checkReportMissingProp)(r,l)}):(t.if((0,zC._)`${d} && (${(0,ab.checkMissingProp)(r,a,s)})`),(0,ab.reportMissingProp)(r,s),t.else())}}Fd.validatePropertyDeps=y9;function g9(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,Nde.alwaysValidSchema)(s,e[a])||(t.if((0,ab.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let d=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(d,o)},()=>t.var(o,!0)),r.ok(o))}Fd.validateSchemaDeps=g9;Fd.default=Mde});var v9=Te(FC=>{"use strict";g();Object.defineProperty(FC,"__esModule",{value:!0});var w9=$t(),Kde=Zt(),Lde={message:"property name must be valid",params:({params:r})=>(0,w9._)`{propertyName: ${r.propertyName}}`},qde={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Lde,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Kde.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,w9.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};FC.default=qde});var WC=Te(GC=>{"use strict";g();Object.defineProperty(GC,"__esModule",{value:!0});var i2=Na(),qc=$t(),zde=ja(),o2=Zt(),Fde={message:"must NOT have additional properties",params:({params:r})=>(0,qc._)`{additionalProperty: ${r.additionalProperty}}`},Gde={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Fde,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:d}=o;if(o.props=!0,d.removeAdditional!=="all"&&(0,o2.alwaysValidSchema)(o,t))return;let l=(0,i2.allSchemaProperties)(n.properties),c=(0,i2.allSchemaProperties)(n.patternProperties);u(),r.ok((0,qc._)`${s} === ${zde.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!c.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let v;if(l.length>8){let w=(0,o2.schemaRefOrVal)(o,n.properties,"properties");v=(0,i2.isOwnProperty)(e,w,y)}else l.length?v=(0,qc.or)(...l.map(w=>(0,qc._)`${y} === ${w}`)):v=qc.nil;return c.length&&(v=(0,qc.or)(v,...c.map(w=>(0,qc._)`${(0,i2.usePattern)(r,w)}.test(${y})`))),(0,qc.not)(v)}function h(y){e.code((0,qc._)`delete ${i}[${y}]`)}function p(y){if(d.removeAdditional==="all"||d.removeAdditional&&t===!1){h(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,o2.alwaysValidSchema)(o,t)){let v=e.name("valid");d.removeAdditional==="failing"?(m(y,v,!1),e.if((0,qc.not)(v),()=>{r.reset(),h(y)})):(m(y,v),a||e.if((0,qc.not)(v),()=>e.break()))}}function m(y,v,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:o2.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(b,v)}}};GC.default=Gde});var P9=Te(VC=>{"use strict";g();Object.defineProperty(VC,"__esModule",{value:!0});var Wde=Wv(),b9=Na(),HC=Zt(),x9=WC(),Hde={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&x9.default.code(new Wde.KeywordCxt(s,x9.default,"additionalProperties"));let o=(0,b9.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=HC.mergeEvaluated.props(e,(0,HC.toHash)(o),s.props));let a=o.filter(u=>!(0,HC.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let d=e.name("valid");for(let u of a)l(u)?c(u):(e.if((0,b9.propertyInData)(e,i,u,s.opts.ownProperties)),c(u),s.allErrors||e.else().var(d,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(d);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function c(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},d)}}};VC.default=Hde});var T9=Te(JC=>{"use strict";g();Object.defineProperty(JC,"__esModule",{value:!0});var _9=Na(),s2=$t(),E9=Zt(),S9=Zt(),Vde={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,_9.allSchemaProperties)(t),d=a.filter(m=>(0,E9.alwaysValidSchema)(s,t[m]));if(a.length===0||d.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,c=e.name("valid");s.props!==!0&&!(s.props instanceof s2.Name)&&(s.props=(0,S9.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let m of a)l&&h(m),s.allErrors?p(m):(e.var(c,!0),p(m),e.if(c))}function h(m){for(let y in l)new RegExp(m).test(y)&&(0,E9.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,s2._)`${(0,_9.usePattern)(r,m)}.test(${y})`,()=>{let v=d.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:S9.Type.Str},c),s.opts.unevaluated&&u!==!0?e.assign((0,s2._)`${u}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,s2.not)(c),()=>e.break())})})}}};JC.default=Vde});var D9=Te(YC=>{"use strict";g();Object.defineProperty(YC,"__esModule",{value:!0});var Jde=Zt(),Yde={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,Jde.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"}};YC.default=Yde});var k9=Te(ZC=>{"use strict";g();Object.defineProperty(ZC,"__esModule",{value:!0});var Zde=Na(),Qde={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Zde.validateUnion,error:{message:"must match a schema in anyOf"}};ZC.default=Qde});var A9=Te(QC=>{"use strict";g();Object.defineProperty(QC,"__esModule",{value:!0});var a2=$t(),Xde=Zt(),ele={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,a2._)`{passingSchemas: ${r.passing}}`},tle={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ele,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 s=t,o=e.let("valid",!1),a=e.let("passing",null),d=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((c,u)=>{let f;(0,Xde.alwaysValidSchema)(i,c)?e.var(d,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},d),u>0&&e.if((0,a2._)`${d} && ${o}`).assign(o,!1).assign(a,(0,a2._)`[${a}, ${u}]`).else(),e.if(d,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,a2.Name)})})}}};QC.default=tle});var I9=Te(XC=>{"use strict";g();Object.defineProperty(XC,"__esModule",{value:!0});var rle=Zt(),nle={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((s,o)=>{if((0,rle.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};XC.default=nle});var $9=Te(e6=>{"use strict";g();Object.defineProperty(e6,"__esModule",{value:!0});var c2=$t(),C9=Zt(),ile={message:({params:r})=>(0,c2.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,c2._)`{failingKeyword: ${r.ifClause}}`},ole={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ile,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,C9.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=R9(n,"then"),s=R9(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(d(),r.reset(),i&&s){let c=e.let("ifClause");r.setParams({ifClause:c}),e.if(a,l("then",c),l("else",c))}else i?e.if(a,l("then")):e.if((0,c2.not)(a),l("else"));r.pass(o,()=>r.error(!0));function d(){let c=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(c)}function l(c,u){return()=>{let f=r.subschema({keyword:c},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,c2._)`${c}`):r.setParams({ifClause:c})}}}};function R9(r,e){let t=r.schema[e];return t!==void 0&&!(0,C9.alwaysValidSchema)(r,t)}e6.default=ole});var O9=Te(t6=>{"use strict";g();Object.defineProperty(t6,"__esModule",{value:!0});var sle=Zt(),ale={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,sle.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};t6.default=ale});var B9=Te(r6=>{"use strict";g();Object.defineProperty(r6,"__esModule",{value:!0});var cle=MC(),dle=f9(),lle=UC(),ule=p9(),fle=m9(),hle=n2(),ple=v9(),mle=WC(),yle=P9(),gle=T9(),wle=D9(),vle=k9(),ble=A9(),xle=I9(),Ple=$9(),_le=O9();function Ele(r=!1){let e=[wle.default,vle.default,ble.default,xle.default,Ple.default,_le.default,ple.default,mle.default,hle.default,yle.default,gle.default];return r?e.push(dle.default,ule.default):e.push(cle.default,lle.default),e.push(fle.default),e}r6.default=Ele});var i6=Te(cb=>{"use strict";g();Object.defineProperty(cb,"__esModule",{value:!0});cb.dynamicAnchor=void 0;var n6=$t(),Sle=ja(),j9=Vv(),Tle=Z_(),Dle={keyword:"$dynamicAnchor",schemaType:"string",code:r=>N9(r,r.schema)};function N9(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,n6._)`${Sle.default.dynamicAnchors}${(0,n6.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:kle(r);t.if((0,n6._)`!${i}`,()=>t.assign(i,s))}cb.dynamicAnchor=N9;function kle(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:d}=n.opts,l=new j9.SchemaEnv({schema:t,schemaId:d,root:i,baseId:s,localRefs:o,meta:a});return j9.compileSchema.call(n,l),(0,Tle.getValidate)(r,l)}cb.default=Dle});var o6=Te(db=>{"use strict";g();Object.defineProperty(db,"__esModule",{value:!0});db.dynamicRef=void 0;var M9=$t(),Ale=ja(),U9=Z_(),Ile={keyword:"$dynamicRef",schemaType:"string",code:r=>K9(r,r.schema)};function K9(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let d=t.let("valid",!1);o(d),r.ok(d)}function o(d){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,M9._)`${Ale.default.dynamicAnchors}${(0,M9.getProperty)(s)}`);t.if(l,a(l,d),a(i.validateName,d))}else a(i.validateName,d)()}function a(d,l){return l?()=>t.block(()=>{(0,U9.callRef)(r,d),t.let(l,!0)}):()=>(0,U9.callRef)(r,d)}}db.dynamicRef=K9;db.default=Ile});var L9=Te(s6=>{"use strict";g();Object.defineProperty(s6,"__esModule",{value:!0});var Rle=i6(),Cle=Zt(),$le={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,Rle.dynamicAnchor)(r,""):(0,Cle.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};s6.default=$le});var q9=Te(a6=>{"use strict";g();Object.defineProperty(a6,"__esModule",{value:!0});var Ole=o6(),Ble={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Ole.dynamicRef)(r,r.schema)};a6.default=Ble});var z9=Te(c6=>{"use strict";g();Object.defineProperty(c6,"__esModule",{value:!0});var jle=i6(),Nle=o6(),Mle=L9(),Ule=q9(),Kle=[jle.default,Nle.default,Mle.default,Ule.default];c6.default=Kle});var G9=Te(d6=>{"use strict";g();Object.defineProperty(d6,"__esModule",{value:!0});var F9=n2(),Lle={keyword:"dependentRequired",type:"object",schemaType:"object",error:F9.error,code:r=>(0,F9.validatePropertyDeps)(r)};d6.default=Lle});var W9=Te(l6=>{"use strict";g();Object.defineProperty(l6,"__esModule",{value:!0});var qle=n2(),zle={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,qle.validateSchemaDeps)(r)};l6.default=zle});var H9=Te(u6=>{"use strict";g();Object.defineProperty(u6,"__esModule",{value:!0});var Fle=Zt(),Gle={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Fle.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};u6.default=Gle});var V9=Te(f6=>{"use strict";g();Object.defineProperty(f6,"__esModule",{value:!0});var Wle=G9(),Hle=W9(),Vle=H9(),Jle=[Wle.default,Hle.default,Vle.default];f6.default=Jle});var Y9=Te(h6=>{"use strict";g();Object.defineProperty(h6,"__esModule",{value:!0});var Kf=$t(),J9=Zt(),Yle=ja(),Zle={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Kf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},Qle={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Zle,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof Kf.Name?e.if((0,Kf._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>d(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?d(u):e.if(c(a,u),()=>d(u))),s.props=!0,r.ok((0,Kf._)`${i} === ${Yle.default.errors}`);function d(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,J9.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:J9.Type.Str},f),o||e.if((0,Kf.not)(f),()=>e.break())}}function l(u,f){return(0,Kf._)`!${u} || !${u}[${f}]`}function c(u,f){let h=[];for(let p in u)u[p]===!0&&h.push((0,Kf._)`${f} !== ${p}`);return(0,Kf.and)(...h)}}};h6.default=Qle});var Q9=Te(p6=>{"use strict";g();Object.defineProperty(p6,"__esModule",{value:!0});var jp=$t(),Z9=Zt(),Xle={message:({params:{len:r}})=>(0,jp.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,jp._)`{limit: ${r}}`},eue={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Xle,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,jp._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,jp._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Z9.alwaysValidSchema)(i,t)){let d=e.var("valid",(0,jp._)`${o} <= ${s}`);e.if((0,jp.not)(d),()=>a(d,s)),r.ok(d)}i.items=!0;function a(d,l){e.forRange("i",l,o,c=>{r.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:Z9.Type.Num},d),i.allErrors||e.if((0,jp.not)(d),()=>e.break())})}}};p6.default=eue});var X9=Te(m6=>{"use strict";g();Object.defineProperty(m6,"__esModule",{value:!0});var tue=Y9(),rue=Q9(),nue=[tue.default,rue.default];m6.default=nue});var ez=Te(y6=>{"use strict";g();Object.defineProperty(y6,"__esModule",{value:!0});var Vn=$t(),iue={message:({schemaCode:r})=>(0,Vn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Vn._)`{format: ${r}}`},oue={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iue,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:d,errSchemaPath:l,schemaEnv:c,self:u}=a;if(!d.validateFormats)return;i?f():h();function f(){let p=t.scopeValue("formats",{ref:u.formats,code:d.code.formats}),m=t.const("fDef",(0,Vn._)`${p}[${o}]`),y=t.let("fType"),v=t.let("format");t.if((0,Vn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,Vn._)`${m}.type || "string"`).assign(v,(0,Vn._)`${m}.validate`),()=>t.assign(y,(0,Vn._)`"string"`).assign(v,m)),r.fail$data((0,Vn.or)(w(),b()));function w(){return d.strictSchema===!1?Vn.nil:(0,Vn._)`${o} && !${v}`}function b(){let T=c.$async?(0,Vn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Vn._)`${v}(${n})`,D=(0,Vn._)`(typeof ${v} == "function" ? ${T} : ${v}.test(${n}))`;return(0,Vn._)`${v} && ${v} !== true && ${y} === ${e} && !${D}`}}function h(){let p=u.formats[s];if(!p){w();return}if(p===!0)return;let[m,y,v]=b(p);m===e&&r.pass(T());function w(){if(d.strictSchema===!1){u.logger.warn(D());return}throw new Error(D());function D(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function b(D){let I=D instanceof RegExp?(0,Vn.regexpCode)(D):d.code.formats?(0,Vn._)`${d.code.formats}${(0,Vn.getProperty)(s)}`:void 0,M=t.scopeValue("formats",{key:s,ref:D,code:I});return typeof D=="object"&&!(D instanceof RegExp)?[D.type||"string",D.validate,(0,Vn._)`${M}.validate`]:["string",D,M]}function T(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!c.$async)throw new Error("async format in sync schema");return(0,Vn._)`await ${v}(${n})`}return typeof y=="function"?(0,Vn._)`${v}(${n})`:(0,Vn._)`${v}.test(${n})`}}}};y6.default=oue});var tz=Te(g6=>{"use strict";g();Object.defineProperty(g6,"__esModule",{value:!0});var sue=ez(),aue=[sue.default];g6.default=aue});var rz=Te(Eg=>{"use strict";g();Object.defineProperty(Eg,"__esModule",{value:!0});Eg.contentVocabulary=Eg.metadataVocabulary=void 0;Eg.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Eg.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var iz=Te(w6=>{"use strict";g();Object.defineProperty(w6,"__esModule",{value:!0});var cue=Yq(),due=c9(),lue=B9(),uue=z9(),fue=V9(),hue=X9(),pue=tz(),nz=rz(),mue=[uue.default,cue.default,due.default,(0,lue.default)(!0),pue.default,nz.metadataVocabulary,nz.contentVocabulary,fue.default,hue.default];w6.default=mue});var sz=Te(d2=>{"use strict";g();Object.defineProperty(d2,"__esModule",{value:!0});d2.DiscrError=void 0;var oz;(function(r){r.Tag="tag",r.Mapping="mapping"})(oz||(d2.DiscrError=oz={}))});var cz=Te(b6=>{"use strict";g();Object.defineProperty(b6,"__esModule",{value:!0});var Sg=$t(),v6=sz(),az=Vv(),yue=Hv(),gue=Zt(),wue={message:({params:{discrError:r,tagName:e}})=>r===v6.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Sg._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},vue={keyword:"discriminator",type:"object",schemaType:"object",error:wue,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="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 d=e.let("valid",!1),l=e.const("tag",(0,Sg._)`${t}${(0,Sg.getProperty)(a)}`);e.if((0,Sg._)`typeof ${l} == "string"`,()=>c(),()=>r.error(!1,{discrError:v6.DiscrError.Tag,tag:l,tagName:a})),r.ok(d);function c(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Sg._)`${l} === ${p}`),e.assign(d,u(h[p]));e.else(),r.error(!1,{discrError:v6.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(h){let p=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:h},p);return r.mergeEvaluated(m,Sg.Name),p}function f(){var h;let p={},m=v(i),y=!0;for(let T=0;T<o.length;T++){let D=o[T];if(D?.$ref&&!(0,gue.schemaHasRulesButRef)(D,s.self.RULES)){let M=D.$ref;if(D=az.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,M),D instanceof az.SchemaEnv&&(D=D.schema),D===void 0)throw new yue.default(s.opts.uriResolver,s.baseId,M)}let I=(h=D?.properties)===null||h===void 0?void 0:h[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||v(D)),w(I,T)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return p;function v({required:T}){return Array.isArray(T)&&T.includes(a)}function w(T,D){if(T.const)b(T.const,D);else if(T.enum)for(let I of T.enum)b(I,D);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(T,D){if(typeof T!="string"||T in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[T]=D}}}};b6.default=vue});var dz=Te((bUe,bue)=>{bue.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 lz=Te((xUe,xue)=>{xue.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 uz=Te((PUe,Pue)=>{Pue.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 fz=Te((_Ue,_ue)=>{_ue.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 hz=Te((EUe,Eue)=>{Eue.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 pz=Te((SUe,Sue)=>{Sue.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 mz=Te((TUe,Tue)=>{Tue.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 yz=Te((DUe,Due)=>{Due.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 gz=Te(x6=>{"use strict";g();Object.defineProperty(x6,"__esModule",{value:!0});var kue=dz(),Aue=lz(),Iue=uz(),Rue=fz(),Cue=hz(),$ue=pz(),Oue=mz(),Bue=yz(),jue=["/properties"];function Nue(r){return[kue,Aue,Iue,Rue,Cue,e(this,$ue),Oue,e(this,Bue)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,jue):n}}x6.default=Nue});var E6=Te((un,_6)=>{"use strict";g();Object.defineProperty(un,"__esModule",{value:!0});un.MissingRefError=un.ValidationError=un.CodeGen=un.Name=un.nil=un.stringify=un.str=un._=un.KeywordCxt=un.Ajv2020=void 0;var Mue=Gq(),Uue=iz(),Kue=cz(),Lue=gz(),P6="https://json-schema.org/draft/2020-12/schema",Tg=class extends Mue.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Uue.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Kue.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Lue.default.call(this,e),this.refs["http://json-schema.org/schema"]=P6)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(P6)?P6:void 0)}};un.Ajv2020=Tg;_6.exports=un=Tg;_6.exports.Ajv2020=Tg;Object.defineProperty(un,"__esModule",{value:!0});un.default=Tg;var que=Wv();Object.defineProperty(un,"KeywordCxt",{enumerable:!0,get:function(){return que.KeywordCxt}});var Dg=$t();Object.defineProperty(un,"_",{enumerable:!0,get:function(){return Dg._}});Object.defineProperty(un,"str",{enumerable:!0,get:function(){return Dg.str}});Object.defineProperty(un,"stringify",{enumerable:!0,get:function(){return Dg.stringify}});Object.defineProperty(un,"nil",{enumerable:!0,get:function(){return Dg.nil}});Object.defineProperty(un,"Name",{enumerable:!0,get:function(){return Dg.Name}});Object.defineProperty(un,"CodeGen",{enumerable:!0,get:function(){return Dg.CodeGen}});var zue=q_();Object.defineProperty(un,"ValidationError",{enumerable:!0,get:function(){return zue.default}});var Fue=Hv();Object.defineProperty(un,"MissingRefError",{enumerable:!0,get:function(){return Fue.default}})});var Lf,l2=G(()=>{"use strict";g();BP();xt();Lf=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:s,messageStore:o}=e;await Ys.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:s,messageStore:o}),r.verifyScope(t,s.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:s,messageStore:o}=e;await Ys.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:s,messageStore:o});let d=s.scope.protocol,l=i.descriptor.filter?.protocol;if(d!==void 0&&l!==d)throw new ne(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${d} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ne(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function es(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 qf(r){return r.includes(":")}function u2(r){return r.split("/").slice(-1)[0]}function Wd(r,e){let t=r.split("/"),n,i=e;for(let s of t){if(!Object.hasOwn(i,s))return;n=i[s],i=n}return n}var Gd,Np=G(()=>{"use strict";g();gn();jy();Gd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,c=[St.ProtocolPath,e.protocol];async function u(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];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,c),i}let s=t;async function o(l,c){for(let u in l)if(!u.startsWith("$")){let f=await zi.derivePrivateKey(c,[u]),h=l[u];if(h.$ref!==void 0){await o(h,f);continue}let p=await kt.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:s,publicKeyJwk:p},await o(h,f)}}let a={derivationScheme:St.ProtocolPath,derivedPrivateKey:n,rootKeyId:s},d=await zi.derivePrivateKey(a,[St.ProtocolPath,e.protocol]);return await o(i.structure,d),i}}});var wz,Ka,f2=G(()=>{"use strict";g();Mc();wz=Rn(E6(),1);vr();Tc();l2();Yo();xt();lr();Np();Ia();kw();Ka=class r extends Mn{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??At.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=Ht.parse(this.message.authorization.authorDelegatedGrant);await Lf.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;mi(t);for(let s in n){let o=n[s].schema;o!==void 0&&Sd(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 ne(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{mi(e[i])}catch{throw new ne(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ne(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 ne(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let s=t[i],o;e===""?o=i:o=`${e}/${i}`,s.$role?n.push(o):r.fetchAllRolePathsRecursively(o,s,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:s,uses:o,types:a}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ne(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:c}=t.$size;if(c!==void 0&&c<l)throw new ne(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${c} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:c}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Cu);if(!u.includes(c))throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${c}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new wz.default.default,{$allowUndefinedTags:c,$requiredTags:u,...f}=t.$tags;for(let h in f){let p=f[h];if(!l.validateSchema(p)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${h}`});throw new ne(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let d=t.$actions??[];for(let l=0;l<d.length;l++){let c=d[l];if(c.role!==void 0){if(qf(c.role))r.validateCrossProtocolAlias(c.role,o,n,"role");else if(!s.includes(c.role))throw new ne(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(c)} for rule set ${n} does not exist.`)}if(c.who==="anyone"&&c.of)throw new ne(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(c.who===td.Recipient&&c.of===void 0&&c.can.some(f=>![_r.CoUpdate,_r.CoDelete,_r.CoPrune].includes(f)))throw new ne(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(c.who===td.Author&&!c.of)throw new ne(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(c.of!==void 0&&n!==""){if(qf(c.of))r.validateCrossProtocolAlias(c.of,o,n,"of");else if(!(n===c.of||n.startsWith(c.of+"/")))throw new ne(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${c.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(c)}.`)}if(c.can!==void 0){if(c.can.includes(_r.Update)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'update' action but missing the required 'create' action.`);if(c.can.includes(_r.Delete)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'delete' action but missing the required 'create' action.`);if(c.can.includes(_r.Prune)&&!c.can.includes(_r.Create))throw new ne(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<d.length;u++){let f=d[u];if(c.who===void 0){if(c.role===f.role)throw new ne(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${c.role} not allowed within a rule set: ${JSON.stringify(c)}`)}else if(c.who===f.who&&c.of===f.of)throw new ne(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${c.who} of ${c.of} not allowed within a rule set: ${JSON.stringify(c)}`)}}if(n!==""){let l=n.split("/").pop();a[l]?.encryptionRequired===!0&&d.some(f=>f.who===td.Anyone&&f.can.includes(_r.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&&d.length>0&&d.some(c=>c.can.includes(_r.Update)||c.can.includes(_r.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 c=t[l];if(c.$ref===void 0&&!i.includes(l))throw new ne(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:c,ruleSetProtocolPath:u,recordTypes:i,roles:s,uses:o,types:a})}}static validateRefNode(e,t,n){let i=e.$ref,s=es(i);if(s===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n?.[s.alias]===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${s.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 a of o)if(e[a]!==void 0)throw new ne(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${a}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let s=es(e);if(s===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(o,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t?.[s.alias]===void 0){let o=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(o,`cross-protocol '${i}' alias '${s.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 s=t[i].schema;s!==void 0&&(t[i].schema=cp(s))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Fo(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Fo(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var h2,vz=G(()=>{"use strict";g();ra();vr();na();ia();f2();l2();xt();lr();Np();h2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Ka.parse(t)}catch(c){return gt(c,400)}try{await bn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(c){return gt(c,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(c){return gt(c,400)}let i={interface:xe.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:s}=await this.deps.messageStore.query(e,[i]),o=await ye.getCid(t);for(let c of s)if(await ye.getCid(c)===o)return{status:{code:409,detail:"Conflict"}};let a=await ye.getNewestMessage(s),d=!1;(a===void 0||await ye.isNewer(t,a))&&(d=!0,a=t);let l;if(d){let c=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,c);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,c),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},c,u),l={status:{code:202,detail:"Accepted"}}}else{let c=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,c);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,c),l={status:{code:202,detail:"Accepted"}}}for(let c of s)if(c!==a){let u=await Ka.parse(c),f=r.constructIndexes(u,!1),h=await ye.getCid(c);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,c,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:s}=e;return{...i,author:s,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 Qe.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Lf.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ne(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let s=new Map;for(let o in i){let a=i[o],d=await r.fetchInstalledProtocolDefinition(e,a,n);if(d===void 0)throw new ne(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${a}' (alias '${o}') is not installed for tenant '${e}'.`);s.set(o,d)}r.validateRefsAndRolesRecursively(t.structure,"",s)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:xe.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:s}=await n.query(e,[i]);if(s.length!==0)return s[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let s=e[i],o=t===""?i:`${t}/${i}`;if(s.$ref!==void 0){let d=es(s.$ref);if(d!==void 0){let l=n.get(d.alias);if(l===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${d.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let c=d.protocolPath.split("/"),u=l.structure;for(let f=0;f<c.length;f++){let h=c[f],p=u[h];if(p===void 0)throw new ne(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${o}' references type path '${d.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(p.$ref!==void 0){let m=c.slice(0,f+1).join("/");throw new ne(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${o}' references type path '${d.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=p}}}let a=s.$actions??[];for(let d of a){if(d.role!==void 0){let l=es(d.role);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${d.role}' at protocol path '${o}' was not found in the referenced definitions map.`);if(!Wd(l.protocolPath,c.structure)?.$role)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${d.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${c.protocol}'.`)}}if(d.of!==void 0){let l=es(d.of);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${d.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(Wd(l.protocolPath,c.structure)===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${d.of}' at protocol path '${o}' does not point to a valid type path in protocol '${c.protocol}'.`)}}}r.validateRefsAndRolesRecursively(s,o,n)}}}});var La,p2=G(()=>{"use strict";g();Mc();vr();ia();l2();He();Yo();xt();lr();Ia();La=class r extends Mn{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&mi(e.descriptor.filter.protocol),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??At.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Mt(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:Fo(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Qe.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await Lf.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ne(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var m2,bz=G(()=>{"use strict";g();ra();xt();na();p2();He();lr();m2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await La.parse(t)}catch(o){return gt(o,400)}try{await bn(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 a=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:a}}else return gt(o,401)}let i={...t.descriptor.filter,interface:xe.Protocols,method:me.Configure,isLatestBaseState:!0};Mt(i);let{messages:s}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:s}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:xe.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function lb(r,e,t,n,i,s,o,a){let d=e.signaturePayload?.protocolRole;if(d===void 0)return;let l=t,c=d;if(qf(d)){let p=es(d);if(p===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${d}' could not be parsed as a valid 'alias:path' format.`);if(i.uses?.[p.alias]===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${p.alias}' in '${d}' does not exist in the protocol's 'uses' map.`);l=i.uses[p.alias],c=p.protocolPath;let m=await o(r,l,s,a);if(!Wd(c,m.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${d} does not match role record type.`)}else if(!Wd(d,i.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Protocol path ${d} does not match role record type.`);let u={interface:xe.Records,method:me.Write,protocol:l,protocolPath:c,recipient:e.author,isLatestBaseState:!0},f=c.split("/").length-1;if(n===void 0&&f>0)throw new ne(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=tr.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:h}=await s.query(r,[u]);if(h.length===0)throw new ne(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${c}`)}async function Gue(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,s=await _t.fetchInitialRecordsWrite(t,r,i);if(s===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push(_r.CoPrune),e.author===s.author&&o.push(_r.Prune)):(o.push(_r.CoDelete),e.author===s.author&&o.push(_r.Delete)),o;case me.Count:return[_r.Read];case me.Query:return[_r.Read];case me.Read:return[_r.Read];case me.Subscribe:return[_r.Read];case me.Write:let d=e;if(await d.isInitialWrite())return d.message.descriptor.squash===!0?[_r.Squash,_r.Create]:[_r.Create];{let l=e.message.recordId,c=await _t.fetchInitialRecordsWrite(t,r,l);return c===void 0?[]:e.author===c.author?[_r.CoUpdate,_r.Update]:[_r.CoUpdate]}}return[]}async function ub(r,e,t,n,i,s){let o=e.message.descriptor.method,a=await Gue(r,e,i),d=e.author,l=t.$actions;if(l===void 0)throw new ne(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${o}, ${d} is unauthorized`);let c=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(p=>a.includes(p)))continue;if(u.who===td.Anyone)return;if(d===void 0)continue;if(c!==void 0){if(u.role===c)return;continue}if(u.who===td.Recipient&&u.of===void 0){let p;if(e.message.descriptor.method===me.Write?p=e.message:p=n[n.length-1],p.descriptor.recipient===d)return;continue}if(await Wue(d,u,n,s))return}throw new ne(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Wue(r,e,t,n){let i=e.of;if(i===void 0)return!1;let s;if(qf(i)&&n?.uses!==void 0){let o=es(i);if(o!==void 0){let a=n.uses[o.alias];a!==void 0&&(s=t.find(d=>d.descriptor.protocol===a&&d.descriptor.protocolPath===o.protocolPath))}}else s=t.find(o=>o.descriptor.protocolPath===i);if(s===void 0)return!1;if(e.who===td.Recipient)return r===s.descriptor.recipient;{let o=(await _t.parse(s)).author;return r===o}}var xz=G(()=>{"use strict";g();$c();Zo();xt();lr();Np();kw()});async function kg(r,e,t){let n={interface:xe.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 fb(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let s=await kg(r,i,t);if(s===void 0)throw new ne(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(s),i=s.descriptor.parentId}return n.reverse()}async function S6(r,e,t){let n=await kg(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var Pz=G(()=>{"use strict";g();Zo();xt();lr()});async function Ez(r,e,t,n,i){let s=e.message.descriptor.protocolPath,o=u2(s),a=e.message.descriptor.parentId;if(a===void 0){if(s!==o)throw new ne(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${s}' is not valid for records with no parent'.`);return}let d=e.message.descriptor.protocol,l=await Hue(r,d,s,t,n,i),c={isLatestBaseState:!0,interface:xe.Records,method:me.Write,protocol:l,recordId:a},{messages:u}=await t.query(r,[c]),f=u[0];if(f===void 0)throw l!==d?new ne(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${a}' in protocol '${l}' for cross-protocol child at path '${s}'.`):new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${s}'.`);if(`${f.descriptor.protocolPath}/${o}`!==s)throw new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${s}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Hue(r,e,t,n,i,s){let o=t.split("/");if(o.length<=1)return e;let a=await i(r,e,n,s),d=a.structure[o[0]];if(d?.$ref!==void 0){let l=es(d.$ref);if(l!==void 0&&a.uses!==void 0){let c=a.uses[l.alias];if(c!==void 0)return o.length===2?c:e}}return e}async function Sz(r,e,t,n,i,s){let o=e.descriptor.protocolPath,a=u2(o),d=await Vue(r,o,t,n,i,s);Jue(e,d,a)}async function Vue(r,e,t,n,i,s){let o=e.split("/"),a=t.structure[o[0]];if(a?.$ref!==void 0&&o.length===1){let d=es(a.$ref);if(d!==void 0&&t.uses!==void 0){let l=t.uses[d.alias];if(l!==void 0)return(await i(r,l,n,s)).types}}return t.types}function Jue(r,e,t){let n=t??u2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let s=e[n],{schema:o}=r.descriptor;if(s.schema!==void 0&&s.schema!==o)throw new ne(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${s.schema}', instead has '${o}'`);let{dataFormat:a}=r.descriptor;if(s.dataFormats!==void 0&&!s.dataFormats.includes(a))throw new ne(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${s.dataFormats}), instead has '${a}'`);if(s.encryptionRequired===!0&&r.encryption===void 0)throw new ne(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function Tz(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ne(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ne(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function Dz(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:s,$requiredTags:o,...a}=e.$tags,d=s||!1,l=o||[],c=new _z.default.default,u=c.compile({type:"object",properties:a,required:l,additionalProperties:d});if(!u(t)){let h=c.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ne(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${h}`)}}}async function kz(r,e,t,n){if(!t.$role)return;let i=e,s=i.message.descriptor.recipient;if(s===void 0)throw new ne(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let o=i.message.descriptor.protocolPath,a={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:o,recipient:s},d=ke.getParentContextFromOfContextId(i.message.contextId);if(d!==""){let f=tr.constructPrefixFilterAsRangeFilter(d);a.contextId=f}let{messages:l}=await n.query(r,[a]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ne(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${s}' is already recipient of a role record at protocol path '${o} under the parent context ${d}.`)}async function Az(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:s,strategy:o}=t.$recordLimit,a=e.message.descriptor.protocolPath,d={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:a},l=ke.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=tr.constructPrefixFilterAsRangeFilter(l);d.contextId=u}if(await n.count(r,[d])>=s)throw o===Cu.Reject?new ne(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${s} reached at protocol path '${a}'${l===""?"":` under parent context '${l}'`}: new records are rejected until existing records are deleted.`):new ne(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${o}' is not yet implemented.`)}async function Iz(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne(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 ne(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function Rz(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ne(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var _z,Cz=G(()=>{"use strict";g();kw();_z=Rn(E6(),1);$c();ni();xt();lr();Np()});var Do,Mp=G(()=>{"use strict";g();Np();Ed();xt();lr();xz();Pz();Cz();Do=class r{static async validateReferentialIntegrity(e,t,n,i){let s=await S6(e,t,n),o=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,s,i),a=r.createBoundFetchDefinition(i);await Sz(e,t.message,o,n,a,s),await Ez(e,t,n,a,s);let d=r.getRuleSet(t.message.descriptor.protocolPath,o);await kz(e,t,d,n),Tz(t,d),Dz(t,d),await Rz(t,d),await Iz(t,d),await Az(e,t,d,n)}static async authorizeWrite(e,t,n,i){let s=await kg(e,t.message.recordId,n),o;s===void 0?o=await fb(e,t.message.descriptor.parentId,n):o=await fb(e,t.message.recordId,n);let a=await S6(e,t,n),d=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),l=r.getRuleSet(t.message.descriptor.protocolPath,d),c=r.createBoundFetchDefinition(i);await lb(e,t,t.message.descriptor.protocol,t.message.contextId,d,n,c,a),await ub(e,t,l,o,n,d)}static async authorizeRead(e,t,n,i,s){let o=await fb(e,n.message.recordId,i),a=await kg(e,n.message.recordId,i),d=a===void 0?n.message.descriptor.messageTimestamp:a.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,s),c=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(s);await lb(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await ub(e,t,c,o,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:s,protocolPath:o,contextId:a}=t.message.descriptor.filter,d=await r.fetchProtocolDefinition(e,s,n,void 0,i),l=r.getRuleSet(o,d),c=r.createBoundFetchDefinition(i);await lb(e,t,s,a,d,n,c),await ub(e,t,l,[],n,d)}static async authorizeDelete(e,t,n,i,s){let o=await fb(e,t.message.descriptor.recordId,i),a=await kg(e,t.message.descriptor.recordId,i),d=a===void 0?n.message.descriptor.messageTimestamp:a.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,s),c=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(s);await lb(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await ub(e,t,c,o,i,l)}static async fetchProtocolDefinition(e,t,n,i,s){if(s!==void 0){let l=s.getDefinition(t);if(l!==void 0)return l}let o={interface:xe.Protocols,method:me.Configure,protocol:t};i===void 0?o.isLatestBaseState=!0:o.messageTimestamp={lte:i};let{messages:a}=await n.query(e,[o],{messageTimestamp:It.Descending},{limit:1});if(a.length===0)throw new ne(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return a[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,s)=>r.fetchProtocolDefinition(t,n,i,s,e)}static getRuleSet(e,t){let n=Wd(e,t.structure);if(n===void 0)throw new ne(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var y2,$z=G(()=>{"use strict";g();ra();vr();na();Mp();ni();b_();lr();y2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Md.parse(t)}catch(s){return gt(s,400)}let i;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return gt(s,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={...ke.convertFilter(n),interface:xe.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 ke.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),ke.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),ke.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{...ke.convertFilter(t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...ke.convertFilter(t),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var qa,hb=G(()=>{"use strict";g();Mc();vr();Tc();ni();Td();He();Yo();lr();qa=class r extends Mn{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,t),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=At.getCurrentTimestamp(),i={interface:xe.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},s=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:i,authorization:s};return ye.validateJsonSchema(o),new r(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:s,recipient:o,schema:a,parentId:d,dateCreated:l}=e.descriptor,c={isLatestBaseState:!0,protocol:i,protocolPath:s,recipient:o,schema:a,parentId:d,dateCreated:l,contextId:e.contextId,author:this.author,...n};return Mt(c),c}async authorizeDelegate(e,t){let n=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var zf,g2,w2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(zf||(zf={}));g2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[zf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[zf.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(s){console.error("Error while running resumable task:",s),console.error("Resumable task:",i),t.push(i)}}}}});var v2,Oz=G(()=>{"use strict";g();ra();lr();vr();na();ia();Mp();ni();hb();Td();Zo();w2();v2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await qa.parse(t)}catch(l){return gt(l,400)}try{await bn(t.authorization,this.deps.didResolver)}catch(l){return gt(l,401)}let i={interface:xe.Records,recordId:t.descriptor.recordId},{messages:s}=await this.deps.messageStore.query(e,[i]),o=await ye.getNewestMessage(s);if(!ke.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 gt(l,401)}return await this.deps.resumableTaskManager.run({name:zf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,s){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 Qe.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Fn.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await Do.authorizeDelete(e,t,n,i,s)}}});var b2,Bz=G(()=>{"use strict";g();ra();rp();vr();na();Mp();ni();x_();Zo();Ed();lr();b2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await $a.parse(t)}catch(o){return gt(o,400)}let i,s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);i=o.messages,s=o.cursor}else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return gt(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);i=o.messages,s=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);i=o.messages,s=o.cursor}}for(let o of i)if(!await _t.isInitialWrite(o)){let d=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete d.encodedData,o.initialWrite=d}return{status:{code:200,detail:"OK"},entries:i,cursor:s}}convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:It.Ascending};case Ut.CreatedDescending:return{dateCreated:It.Descending};case Ut.PublishedAscending:return{datePublished:It.Ascending};case Ut.PublishedDescending:return{datePublished:It.Descending};case Ut.UpdatedAscending:return{messageTimestamp:It.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:s}=t.message.descriptor,o={...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,isLatestBaseState:!0},a=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],a,s)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:s}=t.message.descriptor,o=[];ke.filterIncludesPublishedRecords(s)&&o.push(r.buildPublishedRecordsFilter(t)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,t.author)&&o.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),ke.shouldProtocolAuthorize(t.signaturePayload)&&o.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),ke.shouldBuildUnpublishedRecipientFilter(s,t.author)&&o.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let a=this.convertDateSort(n);return this.deps.messageStore.query(e,o,a,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,s=r.buildPublishedRecordsFilter(t),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var Hd,T6=G(()=>{"use strict";g();Mc();rp();vr();Tc();ni();Td();He();Yo();xt();lr();Hd=class r extends Mn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ut.PublishedAscending||e.descriptor.dateSort===Ut.PublishedDescending))throw new ne(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 ke.validateDelegatedGrantReferentialIntegrity(e,t),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:s,dateSort:o}=e,a=At.getCurrentTimestamp();if(e.filter.published===!1&&(o===Ut.PublishedAscending||o===Ut.PublishedDescending))throw new ne(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${o}`);let d={interface:xe.Records,method:me.Read,filter:ke.normalizeFilter(t),messageTimestamp:e.messageTimestamp??a,permissionGrantId:i,dateSort:o};Mt(d);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:d,signer:n,permissionGrantId:i,protocolRole:s,delegatedGrant:e.delegatedGrant}));let c={descriptor:d,authorization:l};return ye.validateJsonSchema(c),new r(c)}async authorizeDelegate(e,t){let n=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var x2,jz=G(()=>{"use strict";g();ra();ef();Cn();vr();na();ia();Mp();ni();Td();T6();Zo();xt();lr();x2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Hd.parse(t)}catch(u){return gt(u,400)}try{n.author!==void 0&&await bn(t.authorization,this.deps.didResolver)}catch(u){return gt(u,401)}let i={interface:xe.Records,isLatestBaseState:!0,...ke.convertFilter(t.descriptor.filter)},s=ke.convertDateSort(t.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[i],s,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let a=o[0];if(a.descriptor.method===me.Delete){let u=a,f=u.descriptor.recordId,h=await _t.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return gt(new ne(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let p;try{p=await _t.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await _t.parse(p);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return gt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:h}}}let d=a;try{let u=await _t.parse(d);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return gt(u,401)}let l;if(d.encodedData===void 0){let u=await this.deps.dataStore.get(e,d.recordId,d.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:d}};l=u.dataStream}else{let u=Ie.base64UrlToBytes(d.encodedData);l=Et.fromBytes(u),delete d.encodedData}let c={status:{code:200,detail:"OK"},entry:{recordsWrite:d,data:l}};if(!await _t.isInitialWrite(d)){let f=(await this.deps.messageStore.query(e,[{recordId:d.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,c.entry.initialWrite=f}return c}static async authorizeRecordsRead(e,t,n,i,s){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 a=await Qe.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Fn.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:a,messageStore:i})}else await Do.authorizeRead(e,t,n,i,s)}}}});var za,P2=G(()=>{"use strict";g();Mc();vr();Tc();ni();Td();He();Yo();xt();lr();Ia();za=class r extends Mn{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&mi(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Sd(e.descriptor.filter.schema),At.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:xe.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??At.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Mt(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let s={descriptor:t,authorization:i};return ye.validateJsonSchema(s),new r(s)}async authorizeDelegate(e){let t=Ht.parse(this.message.authorization.authorDelegatedGrant);await Fn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var _2,Nz=G(()=>{"use strict";g();ra();rp();vr();na();Mp();ni();P2();Zo();Ed();xt();lr();_2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return gt(new ne(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await za.parse(t)}catch(f){return gt(f,400)}let s=[],o=[];if(ke.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)s=[r.buildPublishedEventFilter(i)],o=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await bn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return gt(f,401)}i.author===e?(s=r.buildOwnerEventFilters(i),o=r.buildOwnerQueryFilters(i)):(s=r.buildNonOwnerEventFilters(i),o=r.buildNonOwnerQueryFilters(i))}let a=await ye.getCid(t),{cursor:d}=i.message.descriptor;if(d!==void 0)try{let f=await this.deps.eventLog.subscribe(e,a,n,{cursor:d,filters:s});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code===re.EventLogProgressGap){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h===void 0?void 0:{code:"ProgressGap",...h}}}return gt(f,500)}let l=await this.deps.eventLog.subscribe(e,a,n,{filters:s}),c,u;try{let{dateSort:f,pagination:h}=i.message.descriptor,p=r.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);c=m.messages,u=m.cursor;for(let y of c)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(),gt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:c,cursor:u}}static convertDateSort(e){switch(e){case Ut.CreatedAscending:return{dateCreated:It.Ascending};case Ut.CreatedDescending:return{dateCreated:It.Descending};case Ut.PublishedAscending:return{datePublished:It.Ascending};case Ut.PublishedDescending:return{datePublished:It.Descending};case Ut.UpdatedAscending:return{messageTimestamp:It.Ascending};case Ut.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...ke.convertFilter(t),interface:xe.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...ke.convertFilter(n),author:e.author,interface:xe.Records,method:[me.Write,me.Delete],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...ke.convertFilter(n),interface:xe.Records,method:[me.Write,me.Delete],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...ke.convertFilter(n),interface:xe.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:xe.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return ke.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(i)&&(ke.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...ke.convertFilter(i,n),author:e.author,interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...ke.convertFilter(i,n),interface:xe.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,t),interface:xe.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),ke.shouldProtocolAuthorize(t.signaturePayload)&&await Do.authorizeQueryOrSubscribe(e,t,n,i)}}});var Ag,D6=G(()=>{"use strict";g();ug();$c();vr();ni();hb();Zo();lr();Ag=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:xe.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),s=await ye.getNewestMessage(i);if(!ke.canPerformDeleteAgainstRecord(t,s))return;let o=await qa.parse(t),a=await _t.getInitialWrite(i),d=o.constructIndexes(a),l=await ye.getCid(t);await this.messageStore.put(e,t,d),await this.stateIndex.insert(e,l,d),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:a},d,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:s}=t.descriptor,o={interface:xe.Records,protocol:n,protocolPath:i},a=ke.getParentContextFromOfContextId(t.contextId);if(a!==void 0&&a!==""){let c=tr.constructPrefixFilterAsRangeFilter(a);o.contextId=c}let{messages:d}=await this.messageStore.query(e,[o]),l=new Map;for(let c of d){let u;ke.isRecordsWrite(c)?u=c.recordId:u=c.descriptor.recordId;let f=l.get(u);f===void 0?l.set(u,[c]):f.push(c)}for(let[c,u]of l){if(c===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<s&&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 s=n;s.descriptor.dataSize<=bs.maxDataSizeAllowedToBeEncoded||s.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,s.recordId,s.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,s){let o={interface:xe.Records,parentId:t},{messages:a}=await n.query(e,[o]),d=new Map;for(let l of a){let c;ke.isRecordsWrite(l)?c=l.recordId:c=l.descriptor.recordId;let u=d.get(c);u?u.push(l):d.set(c,[l])}for(let l of d.keys())await r.purgeRecordDescendants(e,l,n,i,s);for(let l of d.keys())await r.purgeRecordMessages(e,d.get(l),n,i,s)}static async purgeRecordMessages(e,t,n,i,s){let o=t.filter(l=>l.descriptor.method===me.Write),a=await ye.getNewestMessage(o);await i.delete(e,a.recordId,a.descriptor.dataCid);let d=await Promise.all(t.map(l=>ye.getCid(l)));await s.delete(e,d),await Promise.all(d.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,s,o){let a=[];for(let d of t){if(await ye.isOlder(d,n)){await r.deleteFromDataStoreIfNeeded(s,e,d,n);let c=await ye.getCid(d);if(await i.delete(e,c),await _t.isInitialWrite(d)){let p=await(await _t.parse(d)).constructIndexes(!1),m=d;delete m.encodedData,await i.put(e,m,p)}else{let f=await ye.getCid(d);a.push(f)}}await o.delete(e,a)}}}});var E2,Mz=G(()=>{"use strict";g();ra();Nl();ef();ug();Cn();$c();vr();na();ia();Mp();ni();Td();Zo();w2();Ed();D6();xt();lr();E2=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 Do.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return gt(p,400)}try{await bn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(p){return gt(p,401)}let s={interface:xe.Records,recordId:t.recordId},{messages:o}=await this.deps.messageStore.query(e,[s]),a=await i.isInitialWrite(),d;if(!a)try{d=await _t.getInitialWrite(o),_t.verifyEqualityOfImmutableProperties(d,t)}catch(p){return gt(p,400)}try{await this.enforceSquashBackstop(e,t)}catch(p){return gt(p,409)}let l=await ye.getNewestMessage(o),c=!1,u;if(l===void 0||await ye.isNewer(t,l)?(c=!0,u=t):u=l,!c){let p=!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;p=!y&&!v}if(!p)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);try{if(l?.descriptor.method===me.Delete)throw new ne(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let p=!1,m=t;if(n===void 0){if(!a){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),p=!0}}else m=await this.processMessageWithDataStream(e,t,n),p=!0;let y=await i.constructIndexes(p);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&&p&&await this.deps.eventLog.emit(e,{message:m,initialWrite:d},y,v)}catch(p){if(p instanceof ne&&(p.code===re.RecordsWriteMissingEncodedDataInPrevious||p.code===re.RecordsWriteMissingDataInPrevious||p.code===re.RecordsWriteNotAllowedAfterDelete||p.code===re.RecordsWriteDataCidMismatch||p.code===re.RecordsWriteDataSizeMismatch||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return gt(p,400);throw p}let h={status:a&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Ag.deleteAllOlderMessagesButKeepInitialWrite(e,o,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:zf.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}),h}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=Ie.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=bs.maxDataSizeAllowedToBeEncoded){let s=await Et.toBytes(n),o=await pr.computeDagPbCidFromBytes(s);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,s.length);let a=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);a?.validateRecord!==void 0&&a.validateRecord(t,s),i=await this.cloneAndAddEncodedData(t,s)}else{let[s,o]=Et.duplicateDataStream(n,2);try{let[a,d]=await Promise.all([pr.computeDagPbCidFromStream(s),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,o)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,a,d.dataSize)}catch(a){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),a}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:s,dataSize:o}=t.descriptor;if(r.validateDataIntegrity(s,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=bs.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new ne(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");i.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ne(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 ne(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ne(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 Do.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(c){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,c);return}let i=t.descriptor.protocolPath.split("/"),s=n.structure[i[0]];for(let c=1;c<i.length&&s!==void 0;c++)s=s[i[c]];if(s?.$squash!==!0)return;let o={interface:xe.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},a=ke.getParentContextFromOfContextId(t.contextId);if(a!==void 0&&a!==""){let c=tr.constructPrefixFilterAsRangeFilter(a);o.contextId=c}let{messages:d}=await this.deps.messageStore.query(e,[o],{messageTimestamp:It.Descending},{limit:1});if(d.length===0)return;let l=d[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ne(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 ne(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 Qe.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Fn.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await Do.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function Sfe(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 s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,d=r.charAt(0),l=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,v=0,w=p.length;v!==w&&p[v]===0;)v++,m++;for(var b=(w-v)*c+1>>>0,T=new Uint8Array(b);v!==w;){for(var D=p[v],I=0,M=b-1;(D!==0||I<y)&&M!==-1;M--,I++)D+=256*T[M]>>>0,T[M]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");y=I,v++}for(var C=b-y;C!==b&&T[C]===0;)C++;for(var z=d.repeat(m);C<b;++C)z+=r.charAt(T[C]);return z}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,v=0;p[m]===d;)y++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var T=t[p.charCodeAt(m)];if(T===255)return;for(var D=0,I=w-1;(T!==0||D<v)&&I!==-1;I--,D++)T+=a*b[I]>>>0,b[I]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");v=D,m++}if(p[m]!==" "){for(var M=w-v;M!==w&&b[M]===0;)M++;for(var C=new Uint8Array(y+(w-M)),z=y;M!==w;)C[z++]=b[M++];return C}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}function jfe(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Nfe(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function M6(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function vF(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zfe;)e[t++]=r&255|qz,r/=128;for(;r&qfe;)e[t++]=r&255|qz,r>>>=7;return e[t]=r|0,vF.bytes=t-n+1,e}function U6(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw U6.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&zz)<<i:(o&zz)*Math.pow(2,i),i+=7}while(o>=Gfe);return U6.bytes=s-n,t}function bF(r){Object.keys(r).forEach(e=>{let t=r[e];t===void 0?delete r[e]:t!==null&&typeof t=="object"&&bF(t)})}function phe(r){let e=r.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t=e.indexOf("%");if(t!==-1&&(e=e.slice(0,t)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=PF(e);return n!==void 0?_F(n):e.includes(":")?whe(e):!1}function Hz(r,e="URL",t){var n;let i=typeof r=="string"?new URL(r):new URL(r.toString()),s=(n=t?.allowedProtocols)!==null&&n!==void 0?n:mhe;if(!s.includes(i.protocol))throw new O2(`${e} must use one of the allowed schemes (${s.join(", ")}): ${i.protocol}`);if(i.hostname==="")throw new O2(`${e} must specify a hostname.`);if(phe(i.hostname))throw new O2(`${e} must not target a private, loopback, or link-local host: ${i.hostname}`);return i}function xF(r,e,t){return hhe(this,void 0,void 0,function*(){var n,i;let s=(n=t?.description)!==null&&n!==void 0?n:"URL",o=(i=t?.maxRedirects)!==null&&i!==void 0?i:yhe,a=Hz(r,s,{allowedProtocols:t?.allowedProtocols}).href;for(let d=0;d<=o;d++){let l=yield fetch(a,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!ghe.has(l.status))return l;let c=l.headers.get("location");if(c===null)return l;a=Hz(new URL(c,a),s,{allowedProtocols:t?.allowedProtocols}).href}throw new Error(`${s} exceeded the maximum number of redirects (${o}).`)})}function PF(r){let e=r.split(".");if(e.length!==4)return;let t=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(t.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return t}function _F([r,e]){return r===0||r===10||r===100&&e>=64&&e<=127||r===127||r===169&&e===254||r===172&&e>=16&&e<=31||r===192&&e===168||r>=224}function whe(r){let e=vhe(r);if(e===void 0)return!1;let[t,n,i,s,o,a,d,l]=e,c=t===0&&n===0&&i===0&&s===0&&o===0&&a===0;return e.every(u=>u===0)||c&&d===0&&l===1||(t&65024)===64512||(t&65472)===65152||(t&65280)===65280?!0:t===100&&n===65435&&i===0&&s===0&&o===0&&a===0||t===0&&n===0&&i===0&&s===0&&o===0&&a===65535?_F(xhe(d,l)):!!c}function vhe(r){let[e,t,n]=r.split("::");if(n!==void 0)return;let i=e===""?[]:e.split(":"),s=t===void 0||t===""?[]:t.split(":"),o=bhe([...i,...s]);if(o===void 0||o.length>8||t===void 0&&o.length!==8||t!==void 0&&o.length>=8)return;let a=o.map(l=>/^[0-9a-f]{1,4}$/.test(l)?Number.parseInt(l,16):Number.NaN);if(!a.every(l=>Number.isInteger(l)&&l>=0&&l<=65535))return;if(t===void 0)return a;let d=new Array(8-a.length).fill(0);return[...a.slice(0,i.length),...d,...a.slice(i.length)]}function bhe(r){let e=r.at(-1);if(!e?.includes("."))return r;let t=PF(e);if(t===void 0)return;let[n,i,s,o]=t;return[...r.slice(0,-1),((n<<8|i)&65535).toString(16),((s<<8|o)&65535).toString(16)]}function xhe(r,e){return[r>>8&255,r&255,e>>8&255,e&255]}function rl(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Yp(r){if(!rl(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=_he[r[t]];return e}function TF(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function l5(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function Vz(r){if(r>=cu._0&&r<=cu._9)return r-cu._0;if(r>=cu._A&&r<=cu._F)return r-(cu._A-10);if(r>=cu._a&&r<=cu._f)return r-(cu._a-10)}function qg(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,s=0;i<t;i++,s+=2){let o=Vz(r.charCodeAt(s)),a=Vz(r.charCodeAt(s+1));if(o===void 0||a===void 0){let d=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+d+'" at index '+s)}n[i]=o*16+a}return n}function Hp(r){return l5(Yp(r))}function oh(r){if(!rl(r))throw new Error("Uint8Array expected");return l5(Yp(Uint8Array.from(r).reverse()))}function nl(r,e){return qg(r.toString(16).padStart(e*2,"0"))}function zg(r,e){return nl(r,e).reverse()}function Ehe(r){return qg(TF(r))}function Zn(r,e,t){let n;if(typeof e=="string")try{n=qg(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(rl(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 Zp(...r){let e=0;for(let i=0;i<r.length;i++){let s=r[i];if(!rl(s))throw new Error("Uint8Array expected");e+=s.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let s=r[i];t.set(s,n),n+=s.length}return t}function She(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 The(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Dhe(r){let e;for(e=0;r>SF;r>>=mE,e+=1);return e}function khe(r,e){return r>>BigInt(e)&mE}function DF(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=k6(r),i=k6(r),s=0,o=()=>{n.fill(1),i.fill(0),s=0},a=(...c)=>t(i,n,...c),d=(c=k6())=>{i=a(Jz([0]),c),n=a(),c.length!==0&&(i=a(Jz([1]),c),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let c=0,u=[];for(;c<e;){n=a();let f=n.slice();u.push(f),c+=n.length}return Zp(...u)};return(c,u)=>{o(),d(c);let f;for(;!(f=u(l()));)d();return o(),f}}function em(r,e,t={}){let n=(i,s,o)=>{let a=Ihe[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let d=r[i];if(!(o&&d===void 0)&&!a(d,r))throw new Error(`Invalid param ${String(i)}=${d} (${typeof d}), expected ${s}`)};for(let[i,s]of Object.entries(e))n(i,s,!1);for(let[i,s]of Object.entries(t))n(i,s,!0);return r}function Yz(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function Rhe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function kF(r,...e){if(!Rhe(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 Che(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yz(r.outputLen),Yz(r.blockLen)}function rE(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 $he(r,e){kF(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function AF(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function IF(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function f5(r){if(typeof r=="string"&&(r=IF(r)),!AF(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function RF(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!AF(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 s=r[n];t.set(s,i),i+=s.length}return t}function $F(r){let e=n=>r().update(f5(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function h5(r=32){if(A6&&typeof A6.getRandomValues=="function")return A6.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Bhe(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),d=n?4:0,l=n?0:4;r.setUint32(e+d,o,n),r.setUint32(e+l,a,n)}function en(r,e){let t=r%e;return t>=xi?t:e+t}function jF(r,e,t){if(t<=xi||e<xi)throw new Error("Expected power/modulo > 0");if(t===xn)return xi;let n=xn;for(;e>xi;)e&xn&&(n=n*r%t),r=r*r%t,e>>=xn;return n}function Dn(r,e,t){let n=r;for(;e-- >xi;)n*=n,n%=t;return n}function q6(r,e){if(r===xi||e<=xi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=en(r,e),n=e,i=xi,s=xn,o=xn,a=xi;for(;t!==xi;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}if(n!==xn)throw new Error("invert: does not exist");return en(i,e)}function qhe(r){let e=(r-xn)/qp,t,n,i;for(t=r-xn,n=0;t%qp===xi;t/=qp,n++);for(i=qp;i<r&&jF(i,e,r)!==r-xn;i++);if(n===1){let o=(r+xn)/L6;return function(a,d){let l=a.pow(d,o);if(!a.eql(a.sqr(l),d))throw new Error("Cannot find square root");return l}}let s=(t+xn)/qp;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let d=n,l=o.pow(o.mul(o.ONE,i),t),c=o.pow(a,s),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(u);f<d&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(l,xn<<BigInt(d-f-1));l=o.sqr(h),c=o.mul(c,h),u=o.mul(u,l),d=f}return c}}function zhe(r){if(r%L6===Khe){let e=(r+xn)/L6;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%Qz===Zz){let e=(r-Zz)/Qz;return function(t,n){let i=t.mul(n,qp),s=t.pow(i,e),o=t.mul(n,s),a=t.mul(t.mul(o,qp),s),d=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(d),n))throw new Error("Cannot find square root");return d}}return r%Lhe,qhe(r)}function Whe(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Ghe.reduce((n,i)=>(n[i]="function",n),e);return em(r,t)}function Hhe(r,e,t){if(t<xi)throw new Error("Expected power > 0");if(t===xi)return r.ONE;if(t===xn)return e;let n=r.ONE,i=e;for(;t>xi;)t&xn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=xn;return n}function Vhe(r,e){let t=new Array(e.length),n=e.reduce((s,o,a)=>r.is0(o)?s:(t[a]=s,r.mul(s,o)),r.ONE),i=r.inv(n);return e.reduceRight((s,o,a)=>r.is0(o)?s:(t[a]=r.mul(s,t[a]),r.mul(s,o)),i),t}function NF(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function p5(r,e,t=!1,n={}){if(r<=xi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:s}=NF(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=zhe(r),a=Object.freeze({ORDER:r,BITS:i,BYTES:s,MASK:u5(i),ZERO:xi,ONE:xn,create:d=>en(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof d}`);return xi<=d&&d<r},is0:d=>d===xi,isOdd:d=>(d&xn)===xn,neg:d=>en(-d,r),eql:(d,l)=>d===l,sqr:d=>en(d*d,r),add:(d,l)=>en(d+l,r),sub:(d,l)=>en(d-l,r),mul:(d,l)=>en(d*l,r),pow:(d,l)=>Hhe(a,d,l),div:(d,l)=>en(d*q6(l,r),r),sqrN:d=>d*d,addN:(d,l)=>d+l,subN:(d,l)=>d-l,mulN:(d,l)=>d*l,inv:d=>q6(d,r),sqrt:n.sqrt||(d=>o(a,d)),invertBatch:d=>Vhe(a,d),cmov:(d,l,c)=>c?l:d,toBytes:d=>t?zg(d,s):nl(d,s),fromBytes:d=>{if(d.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${d.length}`);return t?oh(d):Hp(d)}});return Object.freeze(a)}function Jhe(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 MF(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 UF(r){let e=MF(r);return e+Math.ceil(e/2)}function Yhe(r,e,t=!1){let n=r.length,i=MF(e),s=UF(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let o=t?Hp(r):oh(r),a=en(o,e-xn)+xn;return t?zg(a,i):nl(a,i)}function KF(r,e){let t=(i,s)=>{let o=s.negate();return i?o:s},n=i=>{let s=Math.ceil(e/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:t,unsafeLadder(i,s){let o=r.ZERO,a=i;for(;s>Zhe;)s&R6&&(o=o.add(a)),a=a.double(),s>>=R6;return o},precomputeWindow(i,s){let{windows:o,windowSize:a}=n(s),d=[],l=i,c=l;for(let u=0;u<o;u++){c=l,d.push(c);for(let f=1;f<a;f++)c=c.add(l),d.push(c);l=c.double()}return d},wNAF(i,s,o){let{windows:a,windowSize:d}=n(i),l=r.ZERO,c=r.BASE,u=BigInt(2**i-1),f=2**i,h=BigInt(i);for(let p=0;p<a;p++){let m=p*d,y=Number(o&u);o>>=h,y>d&&(y-=f,o+=R6);let v=m,w=m+Math.abs(y)-1,b=p%2!==0,T=y<0;y===0?c=c.add(t(b,s[v])):l=l.add(t(T,s[w]))}return{p:l,f:c}},wNAFCached(i,s,o,a){let d=i._WINDOW_SIZE||1,l=s.get(i);return l||(l=this.precomputeWindow(i,d),d!==1&&s.set(i,a(l))),this.wNAF(d,l,o)}}}function m5(r){return Whe(r.Fp),em(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...NF(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function Qhe(r){let e=m5(r);em(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 tpe(r){let e=Qhe(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let v=m.toAffine();return Zp(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(p=>{let m=p.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 s(p){let{a:m,b:y}=e,v=t.sqr(p),w=t.mul(v,p);return t.add(t.add(w,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function o(p){return typeof p=="bigint"&&pu<p&&p<e.n}function a(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function d(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof p!="bigint"){if(rl(p)&&(p=Yp(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let b;try{b=typeof p=="bigint"?p:Hp(Zn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return v&&(b=en(b,w)),a(b),b}let l=new Map;function c(p){if(!(p 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=b=>t.eql(b,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(Zn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(d(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=s(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){c(m);let{px:y,py:v,pz:w}=this,{px:b,py:T,pz:D}=m,I=t.eql(t.mul(y,D),t.mul(b,w)),M=t.eql(t.mul(v,D),t.mul(T,w));return I&&M}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,Xz),{px:w,py:b,pz:T}=this,D=t.ZERO,I=t.ZERO,M=t.ZERO,C=t.mul(w,w),z=t.mul(b,b),L=t.mul(T,T),B=t.mul(w,b);return B=t.add(B,B),M=t.mul(w,T),M=t.add(M,M),D=t.mul(m,M),I=t.mul(v,L),I=t.add(D,I),D=t.sub(z,I),I=t.add(z,I),I=t.mul(D,I),D=t.mul(B,D),M=t.mul(v,M),L=t.mul(m,L),B=t.sub(C,L),B=t.mul(m,B),B=t.add(B,M),M=t.add(C,C),C=t.add(M,C),C=t.add(C,L),C=t.mul(C,B),I=t.add(I,C),L=t.mul(b,T),L=t.add(L,L),C=t.mul(L,B),D=t.sub(D,C),M=t.mul(L,z),M=t.add(M,M),M=t.add(M,M),new u(D,I,M)}add(m){c(m);let{px:y,py:v,pz:w}=this,{px:b,py:T,pz:D}=m,I=t.ZERO,M=t.ZERO,C=t.ZERO,z=e.a,L=t.mul(e.b,Xz),B=t.mul(y,b),H=t.mul(v,T),ee=t.mul(w,D),R=t.add(y,v),$=t.add(b,T);R=t.mul(R,$),$=t.add(B,H),R=t.sub(R,$),$=t.add(y,w);let E=t.add(b,D);return $=t.mul($,E),E=t.add(B,ee),$=t.sub($,E),E=t.add(v,w),I=t.add(T,D),E=t.mul(E,I),I=t.add(H,ee),E=t.sub(E,I),C=t.mul(z,$),I=t.mul(L,ee),C=t.add(I,C),I=t.sub(H,C),C=t.add(H,C),M=t.mul(I,C),H=t.add(B,B),H=t.add(H,B),ee=t.mul(z,ee),$=t.mul(L,$),H=t.add(H,ee),ee=t.sub(B,ee),ee=t.mul(z,ee),$=t.add($,ee),B=t.mul(H,$),M=t.add(M,B),B=t.mul(E,$),I=t.mul(R,I),I=t.sub(I,B),B=t.mul(R,H),C=t.mul(E,C),C=t.add(C,B),new u(I,M,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return h.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,b)=>w.toAffine(v[b])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===pu)return y;if(a(m),m===Ja)return this;let{endo:v}=e;if(!v)return h.unsafeLadder(this,m);let{k1neg:w,k1:b,k2neg:T,k2:D}=v.splitScalar(m),I=y,M=y,C=this;for(;b>pu||D>pu;)b&Ja&&(I=I.add(C)),D&Ja&&(M=M.add(C)),C=C.double(),b>>=Ja,D>>=Ja;return w&&(I=I.negate()),T&&(M=M.negate()),M=new u(t.mul(M.px,v.beta),M.py,M.pz),I.add(M)}multiply(m){a(m);let y=m,v,w,{endo:b}=e;if(b){let{k1neg:T,k1:D,k2neg:I,k2:M}=b.splitScalar(y),{p:C,f:z}=this.wNAF(D),{p:L,f:B}=this.wNAF(M);C=h.constTimeNegate(T,C),L=h.constTimeNegate(I,L),L=new u(t.mul(L.px,b.beta),L.py,L.pz),v=C.add(L),w=z.add(B)}else{let{p:T,f:D}=this.wNAF(y);v=T,w=D}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,b=(D,I)=>I===pu||I===Ja||!D.equals(w)?D.multiplyUnsafe(I):D.multiply(I),T=b(this,y).add(b(m,v));return T.is0()?void 0:T}toAffine(m){let{px:y,py:v,pz:w}=this,b=this.is0();m==null&&(m=b?t.ONE:t.inv(w));let T=t.mul(y,m),D=t.mul(v,m),I=t.mul(w,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:T,y:D}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Ja)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===Ja?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return Yp(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,h=KF(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:o}}function rpe(r){let e=m5(r);return em(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function npe(r){let e=rpe(r),{Fp:t,n}=e,i=t.BYTES+1,s=2*t.BYTES+1;function o($){return pu<$&&$<t.ORDER}function a($){return en($,n)}function d($){return q6($,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:u,isWithinCurveOrder:f}=tpe({...e,toBytes($,E,P){let _=E.toAffine(),S=t.toBytes(_.x),A=Zp;return P?A(Uint8Array.from([E.hasEvenY()?2:3]),S):A(Uint8Array.from([4]),S,t.toBytes(_.y))},fromBytes($){let E=$.length,P=$[0],_=$.subarray(1);if(E===i&&(P===2||P===3)){let S=Hp(_);if(!o(S))throw new Error("Point is not on curve");let A=u(S),N=t.sqrt(A),q=(N&Ja)===Ja;return(P&1)===1!==q&&(N=t.neg(N)),{x:S,y:N}}else if(E===s&&P===4){let S=t.fromBytes(_.subarray(0,t.BYTES)),A=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:S,y:A}}else throw new Error(`Point of length ${E} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),h=$=>Yp(nl($,e.nByteLength));function p($){let E=n>>Ja;return $>E}function m($){return p($)?a(-$):$}let y=($,E,P)=>Hp($.slice(E,P));class v{constructor(E,P,_){this.r=E,this.s=P,this.recovery=_,this.assertValidity()}static fromCompact(E){let P=e.nByteLength;return E=Zn("compactSignature",E,P*2),new v(y(E,0,P),y(E,P,2*P))}static fromDER(E){let{r:P,s:_}=Gp.toSig(Zn("DER",E));return new v(P,_)}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(E){return new v(this.r,this.s,E)}recoverPublicKey(E){let{r:P,s:_,recovery:S}=this,A=M(Zn("msgHash",E));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let N=S===2||S===3?P+e.n:P;if(N>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=S&1?"03":"02",W=l.fromHex(q+h(N)),J=d(N),V=a(-A*J),Y=a(_*J),F=l.BASE.multiplyAndAddUnsafe(W,V,Y);if(!F)throw new Error("point at infinify");return F.assertValidity(),F}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return qg(this.toDERHex())}toDERHex(){return Gp.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qg(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey($){try{return c($),!0}catch{return!1}},normPrivateKeyToScalar:c,randomPrivateKey:()=>{let $=UF(e.n);return Yhe(e.randomBytes($),e.n)},precompute($=8,E=l.BASE){return E._setWindowSize($),E.multiply(BigInt(3)),E}};function b($,E=!0){return l.fromPrivateKey($).toRawBytes(E)}function T($){let E=rl($),P=typeof $=="string",_=(E||P)&&$.length;return E?_===i||_===s:P?_===2*i||_===2*s:$ instanceof l}function D($,E,P=!0){if(T($))throw new Error("first arg must be private key");if(!T(E))throw new Error("second arg must be public key");return l.fromHex(E).multiply(c($)).toRawBytes(P)}let I=e.bits2int||function($){let E=Hp($),P=$.length*8-e.nBitLength;return P>0?E>>BigInt(P):E},M=e.bits2int_modN||function($){return a(I($))},C=u5(e.nBitLength);function z($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(pu<=$&&$<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return nl($,e.nByteLength)}function L($,E,P=B){if(["recovered","canonical"].some(ie=>ie in P))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:S}=e,{lowS:A,prehash:N,extraEntropy:q}=P;A==null&&(A=!0),$=Zn("msgHash",$),N&&($=Zn("prehashed msgHash",_($)));let W=M($),J=c(E),V=[z(J),z(W)];if(q!=null){let ie=q===!0?S(t.BYTES):q;V.push(Zn("extraEntropy",ie))}let Y=Zp(...V),F=W;function Q(ie){let oe=I(ie);if(!f(oe))return;let Z=d(oe),le=l.BASE.multiply(oe).toAffine(),he=a(le.x);if(he===pu)return;let ue=a(Z*a(F+he*J));if(ue===pu)return;let Se=(le.x===he?0:2)|Number(le.y&Ja),pe=ue;return A&&p(ue)&&(pe=m(ue),Se^=1),new v(he,pe,Se)}return{seed:Y,k2sig:Q}}let B={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function ee($,E,P=B){let{seed:_,k2sig:S}=L($,E,P),A=e;return DF(A.hash.outputLen,A.nByteLength,A.hmac)(_,S)}l.BASE._setWindowSize(8);function R($,E,P,_=H){let S=$;if(E=Zn("msgHash",E),P=Zn("publicKey",P),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:N}=_,q,W;try{if(typeof S=="string"||rl(S))try{q=v.fromDER(S)}catch(Z){if(!(Z instanceof Gp.Err))throw Z;q=v.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:Z,s:le}=S;q=new v(Z,le)}else throw new Error("PARSE");W=l.fromHex(P)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(A&&q.hasHighS())return!1;N&&(E=e.hash(E));let{r:J,s:V}=q,Y=M(E),F=d(V),Q=a(Y*F),ie=a(J*F),oe=l.BASE.multiplyAndAddUnsafe(W,Q,ie)?.toAffine();return oe?a(oe.x)===J:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:D,sign:ee,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function ipe(r){return{hash:r,hmac:(e,...t)=>qF(r,e,RF(...t)),randomBytes:h5}}function zF(r,e){let t=n=>npe({...r,...ipe(n)});return Object.freeze({...t(e),create:t})}function spe(r){let e=FF,t=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),d=BigInt(88),l=r*r*r%e,c=l*l*r%e,u=Dn(c,t,e)*c%e,f=Dn(u,t,e)*c%e,h=Dn(f,z6,e)*l%e,p=Dn(h,i,e)*h%e,m=Dn(p,s,e)*p%e,y=Dn(m,a,e)*m%e,v=Dn(y,d,e)*y%e,w=Dn(v,a,e)*m%e,b=Dn(w,t,e)*c%e,T=Dn(b,o,e)*p%e,D=Dn(T,n,e)*l%e,I=Dn(D,z6,e);if(!F6.eql(F6.sqr(I),r))throw new Error("Cannot find square root");return I}function ape(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function GF(r,...e){if(!ape(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 r7(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 cpe(r,e){GF(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function dpe(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function WF(r){return typeof r=="string"&&(r=dpe(r)),GF(r),r}function upe(r){let e=n=>r().update(WF(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function fpe(r=32){if(B2&&typeof B2.getRandomValues=="function")return B2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function hpe(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),d=n?4:0,l=n?0:4;r.setUint32(e+d,o,n),r.setUint32(e+l,a,n)}function vpe(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort((o,a)=>o.localeCompare(a)),s={};for(let o of i)s[o]=e(n[o]);return s}return n},t=e(r);return JSON.stringify(t)}function Tr(r){return xpe(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}`);bF(n);let i=vpe(n),s=ot.string(i).toUint8Array(),o=yield HF.digest({data:s});return ot.uint8Array(o).toBase64Url()})}function Vp(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 y5(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 gu(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 g5(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 Ppe(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 JF(r,e=!1){return e?{h:Number(r&T2),l:Number(r>>G6&T2)}:{h:Number(r>>G6&T2)|0,l:Number(r&T2)|0}}function kpe(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:s,l:o}=JF(r[i],e);[t[i],n[i]]=[s,o]}return[t,n]}function qpe(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function tme(r){let e=m5(r);return em(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function w5(r){let e=tme(r),{Fp:t,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:d}=e,l=D2<<BigInt(a*8)-oa,c=t.create,u=e.uvRatio||((P,_)=>{try{return{isValid:!0,value:t.sqrt(P*t.inv(_))}}catch{return{isValid:!1,value:zc}}}),f=e.adjustScalarBytes||(P=>P),h=e.domain||((P,_,S)=>{if(_.length||S)throw new Error("Contexts/pre-hash are not supported");return P}),p=P=>typeof P=="bigint"&&zc<P,m=(P,_)=>p(P)&&p(_)&&P<_,y=P=>P===zc||m(P,l);function v(P,_){if(m(P,_))return P;throw new Error(`Expected valid scalar < ${_}, got ${typeof P} ${P}`)}function w(P){return P===zc?P:v(P,n)}let b=new Map;function T(P){if(!(P instanceof D))throw new Error("ExtendedPoint expected")}class D{constructor(_,S,A,N){if(this.ex=_,this.ey=S,this.ez=A,this.et=N,!y(_))throw new Error("x required");if(!y(S))throw new Error("y required");if(!y(A))throw new Error("z required");if(!y(N))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof D)throw new Error("extended point not allowed");let{x:S,y:A}=_||{};if(!y(S)||!y(A))throw new Error("invalid affine point");return new D(S,A,oa,c(S*A))}static normalizeZ(_){let S=t.invertBatch(_.map(A=>A.ez));return _.map((A,N)=>A.toAffine(S[N])).map(D.fromAffine)}_setWindowSize(_){this._WINDOW_SIZE=_,b.delete(this)}assertValidity(){let{a:_,d:S}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:N,ez:q,et:W}=this,J=c(A*A),V=c(N*N),Y=c(q*q),F=c(Y*Y),Q=c(J*_),ie=c(Y*c(Q+V)),oe=c(F+c(S*c(J*V)));if(ie!==oe)throw new Error("bad point: equation left != right (1)");let Z=c(A*N),le=c(q*W);if(Z!==le)throw new Error("bad point: equation left != right (2)")}equals(_){T(_);let{ex:S,ey:A,ez:N}=this,{ex:q,ey:W,ez:J}=_,V=c(S*J),Y=c(q*N),F=c(A*J),Q=c(W*N);return V===Y&&F===Q}is0(){return this.equals(D.ZERO)}negate(){return new D(c(-this.ex),this.ey,this.ez,c(-this.et))}double(){let{a:_}=e,{ex:S,ey:A,ez:N}=this,q=c(S*S),W=c(A*A),J=c(D2*c(N*N)),V=c(_*q),Y=S+A,F=c(c(Y*Y)-q-W),Q=V+W,ie=Q-J,oe=V-W,Z=c(F*ie),le=c(Q*oe),he=c(F*oe),ue=c(ie*Q);return new D(Z,le,ue,he)}add(_){T(_);let{a:S,d:A}=e,{ex:N,ey:q,ez:W,et:J}=this,{ex:V,ey:Y,ez:F,et:Q}=_;if(S===BigInt(-1)){let ds=c((q-N)*(Y+V)),Ye=c((q+N)*(Y-V)),ar=c(Ye-ds);if(ar===zc)return this.double();let qr=c(W*D2*Q),yr=c(J*D2*F),Gt=yr+qr,k=Ye+ds,U=yr-qr,K=c(Gt*ar),te=c(k*U),de=c(Gt*U),ge=c(ar*k);return new D(K,te,ge,de)}let ie=c(N*V),oe=c(q*Y),Z=c(J*A*Q),le=c(W*F),he=c((N+q)*(V+Y)-ie-oe),ue=le-Z,Se=le+Z,pe=c(oe-S*ie),Ae=c(he*ue),Ot=c(Se*pe),ai=c(he*pe),Lr=c(ue*Se);return new D(Ae,Ot,Lr,ai)}subtract(_){return this.add(_.negate())}wNAF(_){return C.wNAFCached(this,b,_,D.normalizeZ)}multiply(_){let{p:S,f:A}=this.wNAF(v(_,n));return D.normalizeZ([S,A])[0]}multiplyUnsafe(_){let S=w(_);return S===zc?M:this.equals(M)||S===oa?this:this.equals(I)?this.wNAF(S).p:C.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(_){let{ex:S,ey:A,ez:N}=this,q=this.is0();_==null&&(_=q?Xpe:t.inv(N));let W=c(S*_),J=c(A*_),V=c(N*_);if(q)return{x:zc,y:oa};if(V!==oa)throw new Error("invZ was invalid");return{x:W,y:J}}clearCofactor(){let{h:_}=e;return _===oa?this:this.multiplyUnsafe(_)}static fromHex(_,S=!1){let{d:A,a:N}=e,q=t.BYTES;_=Zn("pointHex",_,q);let W=_.slice(),J=_[q-1];W[q-1]=J&-129;let V=oh(W);V===zc||(S?v(V,l):v(V,t.ORDER));let Y=c(V*V),F=c(Y-oa),Q=c(A*Y-N),{isValid:ie,value:oe}=u(F,Q);if(!ie)throw new Error("Point.fromHex: invalid y coordinate");let Z=(oe&oa)===oa,le=(J&128)!==0;if(!S&&oe===zc&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==Z&&(oe=c(-oe)),D.fromAffine({x:oe,y:V})}static fromPrivateKey(_){return B(_).point}toRawBytes(){let{x:_,y:S}=this.toAffine(),A=zg(S,t.BYTES);return A[A.length-1]|=_&oa?128:0,A}toHex(){return Yp(this.toRawBytes())}}D.BASE=new D(e.Gx,e.Gy,oa,c(e.Gx*e.Gy)),D.ZERO=new D(zc,oa,oa,zc);let{BASE:I,ZERO:M}=D,C=KF(D,a*8);function z(P){return en(P,n)}function L(P){return z(oh(P))}function B(P){let _=a;P=Zn("private key",P,_);let S=Zn("hashed private key",s(P),2*_),A=f(S.slice(0,_)),N=S.slice(_,2*_),q=L(A),W=I.multiply(q),J=W.toRawBytes();return{head:A,prefix:N,scalar:q,point:W,pointBytes:J}}function H(P){return B(P).pointBytes}function ee(P=new Uint8Array,..._){let S=Zp(..._);return L(s(h(S,Zn("context",P),!!i)))}function R(P,_,S={}){P=Zn("message",P),i&&(P=i(P));let{prefix:A,scalar:N,pointBytes:q}=B(_),W=ee(S.context,A,P),J=I.multiply(W).toRawBytes(),V=ee(S.context,J,q,P),Y=z(W+V*N);w(Y);let F=Zp(J,zg(Y,t.BYTES));return Zn("result",F,a*2)}let $=eme;function E(P,_,S,A=$){let{context:N,zip215:q}=A,W=t.BYTES;P=Zn("signature",P,2*W),_=Zn("message",_),i&&(_=i(_));let J=oh(P.slice(W,2*W)),V,Y,F;try{V=D.fromHex(S,q),Y=D.fromHex(P.slice(0,W),q),F=I.multiplyUnsafe(J)}catch{return!1}if(!q&&V.isSmallOrder())return!1;let Q=ee(N,Y.toRawBytes(),V.toRawBytes(),_);return Y.add(V.multiplyUnsafe(Q)).subtract(F).clearCofactor().equals(D.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:E,ExtendedPoint:D,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(t.BYTES),precompute(P=8,_=D.BASE){return _._setWindowSize(P),_.multiply(BigInt(3)),_}}}}function rme(r){return em(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function nme(r){let e=rme(r),{P:t}=e,n=b=>en(b,t),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),d=e.powPminus2||(b=>jF(b,t-BigInt(2),t));function l(b,T,D){let I=n(b*(T-D));return T=n(T-I),D=n(D+I),[T,D]}function c(b){if(typeof b=="bigint"&&yb<=b&&b<t)return b;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(b,T){let D=c(b),I=c(T),M=D,C=$6,z=yb,L=D,B=$6,H=yb,ee;for(let $=BigInt(i-1);$>=yb;$--){let E=I>>$&$6;H^=E,ee=l(H,C,L),C=ee[0],L=ee[1],ee=l(H,z,B),z=ee[0],B=ee[1],H=E;let P=C+z,_=n(P*P),S=C-z,A=n(S*S),N=_-A,q=L+B,W=L-B,J=n(W*P),V=n(q*S),Y=J+V,F=J-V;L=n(Y*Y),B=n(M*n(F*F)),C=n(_*A),z=n(N*(_+n(u*N)))}ee=l(H,C,L),C=ee[0],L=ee[1],ee=l(H,z,B),z=ee[0],B=ee[1];let R=d(z);return n(C*R)}function h(b){return zg(n(b),s)}function p(b){let T=Zn("u coordinate",b,s);return o===32&&(T[31]&=127),oh(T)}function m(b){let T=Zn("scalar",b),D=T.length;if(D!==s&&D!==o)throw new Error(`Expected ${s} or ${o} bytes, got ${D}`);return oh(a(T))}function y(b,T){let D=p(T),I=m(b),M=f(D,I);if(M===yb)throw new Error("Invalid private or public key received");return h(M)}let v=h(e.Gu);function w(b){return y(b,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(b,T)=>y(b,T),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function ZF(r){let e=Lb,t=r*r%e*r%e,n=Dn(t,W6,e)*t%e,i=Dn(n,ime,e)*r%e,s=Dn(i,ome,e)*i%e,o=Dn(s,s7,e)*s%e,a=Dn(o,sme,e)*o%e,d=Dn(a,ame,e)*a%e,l=Dn(d,a7,e)*d%e,c=Dn(l,a7,e)*d%e,u=Dn(c,s7,e)*s%e;return{pow_p_5_8:Dn(u,W6,e)*r%e,b2:t}}function QF(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function cme(r,e){let t=Lb,n=en(e*e*e,t),i=en(n*n*e,t),s=ZF(r*i).pow_p_5_8,o=en(r*n*s,t),a=en(e*o*o,t),d=o,l=en(o*o7,t),c=a===r,u=a===en(-r,t),f=a===en(-r*o7,t);return c&&(o=d),(u||f)&&(o=l),Fhe(o,t)&&(o=en(-o,t)),{isValid:c||u,value:o}}function XF(r,e,t){if(e.length>255)throw new Error("Context is too big");return RF(IF("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function dme(r){let{y:e}=Kp.ExtendedPoint.fromHex(r),t=BigInt(1);return Xa.toBytes(Xa.create((t+e)*Xa.inv(t-e)))}function lme(r){let e=qb.hash(r.subarray(0,32));return qb.adjustScalarBytes(e).subarray(0,32)}function bme(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":xme(r)||"Object"}function xme(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(vme.includes(e))return e}function nE(r){return Vb&&globalThis.Buffer.isBuffer(r)}function tG(r){return r instanceof Uint8Array?nE(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function rG(r,e){if(nE(r)&&nE(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 c7(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 Vg(r,e,t){if(r.length-e<t)throw new Error(`${kn} not enough data for type`)}function tm(r,e,t){Vg(r,e,1);let n=r[e];if(t.strict===!0&&n<lo[0])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function rm(r,e,t){Vg(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<lo[1])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function nm(r,e,t){Vg(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<lo[2])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);return n}function im(r,e,t){Vg(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],s=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&s<lo[3])throw new Error(`${kn} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${kn} integers outside of the safe integer range are not supported`)}function Rme(r,e,t,n){return new nt(_e.uint,tm(r,e+1,n),2)}function Cme(r,e,t,n){return new nt(_e.uint,rm(r,e+1,n),3)}function $me(r,e,t,n){return new nt(_e.uint,nm(r,e+1,n),5)}function Ome(r,e,t,n){return new nt(_e.uint,im(r,e+1,n),9)}function om(r,e){return tc(r,0,e.value)}function tc(r,e,t){if(t<lo[0]){let n=Number(t);r.push([e|n])}else if(t<lo[1]){let n=Number(t);r.push([e|24,n])}else if(t<lo[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<lo[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<lo[4]){let i=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&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 Bme(r,e,t,n){return new nt(_e.negint,-1-tm(r,e+1,n),2)}function jme(r,e,t,n){return new nt(_e.negint,-1-rm(r,e+1,n),3)}function Nme(r,e,t,n){return new nt(_e.negint,-1-nm(r,e+1,n),5)}function Mme(r,e,t,n){let i=im(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new nt(_e.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${kn} integers outside of the safe integer range are not supported`);return new nt(_e.negint,v5-BigInt(i),9)}function b5(r,e){let t=e.value,n=typeof t=="bigint"?t*v5-oG:t*-1-1;tc(r,e.type.majorEncoded,n)}function Yb(r,e,t,n){Vg(r,e,t+n);let i=r.slice(e+t,e+t+n);return new nt(_e.bytes,i,t+n)}function Ume(r,e,t,n){return Yb(r,e,1,t)}function Kme(r,e,t,n){return Yb(r,e,2,tm(r,e+1,n))}function Lme(r,e,t,n){return Yb(r,e,3,rm(r,e+1,n))}function qme(r,e,t,n){return Yb(r,e,5,nm(r,e+1,n))}function zme(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer bytes lengths not supported`);return Yb(r,e,9,i)}function iE(r){return r.encodedBytes===void 0&&(r.encodedBytes=_e.equals(r.type,_e.string)?Sme(r.value):r.value),r.encodedBytes}function yE(r,e){let t=iE(e);tc(r,e.type.majorEncoded,t.length),r.push(t)}function Fme(r,e){return r.length<e.length?-1:r.length>e.length?1:rG(r,e)}function Wme(r,e,t){if(t-e<Gme){let n="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return d7.decode(r.subarray(e,t));n+=String.fromCharCode(s)}return n}return d7.decode(r.subarray(e,t))}function Zb(r,e,t,n,i){let s=t+n;Vg(r,e,s);let o=new nt(_e.string,Wme(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=r.slice(e+t,e+s)),o}function Hme(r,e,t,n){return Zb(r,e,1,t,n)}function Vme(r,e,t,n){return Zb(r,e,2,tm(r,e+1,n),n)}function Jme(r,e,t,n){return Zb(r,e,3,rm(r,e+1,n),n)}function Yme(r,e,t,n){return Zb(r,e,5,nm(r,e+1,n),n)}function Zme(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer string lengths not supported`);return Zb(r,e,9,i,n)}function Jg(r,e,t,n){return new nt(_e.array,n,t)}function Xme(r,e,t,n){return Jg(r,e,1,t)}function eye(r,e,t,n){return Jg(r,e,2,tm(r,e+1,n))}function tye(r,e,t,n){return Jg(r,e,3,rm(r,e+1,n))}function rye(r,e,t,n){return Jg(r,e,5,nm(r,e+1,n))}function nye(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer array lengths not supported`);return Jg(r,e,9,i)}function iye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Jg(r,e,1,1/0)}function x5(r,e){tc(r,_e.array.majorEncoded,e.value)}function Yg(r,e,t,n){return new nt(_e.map,n,t)}function oye(r,e,t,n){return Yg(r,e,1,t)}function sye(r,e,t,n){return Yg(r,e,2,tm(r,e+1,n))}function aye(r,e,t,n){return Yg(r,e,3,rm(r,e+1,n))}function cye(r,e,t,n){return Yg(r,e,5,nm(r,e+1,n))}function dye(r,e,t,n){let i=im(r,e+1,n);if(typeof i=="bigint")throw new Error(`${kn} 64-bit integer map lengths not supported`);return Yg(r,e,9,i)}function lye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return Yg(r,e,1,1/0)}function P5(r,e){tc(r,_e.map.majorEncoded,e.value)}function uye(r,e,t,n){return new nt(_e.tag,t,1)}function fye(r,e,t,n){return new nt(_e.tag,tm(r,e+1,n),2)}function hye(r,e,t,n){return new nt(_e.tag,rm(r,e+1,n),3)}function pye(r,e,t,n){return new nt(_e.tag,nm(r,e+1,n),5)}function mye(r,e,t,n){return new nt(_e.tag,im(r,e+1,n),9)}function _5(r,e){tc(r,_e.tag.majorEncoded,e.value)}function yye(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${kn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new nt(_e.null,null,1):new nt(_e.undefined,void 0,1)}function gye(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${kn} indefinite length items not allowed`);return new nt(_e.break,void 0,1)}function E5(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 nt(_e.float,r,e)}function wye(r,e,t,n){return E5(T5(r,e+1),3,n)}function vye(r,e,t,n){return E5(D5(r,e+1),5,n)}function bye(r,e,t,n){return E5(hG(r,e+1),9,n)}function S5(r,e,t){let n=e.value;if(n===!1)r.push([_e.float.majorEncoded|sG]);else if(n===!0)r.push([_e.float.majorEncoded|aG]);else if(n===null)r.push([_e.float.majorEncoded|cG]);else if(n===void 0)r.push([_e.float.majorEncoded|dG]);else{let i,s=!1;(!t||t.float64!==!0)&&(uG(n),i=T5(Fc,1),n===i||Number.isNaN(n)?(Fc[0]=249,r.push(Fc.slice(0,3)),s=!0):(fG(n),i=D5(Fc,1),n===i&&(Fc[0]=250,r.push(Fc.slice(0,5)),s=!0))),s||(xye(n),i=hG(Fc,1),Fc[0]=251,r.push(Fc.slice(0,9)))}}function uG(r){if(r===1/0)Ha.setUint16(0,31744,!1);else if(r===-1/0)Ha.setUint16(0,64512,!1);else if(Number.isNaN(r))Ha.setUint16(0,32256,!1);else{Ha.setFloat32(0,r);let e=Ha.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ha.setUint16(0,31744,!1);else if(t===0)Ha.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ha.setUint16(0,0):i<-14?Ha.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ha.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function T5(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,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function fG(r){Ha.setFloat32(0,r,!1)}function D5(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 xye(r){Ha.setFloat64(0,r,!1)}function hG(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 mr(r,e,t){throw new Error(`${kn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function gE(r){return()=>{throw new Error(`${kn} ${r}`)}}function Pye(r){switch(r.type){case _e.false:return fu([244]);case _e.true:return fu([245]);case _e.null:return fu([246]);case _e.bytes:return r.value.length?void 0:fu([64]);case _e.string:return r.value===""?fu([96]):void 0;case _e.array:return r.value===0?fu([128]):void 0;case _e.map:return r.value===0?fu([160]):void 0;case _e.uint:return r.value<24?fu([Number(r.value)]):void 0;case _e.negint:if(r.value>=-24)return fu([31-Number(r.value)])}}function Eye(){let r=[];return r[_e.uint.major]=om,r[_e.negint.major]=b5,r[_e.bytes.major]=yE,r[_e.string.major]=Qme,r[_e.array.major]=x5,r[_e.map.major]=P5,r[_e.tag.major]=_5,r[_e.float.major]=S5,r}function j2(r,e={},t){let n=bme(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||ah[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=ah[n];if(!s)throw new Error(`${iG} unsupported type: ${n}`);return s(r,n,e,t)}function Dye(r,e){e.mapSorter&&r.sort(e.mapSorter)}function kye(r,e){if(r[0]instanceof nt&&e[0]instanceof nt){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=u7(t.value)),n._keyBytes||(n._keyBytes=u7(n.value)),rG(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function u7(r){return Aye(r,Sye,_ye)}function mG(r,e,t,n){if(Array.isArray(e))for(let i of e)mG(r,i,t,n);else t[e.type.major](r,e,n)}function Aye(r,e,t,n){let i=n instanceof Uint8Array,s=i?new Ime(n):Tye,o=j2(r,t);if(!Array.isArray(o)&&t.quickEncodeToken){let a=t.quickEncodeToken(o);if(a)return i?(s.push(a),s.toBytes()):a;let d=e[o.type.major];if(d.encodedSize){let l=d.encodedSize(o,t);if(i||(s=new nG(l)),d(s,o,t),s.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return i?s.toBytes():tG(s.chunks[0])}}return s.reset(),mG(s,o,e,t),s.toBytes(!0)}function rs(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function Iye({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function Rye({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=wE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await Tr({jwk:e})===await Tr({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function wE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(oE)??[]),Object.keys(hE).forEach(t=>{e.push(...r[t]?.filter(oE)??[])}),e}function yG({didDocument:r}){let e=wE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function gG({didDocument:r,methodId:e}){let t=[];return Object.keys(hE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],s=rs(e);i.some(o=>{let a=rs(o)===s,d=oE(o)&&rs(o.id)===s;return a||d})&&t.push(n)}}),t}function wG(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function Cye(r){return!(!wG(r)||r.type!=="DecentralizedWebNode")}function oE(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 Zg(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 vG({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=ec.addPrefix({code:e,data:r,name:t}),i=ot.uint8Array(n).toBase58Btc();return ot.base58Btc(i).toMultibase()}function bG({multibaseKeyId:r}){try{let e=ot.multibase(r).toBase58Btc(),t=ot.base58Btc(e).toUint8Array(),{code:n,data:i,name:s}=ec.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:s}}catch{throw new rt("invalidDid",`Invalid multibase identifier: ${r}`)}}function Xb(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function TG(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=Oye(n),br.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function AG(r,e,t){let n=0,i=1;for(let s=e;s<t;s++){let o=r[s];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(s===e&&o===43)){if(s===e&&o===45){i=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+s+"] = "+o)}}return n*i}function vt(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),vt.position=0,vt.encoding=n||null,vt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):wu(r),vt.bytes=vt.data.length,vt.next())}function Fye(r){let e=2;for(let t of r)e+=bE(t);return e}function Gye(r){let e=2;for(let[t,n]of r){let i=wu(t).byteLength;e+=Xb(i)+1+i,e+=bE(n)}return e}function Wye(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=wu(t[n]).byteLength;e+=Xb(i)+1+i,e+=bE(r[t[n]])}return e}function Hye(r){let e=wu(r).byteLength;return Xb(e)+1+e}function Vye(r){let e=r.byteLength-r.byteOffset;return Xb(e)+1+e}function bE(r){if(r==null)return 0;let e=TG(r);switch(e){case"arraybufferview":return Vye(r);case"string":return Hye(r);case"array":case"set":return Fye(r);case"number":return 1+Xb(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Wye(r);case"map":return Gye(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function CG(r){if(tl.isFormat(r))return tl.size;if(sh.isFormat(r))return sh.size;throw Error(`Invalid ip address: ${r}`)}function Qye(r){return CG(r)===tl.size?1:2}function Xye(r,e,t){t=~~t;let n=CG(r);return typeof e=="function"&&(e=e(t+n)),n===tl.size?tl.encode(r,e,t):sh.encode(r,e,t)}function ege(r,e,t){if(e=~~e,t=t||r.length-e,t===tl.size)return tl.decode(r,e,t);if(t===sh.size)return sh.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${tl.size} for v4 or ${sh.size} for v6.`)}function xE(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 zb(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 tge(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 rge(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 $G(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 OG(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 nge(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 E7(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 BG(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 s=n+1;s===t||i>=56320||(r.charCodeAt(s)&64512)!==56320?e+=3:(n=s,e+=4)}}return e}function Fb(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(BG(r)+t));let i=t;for(let s=0;s<n;s+=1){let o=r.charCodeAt(s);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 a=s+1;if(a===n||o>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let d=r.charCodeAt(a);(d&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(s=a,o=65536|(o&1023)<<10|d&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 Fb.bytes=i-t,e}function e1(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let s=r[i++],o;if(s<=128)o=s;else if(s>191&&s<224)o=(s&31)<<6|r[i++]&63;else if(s>239&&s<365){o=((s&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let a=55296|o>>10&1023;n+=String.fromCharCode(a),o=56320|o&1023}else o=(s&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(o)}return e1.bytes=t-e,n}function ch(r){return typeof r=="string"?BG(r):r.byteLength}function R5(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):Fb(r)}function C5(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return Fb(e,r,t),Fb.bytes}function ige(r,e,t){let n="";for(let i=e;i<t;){let s=r[i++];n+=jG[s]}return n}function S7(r){return r.length>>>1}function oge(r,e,t,n){let i=0;for(;t<n;){let s=e.substr(i,2),o=Eb[s];if(o===void 0)return;r[t++]=o,i+=2}return r}function la(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:dge(r,e,t,n,i)}function dge(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let s=i-n,o=r.length-n;return s>o&&(s=o),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,s)),e.set(r,t),s}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 V6(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function B6(r){switch(r.toUpperCase()){case"A":return MG;case"PTR":return Ug;case"CNAME":return Ug;case"DNAME":return Ug;case"TXT":return K2;case"NULL":return L2;case"AAAA":return G2;case"SRV":return z2;case"HINFO":return q2;case"CAA":return nh;case"NS":return M2;case"SOA":return U2;case"MX":return F2;case"OPT":return ih;case"DNSKEY":return el;case"RRSIG":return Sb;case"RP":return Tb;case"NSEC":return Db;case"NSEC3":return kb;case"SSHFP":return jg;case"DS":return Ab}return N2}function sE(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 UG(r){let e=dE(r),t=new Uint8Array(2+e.byteLength);return st(t,e.byteLength),la(e,t,2,0,e.length),UG.bytes=t.byteLength,t}function KG(r){let e=Lt(r,0);if(r.byteLength<e+2)return null;let t=J6(r.slice(2));return KG.bytes=J6.bytes,t}function Ng(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function Ib(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 k2(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 LG(r,e){let t=ot.uint8Array(r).toBase32Z();return new URL(t,e).href}async function qG(r,e,t){if(t)return fetch(r,e);try{return await xF(r,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof O2?new rt("invalidGatewayUri",n.message):n}}async function mge({gatewayUri:r,publicKeyBytes:e,allowPrivateGatewayUri:t=!1}){let n=ot.uint8Array(e).toBase32Z(),i=LG(e,r),s;try{if(s=await qG(i,{method:"GET",signal:AbortSignal.timeout(3e4)},t),!s.ok)throw new rt("notFound",`Pkarr record not found for: ${n}`)}catch(a){throw a instanceof rt?a:new rt("internalError",`Failed to fetch Pkarr record: ${a.message}`)}let o=await s.arrayBuffer();if(!o)throw new rt("notFound",`Pkarr record not found for: ${n}`);if(o.byteLength<72)throw new rt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${o.byteLength}`);if(o.byteLength>1072)throw new rt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${o.byteLength}`);return{k:e,seq:Number(new DataView(o).getBigUint64(64)),sig:new Uint8Array(o,0,64),v:new Uint8Array(o,72)}}async function yge({gatewayUri:r,bep44Message:e,allowPrivateGatewayUri:t=!1}){let n=ot.uint8Array(e.k).toBase32Z(),i=LG(e.k,r),s=new Uint8Array(e.v.length+72);s.set(e.sig,0),new DataView(s.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),s.set(e.v,e.sig.length+8);let o;try{o=await qG(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)},t)}catch(a){throw a instanceof rt?a:new rt("internalError",`Failed to put Pkarr record for identifier ${n}: ${a.message}`)}return o.ok}async function gge({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=dE(r),s=RG.encode({seq:n,v:i}).subarray(1,-1);if(s.length>1e3)throw new rt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${s.length} bytes`);let o=await t.sign({data:new Uint8Array(s)});return{k:e,seq:n,sig:o,v:i}}async function wge({bep44Message:r}){let e=await co.bytesToPublicKey({publicKeyBytes:r.k}),t=RG.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await co.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new rt("invalidSignature","Invalid signature for DHT BEP44 message");return J6(r.v)}async function FG({didUri:r}){let e=$5({didUri:r});return await co.bytesToPublicKey({publicKeyBytes:e})}function $5({didUri:r}){let e=Qn.parse(r);if(!e)throw new rt("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==zG)throw new rt("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=ot.base32Z(e.id).toUint8Array()}catch{throw new rt("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new rt("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function vge({identityKey:r}){let e=await co.publicKeyToBytes({publicKey:r}),t=ot.uint8Array(e).toBase32Z();return`did:${zG}:${t}`}function O5(r){let e={Ed25519:co,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await Ao.publicKeyToBytes({publicKey:t});return await Ao.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Ao.bytesToPublicKey,privateKeyToBytes:Ao.privateKeyToBytes,bytesToPrivateKey:Ao.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await ao.publicKeyToBytes({publicKey:t});return await ao.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ao.bytesToPublicKey,privateKeyToBytes:ao.privateKeyToBytes,bytesToPrivateKey:ao.bytesToPrivateKey},X25519:Rg}[r];if(!e)throw new rt("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function GG({newDid:r,previousDidProof:e}){let t=await FG({didUri:e.previousDid}),n=$5({didUri:r}),i=ot.base64Url(e.signature).toUint8Array();if(!await co.verify({key:t,data:n,signature:i}))throw new rt("invalidPreviousDidProof","The previous DID proof is invalid.")}function Gb(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return ot.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>Gb(e)).join("");throw new rt("internalError","Pkarr returned DNS TXT record with invalid data type")}function Rb(r){return Gb(r).split(W2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function VG(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 xge({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let s of e?.answers??[]){if(s.type!=="TXT")continue;let o=s.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let a=Gb(s.data);t.alsoKnownAs=a.split(ts);break}case o.startsWith("cnt"):{let a=Gb(s.data);t.controller=a.includes(ts)?a.split(ts):a;break}case o.startsWith("k"):{let{id:a,t:d,k:l,c,a:u}=Rb(s.data),f=ot.base64Url(l).toUint8Array(),h=A5[Number(d)],p=await O5(h).bytesToPublicKey({publicKeyBytes:f});p.alg=u||HG[Number(d)];let m=o==="k0"?"0":a===void 0?await Tr({jwk:p}):a;t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:c??r,publicKeyJwk:p}),i.set(o,y);break}case o.startsWith("s"):{let{id:a,t:d,se:l,...c}=Rb(s.data),u=l.includes(ts)?l.split(ts):[l],f=Object.fromEntries(Object.entries(c).map(([h,p])=>[h,p.includes(ts)?p.split(ts):p]));t.service??=[],t.service.push({...f,id:`${r}#${a}`,type:d,serviceEndpoint:u});break}case o.startsWith("typ"):{let{id:a}=Rb(s.data);n.types=a.split(ts).map(d=>Number(d));break}case o.startsWith("did"):{let a=h=>h.split(ts).map(p=>i.get(p)).filter(p=>typeof p=="string"),{auth:d,asm:l,del:c,inv:u,agm:f}=Rb(s.data);d&&(t.authentication=a(d)),l&&(t.assertionMethod=a(l)),c&&(t.capabilityDelegation=a(c)),u&&(t.capabilityInvocation=a(u)),f&&(t.keyAgreement=a(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function Pge({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],s=[],o=new Map,a=[],d=[];if(n!==void 0){let{signature:c,previousDid:u}=n;await GG({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:Xf,data:`id=${u};s=${c}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:Xf,data:r.alsoKnownAs.join(ts)}),r.controller){let c=Array.isArray(r.controller)?r.controller.join(ts):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:Xf,data:c})}for(let[c,u]of r.verificationMethod?.entries()??[]){let f=`k${c}`;d.push(f);let h=u.id.split("#").pop();o.set(h,f);let p=u.publicKeyJwk;if(!(p?.crv&&p.crv in WG))throw new rt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=A5[p.crv],y=await O5(p.crv).publicKeyToBytes({publicKey:p}),v=ot.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];h!=="0"&&await Tr({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==HG[m]&&w.push(`a=${p.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:Xf,data:w.join(W2)})}r.service?.forEach((c,u)=>{let f=`s${u}`;a.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=c;h=rs(h),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:h,t:p,se:m,...y}).map(([b,T])=>`${b}=${T}`).join(W2),w=VG(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:Xf,data:w})});let l=[`v=${bge}`];if(d.length&&l.push(`vm=${d.join(ts)}`),Object.keys(hE).forEach(c=>{let u=r[c]?.map(f=>o.get(f.split("#").pop()));if(u){let f=_G[c];l.push(`${f}=${u.join(ts)}`)}}),a.length&&l.push(`svc=${a.join(ts)}`),e.types?.length){let c=e.types.map(u=>typeof u=="string"?PG[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:Xf,data:`id=${c.join(ts)}`})}i.push({type:"TXT",name:"_did."+k7(r.id)+".",ttl:Xf,data:l.join(W2)});for(let c of t||[])s.push({type:"NS",name:"_did."+k7(r.id)+".",ttl:Xf,data:c+"."});return{id:0,type:"response",flags:hge,answers:[...i,...s]}}function k7(r){return r.split(":")[2]}function Ege(){return O.DID_DHT_GATEWAY_URI||_ge}function Sge(){return O.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function A7(r,e){return{gatewayUri:r??Ege(),allowPrivateGatewayUri:e??Sge()}}function ZG(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Uge;)e[t++]=r&255|C7,r/=128;for(;r&Mge;)e[t++]=r&255|C7,r>>>=7;return e[t]=r|0,ZG.bytes=t-n+1,e}function X6(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw X6.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&$7)<<i:(o&$7)*Math.pow(2,i),i+=7}while(o>=Lge);return X6.bytes=s-n,t}function hwe(r){r=L5(r);let e=Lg+8;(r.length<e||r.length>1024)&&Bi("expected proper params");let t=tt(SE(r),K5-1n)+1n;return z5(t)}var Yue,i5,Zue,Que,Xue,efe,Xt,o5,tfe,Xp,rfe,nfe,il,ife,ofe,s5,nF,iF,oF,sfe,afe,cfe,dfe,fE,a5,Wp,lfe,ufe,sF,ffe,hfe,aF,pfe,mfe,yfe,Uz,cF,gfe,dF,lF,wfe,vfe,bfe,uF,xfe,Pfe,fF,hE,fo,oo,Qn,rt,_fe,Qa,ks,Efe,Tfe,Dfe,kfe,P9e,Afe,c5,Ife,Rfe,Cfe,yF,$fe,gF,wF,Ofe,Bfe,ua,$2,_9e,E9e,S9e,T9e,D9e,k9e,A9e,Kz,Ya,I9e,R9e,C9e,au,$9e,pb,Lz,S2,Up,ot,jb,Mfe,Ufe,xb,Kfe,qz,Lfe,qfe,zfe,Ffe,Gfe,zz,Wfe,Hfe,Vfe,Jfe,Yfe,Zfe,Qfe,Xfe,ehe,the,rhe,nhe,eE,tE,Mb,Ub,ihe,ohe,she,d5,Fz,Gz,K6,O9e,ahe,che,dhe,mb,lhe,Wz,uhe,ec,B9e,Ff,fhe,hhe,mhe,O2,yhe,ghe,pE,EF,SF,mE,Phe,_he,cu,Ahe,u5,k6,Jz,Ihe,A6,I6,Vd,Ohe,CF,j9e,OF,jhe,Nhe,Mhe,Gf,Wf,Uhe,BF,xi,xn,qp,Khe,L6,Zz,Qz,N9e,Lhe,Fhe,Ghe,Zhe,R6,Xhe,epe,Gp,pu,Ja,M9e,Xz,U9e,LF,qF,FF,e7,ope,z6,t7,F6,aa,K9e,L9e,B2,C6,Jd,q9e,lpe,z9e,ppe,mpe,ype,gpe,Hf,Vf,wpe,Kb,bpe,HF,xpe,n7,no,_pe,ao,VF,Epe,Spe,Tpe,Fa,io,Dpe,Ao,du,i7,T2,G6,Ape,Ipe,Rpe,Cpe,$pe,Ope,Bpe,jpe,Npe,Mpe,Upe,Kpe,Lpe,zpe,Fpe,Gpe,Wpe,Hpe,Vpe,Jpe,Kt,Ype,Zpe,Jf,Yf,Qpe,YF,zc,oa,D2,Xpe,eme,yb,$6,Lb,o7,F9e,ime,W6,ome,s7,sme,ame,a7,Xa,qb,Kp,G9e,W9e,Pb,ume,H9e,V9e,J9e,Y9e,Z9e,Q9e,X9e,eze,tze,rze,Ga,fme,co,lu,hme,pme,mme,Zf,yme,Rg,gb,gme,uu,O6,Wc,wme,vme,_e,nt,Vb,Pme,_me,Eme,Sme,fu,Tme,Dme,kme,Ame,nG,Ime,kn,iG,Jb,lo,v5,oG,d7,Gme,Qme,sG,aG,cG,dG,lG,Ha,Fc,Be,vu,_ye,Sye,Tye,l7,Qf,ah,nze,ize,oze,sze,aze,cze,dze,lze,uze,fze,hze,pze,mze,f7,Io,Za,h7,p7,yze,gze,wze,vze,m7,y7,g7,w7,k5,Ro,Qb,PG,A5,_G,v7,EG,b7,$ye,Oye,x7,Bye,wb,jye,SG,Nye,wu,P7,_7,bze,vE,DG,kG,Mye,Uye,Kye,Lye,qye,I5,zye,IG,Jye,RG,Yye,Zye,tl,sh,Qp,Eb,jG,sge,age,cge,mu,Lt,yu,st,lge,T7,H6,uge,NG,fge,Ve,bi,Cg,N2,M2,U2,K2,L2,q2,Ug,z2,nh,F2,MG,G2,D7,hu,ih,el,Sb,Tb,da,Db,kb,Ab,jg,Va,Kg,hge,uo,aE,cE,dE,J6,pge,zG,bge,Xf,W2,ts,WG,HG,_ge,JG,fa,I7,Mg,Jn,Yn,xze,Tge,Dge,kge,Age,YG,Ige,Rge,Cge,$ge,PE,Pze,_ze,R7,Eze,Fg,Oge,Z6,Xd,sa,B5,Gc,Bge,Wb,jge,C7,Nge,Mge,Uge,Kge,Lge,$7,qge,zge,Fge,Gge,Wge,Hge,Vge,Jge,Yge,Zge,Qge,Xge,lE,O7,B7,j7,N7,ewe,QG,XG,twe,eW,M7,Sze,vb,ca,e5,A2,t5,Ig,I2,tW,U7,rwe,so,V2,r5,n5,R2,Ds,nW,j5,Gg,nwe,dt,K7,L7,Wg,uE,J2,iW,N5,M5,iwe,owe,q7,oW,Yd,swe,z7,awe,j6,F7,cwe,zp,dwe,lwe,U5,Jp,K5,sW,aW,cW,Lg,G7,Bi,_E,dW,N6,lW,uW,Hb,L5,tt,W7,H7,Hg,Nb,Y2,fW,q5,EE,SE,V7,z5,J7,Y7,hW,uwe,fwe,Z7,Z2,pwe,Fp,mwe,ywe,Q7,X7,bb,gwe,wwe,eF,vwe,pW,ns,bwe,Q2,C2,xwe,tF,mW,sm,Pwe,yW,TE,_we,Ewe,DE,Swe,t1,Twe,dh,is=G(()=>{"use strict";g();Yue=Object.create,i5=Object.defineProperty,Zue=Object.getOwnPropertyDescriptor,Que=Object.getOwnPropertyNames,Xue=Object.getPrototypeOf,efe=Object.prototype.hasOwnProperty,Xt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),o5=(r,e)=>{for(var t in e)i5(r,t,{get:e[t],enumerable:!0})},tfe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Que(e))!efe.call(r,i)&&i!==t&&i5(r,i,{get:()=>e[i],enumerable:!(n=Zue(e,i))||n.enumerable});return r},Xp=(r,e,t)=>(t=r!=null?Yue(Xue(r)):{},tfe(e||!r||!r.__esModule?i5(t,"default",{value:r,enumerable:!0}):t,r)),rfe=Xt((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),s=a=>a===1/0||i(a),o=class rF{constructor({max:d=1/0,ttl:l,updateAgeOnGet:c=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!s(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!s(d))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=d,this.updateAgeOnGet=!!c,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!p,h!==void 0){if(typeof h!="function")throw new TypeError("dispose must be function if set");this.dispose=h}this.timer=void 0,this.timerExpiration=void 0}setTimer(d,l){if(this.timerExpiration<d)return;this.timer&&clearTimeout(this.timer);let c=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);c.unref&&c.unref(),this.timerExpiration=d,this.timer=c}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 d=this.dispose!==rF.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,c]of d)this.dispose(c,l,"delete")}setTTL(d,l=this.ttl){let c=this.expirationMap.get(d);if(c!==void 0){let u=this.expirations[c];!u||u.length<=1?delete this.expirations[c]:this.expirations[c]=u.filter(f=>f!==d)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(d,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(d)}else this.expirationMap.set(d,1/0)}set(d,l,{ttl:c=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!s(c))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(d)){u||this.setTTL(d,c);let h=this.data.get(d);h!==l&&(this.data.set(d,l),f||this.dispose(h,d,"set"))}else this.setTTL(d,c),this.data.set(d,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(d){return this.data.has(d)}getRemainingTTL(d){let l=this.expirationMap.get(d);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(d,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:c=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(d);if(u&&this.getRemainingTTL(d)===0){this.delete(d);return}return l&&this.setTTL(d,c),f}dispose(d,l){}delete(d){let l=this.expirationMap.get(d);if(l!==void 0){let c=this.data.get(d);this.data.delete(d),this.expirationMap.delete(d);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==d)),this.dispose(c,d,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let d in this.expirations){let l=this.expirations[d];if(this.size-l.length>=this.max){delete this.expirations[d];let c=[];for(let u of l)c.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of c)this.dispose(f,u,"evict")}else{let c=this.size-this.max,u=[];for(let f of l.splice(0,c))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let d=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>d)return;let c=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of c)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let d in this.expirations)for(let l of this.expirations[d])yield[l,this.data.get(l)]}*keys(){for(let d in this.expirations)for(let l of this.expirations[d])yield l}*values(){for(let d in this.expirations)for(let l of this.expirations[d])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=o}),nfe=Xt(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)})}}),il=Xt((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)}}}),ife=Xt(r=>{"use strict";r.byteLength=d,r.toByteArray=c,r.fromByteArray=h;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(s=0,o=i.length;s<o;++s)e[s]=i[s],t[i.charCodeAt(s)]=s;var s,o;t[45]=62,t[95]=63;function a(p){var m=p.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=p.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function d(p){var m=a(p),y=m[0],v=m[1];return(y+v)*3/4-v}function l(p,m,y){return(m+y)*3/4-y}function c(p){var m,y=a(p),v=y[0],w=y[1],b=new n(l(p,v,w)),T=0,D=w>0?v-4:v,I;for(I=0;I<D;I+=4)m=t[p.charCodeAt(I)]<<18|t[p.charCodeAt(I+1)]<<12|t[p.charCodeAt(I+2)]<<6|t[p.charCodeAt(I+3)],b[T++]=m>>16&255,b[T++]=m>>8&255,b[T++]=m&255;return w===2&&(m=t[p.charCodeAt(I)]<<2|t[p.charCodeAt(I+1)]>>4,b[T++]=m&255),w===1&&(m=t[p.charCodeAt(I)]<<10|t[p.charCodeAt(I+1)]<<4|t[p.charCodeAt(I+2)]>>2,b[T++]=m>>8&255,b[T++]=m&255),b}function u(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var v,w=[],b=m;b<y;b+=3)v=(p[b]<<16&16711680)+(p[b+1]<<8&65280)+(p[b+2]&255),w.push(u(v));return w.join("")}function h(p){for(var m,y=p.length,v=y%3,w=[],b=16383,T=0,D=y-v;T<D;T+=b)w.push(f(p,T,T+b>D?D:T+b));return v===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),ofe=Xt(r=>{r.read=function(e,t,n,i,s){var o,a,d=s*8-i-1,l=(1<<d)-1,c=l>>1,u=-7,f=n?s-1:0,h=n?-1:1,p=e[t+f];for(f+=h,o=p&(1<<-u)-1,p>>=-u,u+=d;u>0;o=o*256+e[t+f],f+=h,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=i;u>0;a=a*256+e[t+f],f+=h,u-=8);if(o===0)o=1-c;else{if(o===l)return a?NaN:(p?-1:1)*(1/0);a=a+Math.pow(2,i),o=o-c}return(p?-1:1)*a*Math.pow(2,o-i)},r.write=function(e,t,n,i,s,o){var a,d,l,c=o*8-s-1,u=(1<<c)-1,f=u>>1,h=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=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?(d=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+f>=1?t+=h/l:t+=h*Math.pow(2,1-f),t*l>=2&&(a++,l/=2),a+f>=u?(d=0,a=u):a+f>=1?(d=(t*l-1)*Math.pow(2,s),a=a+f):(d=t*Math.pow(2,f-1)*Math.pow(2,s),a=0));s>=8;e[n+p]=d&255,p+=m,d/=256,s-=8);for(a=a<<s|d,c+=s;c>0;e[n+p]=a&255,p+=m,a/=256,c-=8);e[n+p-m]|=y*128}}),s5=Xt(r=>{"use strict";var e=ife(),t=ofe(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=a,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.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 s(){try{let k=new Uint8Array(1),U={foo:function(){return 42}};return Object.setPrototypeOf(U,Uint8Array.prototype),Object.setPrototypeOf(k,U),k.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(k){if(k>i)throw new RangeError('The value "'+k+'" is invalid for option "size"');let U=new Uint8Array(k);return Object.setPrototypeOf(U,a.prototype),U}function a(k,U,K){if(typeof k=="number"){if(typeof U=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(k)}return d(k,U,K)}a.poolSize=8192;function d(k,U,K){if(typeof k=="string")return f(k,U);if(ArrayBuffer.isView(k))return p(k);if(k==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k);if(Ye(k,ArrayBuffer)||k&&Ye(k.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ye(k,SharedArrayBuffer)||k&&Ye(k.buffer,SharedArrayBuffer)))return m(k,U,K);if(typeof k=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=k.valueOf&&k.valueOf();if(te!=null&&te!==k)return a.from(te,U,K);let de=y(k);if(de)return de;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof k[Symbol.toPrimitive]=="function")return a.from(k[Symbol.toPrimitive]("string"),U,K);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k)}a.from=function(k,U,K){return d(k,U,K)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(k){if(typeof k!="number")throw new TypeError('"size" argument must be of type number');if(k<0)throw new RangeError('The value "'+k+'" is invalid for option "size"')}function c(k,U,K){return l(k),k<=0?o(k):U!==void 0?typeof K=="string"?o(k).fill(U,K):o(k).fill(U):o(k)}a.alloc=function(k,U,K){return c(k,U,K)};function u(k){return l(k),o(k<0?0:v(k)|0)}a.allocUnsafe=function(k){return u(k)},a.allocUnsafeSlow=function(k){return u(k)};function f(k,U){if((typeof U!="string"||U==="")&&(U="utf8"),!a.isEncoding(U))throw new TypeError("Unknown encoding: "+U);let K=b(k,U)|0,te=o(K),de=te.write(k,U);return de!==K&&(te=te.slice(0,de)),te}function h(k){let U=k.length<0?0:v(k.length)|0,K=o(U);for(let te=0;te<U;te+=1)K[te]=k[te]&255;return K}function p(k){if(Ye(k,Uint8Array)){let U=new Uint8Array(k);return m(U.buffer,U.byteOffset,U.byteLength)}return h(k)}function m(k,U,K){if(U<0||k.byteLength<U)throw new RangeError('"offset" is outside of buffer bounds');if(k.byteLength<U+(K||0))throw new RangeError('"length" is outside of buffer bounds');let te;return U===void 0&&K===void 0?te=new Uint8Array(k):K===void 0?te=new Uint8Array(k,U):te=new Uint8Array(k,U,K),Object.setPrototypeOf(te,a.prototype),te}function y(k){if(a.isBuffer(k)){let U=v(k.length)|0,K=o(U);return K.length===0||k.copy(K,0,0,U),K}if(k.length!==void 0)return typeof k.length!="number"||ar(k.length)?o(0):h(k);if(k.type==="Buffer"&&Array.isArray(k.data))return h(k.data)}function v(k){if(k>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return k|0}function w(k){return+k!=k&&(k=0),a.alloc(+k)}a.isBuffer=function(k){return k!=null&&k._isBuffer===!0&&k!==a.prototype},a.compare=function(k,U){if(Ye(k,Uint8Array)&&(k=a.from(k,k.offset,k.byteLength)),Ye(U,Uint8Array)&&(U=a.from(U,U.offset,U.byteLength)),!a.isBuffer(k)||!a.isBuffer(U))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(k===U)return 0;let K=k.length,te=U.length;for(let de=0,ge=Math.min(K,te);de<ge;++de)if(k[de]!==U[de]){K=k[de],te=U[de];break}return K<te?-1:te<K?1:0},a.isEncoding=function(k){switch(String(k).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}},a.concat=function(k,U){if(!Array.isArray(k))throw new TypeError('"list" argument must be an Array of Buffers');if(k.length===0)return a.alloc(0);let K;if(U===void 0)for(U=0,K=0;K<k.length;++K)U+=k[K].length;let te=a.allocUnsafe(U),de=0;for(K=0;K<k.length;++K){let ge=k[K];if(Ye(ge,Uint8Array))de+ge.length>te.length?(a.isBuffer(ge)||(ge=a.from(ge)),ge.copy(te,de)):Uint8Array.prototype.set.call(te,ge,de);else if(a.isBuffer(ge))ge.copy(te,de);else throw new TypeError('"list" argument must be an Array of Buffers');de+=ge.length}return te};function b(k,U){if(a.isBuffer(k))return k.length;if(ArrayBuffer.isView(k)||Ye(k,ArrayBuffer))return k.byteLength;if(typeof k!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof k);let K=k.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&K===0)return 0;let de=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return K;case"utf8":case"utf-8":return Ae(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K*2;case"hex":return K>>>1;case"base64":return Lr(k).length;default:if(de)return te?-1:Ae(k).length;U=(""+U).toLowerCase(),de=!0}}a.byteLength=b;function T(k,U,K){let te=!1;if((U===void 0||U<0)&&(U=0),U>this.length||((K===void 0||K>this.length)&&(K=this.length),K<=0)||(K>>>=0,U>>>=0,K<=U))return"";for(k||(k="utf8");;)switch(k){case"hex":return S(this,U,K);case"utf8":case"utf-8":return R(this,U,K);case"ascii":return P(this,U,K);case"latin1":case"binary":return _(this,U,K);case"base64":return ee(this,U,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,U,K);default:if(te)throw new TypeError("Unknown encoding: "+k);k=(k+"").toLowerCase(),te=!0}}a.prototype._isBuffer=!0;function D(k,U,K){let te=k[U];k[U]=k[K],k[K]=te}a.prototype.swap16=function(){let k=this.length;if(k%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;U<k;U+=2)D(this,U,U+1);return this},a.prototype.swap32=function(){let k=this.length;if(k%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let U=0;U<k;U+=4)D(this,U,U+3),D(this,U+1,U+2);return this},a.prototype.swap64=function(){let k=this.length;if(k%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let U=0;U<k;U+=8)D(this,U,U+7),D(this,U+1,U+6),D(this,U+2,U+5),D(this,U+3,U+4);return this},a.prototype.toString=function(){let k=this.length;return k===0?"":arguments.length===0?R(this,0,k):T.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(k){if(!a.isBuffer(k))throw new TypeError("Argument must be a Buffer");return this===k?!0:a.compare(this,k)===0},a.prototype.inspect=function(){let k="",U=r.INSPECT_MAX_BYTES;return k=this.toString("hex",0,U).replace(/(.{2})/g,"$1 ").trim(),this.length>U&&(k+=" ... "),"<Buffer "+k+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(k,U,K,te,de){if(Ye(k,Uint8Array)&&(k=a.from(k,k.offset,k.byteLength)),!a.isBuffer(k))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof k);if(U===void 0&&(U=0),K===void 0&&(K=k?k.length:0),te===void 0&&(te=0),de===void 0&&(de=this.length),U<0||K>k.length||te<0||de>this.length)throw new RangeError("out of range index");if(te>=de&&U>=K)return 0;if(te>=de)return-1;if(U>=K)return 1;if(U>>>=0,K>>>=0,te>>>=0,de>>>=0,this===k)return 0;let ge=de-te,Ee=K-U,Wt=Math.min(ge,Ee),ci=this.slice(te,de),Vr=k.slice(U,K);for(let Dr=0;Dr<Wt;++Dr)if(ci[Dr]!==Vr[Dr]){ge=ci[Dr],Ee=Vr[Dr];break}return ge<Ee?-1:Ee<ge?1:0};function I(k,U,K,te,de){if(k.length===0)return-1;if(typeof K=="string"?(te=K,K=0):K>2147483647?K=2147483647:K<-2147483648&&(K=-2147483648),K=+K,ar(K)&&(K=de?0:k.length-1),K<0&&(K=k.length+K),K>=k.length){if(de)return-1;K=k.length-1}else if(K<0)if(de)K=0;else return-1;if(typeof U=="string"&&(U=a.from(U,te)),a.isBuffer(U))return U.length===0?-1:M(k,U,K,te,de);if(typeof U=="number")return U=U&255,typeof Uint8Array.prototype.indexOf=="function"?de?Uint8Array.prototype.indexOf.call(k,U,K):Uint8Array.prototype.lastIndexOf.call(k,U,K):M(k,[U],K,te,de);throw new TypeError("val must be string, number or Buffer")}function M(k,U,K,te,de){let ge=1,Ee=k.length,Wt=U.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(k.length<2||U.length<2)return-1;ge=2,Ee/=2,Wt/=2,K/=2}function ci(Dr,gr){return ge===1?Dr[gr]:Dr.readUInt16BE(gr*ge)}let Vr;if(de){let Dr=-1;for(Vr=K;Vr<Ee;Vr++)if(ci(k,Vr)===ci(U,Dr===-1?0:Vr-Dr)){if(Dr===-1&&(Dr=Vr),Vr-Dr+1===Wt)return Dr*ge}else Dr!==-1&&(Vr-=Vr-Dr),Dr=-1}else for(K+Wt>Ee&&(K=Ee-Wt),Vr=K;Vr>=0;Vr--){let Dr=!0;for(let gr=0;gr<Wt;gr++)if(ci(k,Vr+gr)!==ci(U,gr)){Dr=!1;break}if(Dr)return Vr}return-1}a.prototype.includes=function(k,U,K){return this.indexOf(k,U,K)!==-1},a.prototype.indexOf=function(k,U,K){return I(this,k,U,K,!0)},a.prototype.lastIndexOf=function(k,U,K){return I(this,k,U,K,!1)};function C(k,U,K,te){K=Number(K)||0;let de=k.length-K;te?(te=Number(te),te>de&&(te=de)):te=de;let ge=U.length;te>ge/2&&(te=ge/2);let Ee;for(Ee=0;Ee<te;++Ee){let Wt=parseInt(U.substr(Ee*2,2),16);if(ar(Wt))return Ee;k[K+Ee]=Wt}return Ee}function z(k,U,K,te){return ds(Ae(U,k.length-K),k,K,te)}function L(k,U,K,te){return ds(Ot(U),k,K,te)}function B(k,U,K,te){return ds(Lr(U),k,K,te)}function H(k,U,K,te){return ds(ai(U,k.length-K),k,K,te)}a.prototype.write=function(k,U,K,te){if(U===void 0)te="utf8",K=this.length,U=0;else if(K===void 0&&typeof U=="string")te=U,K=this.length,U=0;else if(isFinite(U))U=U>>>0,isFinite(K)?(K=K>>>0,te===void 0&&(te="utf8")):(te=K,K=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let de=this.length-U;if((K===void 0||K>de)&&(K=de),k.length>0&&(K<0||U<0)||U>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return C(this,k,U,K);case"utf8":case"utf-8":return z(this,k,U,K);case"ascii":case"latin1":case"binary":return L(this,k,U,K);case"base64":return B(this,k,U,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,k,U,K);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(k,U,K){return U===0&&K===k.length?e.fromByteArray(k):e.fromByteArray(k.slice(U,K))}function R(k,U,K){K=Math.min(k.length,K);let te=[],de=U;for(;de<K;){let ge=k[de],Ee=null,Wt=ge>239?4:ge>223?3:ge>191?2:1;if(de+Wt<=K){let ci,Vr,Dr,gr;switch(Wt){case 1:ge<128&&(Ee=ge);break;case 2:ci=k[de+1],(ci&192)===128&&(gr=(ge&31)<<6|ci&63,gr>127&&(Ee=gr));break;case 3:ci=k[de+1],Vr=k[de+2],(ci&192)===128&&(Vr&192)===128&&(gr=(ge&15)<<12|(ci&63)<<6|Vr&63,gr>2047&&(gr<55296||gr>57343)&&(Ee=gr));break;case 4:ci=k[de+1],Vr=k[de+2],Dr=k[de+3],(ci&192)===128&&(Vr&192)===128&&(Dr&192)===128&&(gr=(ge&15)<<18|(ci&63)<<12|(Vr&63)<<6|Dr&63,gr>65535&&gr<1114112&&(Ee=gr))}}Ee===null?(Ee=65533,Wt=1):Ee>65535&&(Ee-=65536,te.push(Ee>>>10&1023|55296),Ee=56320|Ee&1023),te.push(Ee),de+=Wt}return E(te)}var $=4096;function E(k){let U=k.length;if(U<=$)return String.fromCharCode.apply(String,k);let K="",te=0;for(;te<U;)K+=String.fromCharCode.apply(String,k.slice(te,te+=$));return K}function P(k,U,K){let te="";K=Math.min(k.length,K);for(let de=U;de<K;++de)te+=String.fromCharCode(k[de]&127);return te}function _(k,U,K){let te="";K=Math.min(k.length,K);for(let de=U;de<K;++de)te+=String.fromCharCode(k[de]);return te}function S(k,U,K){let te=k.length;(!U||U<0)&&(U=0),(!K||K<0||K>te)&&(K=te);let de="";for(let ge=U;ge<K;++ge)de+=qr[k[ge]];return de}function A(k,U,K){let te=k.slice(U,K),de="";for(let ge=0;ge<te.length-1;ge+=2)de+=String.fromCharCode(te[ge]+te[ge+1]*256);return de}a.prototype.slice=function(k,U){let K=this.length;k=~~k,U=U===void 0?K:~~U,k<0?(k+=K,k<0&&(k=0)):k>K&&(k=K),U<0?(U+=K,U<0&&(U=0)):U>K&&(U=K),U<k&&(U=k);let te=this.subarray(k,U);return Object.setPrototypeOf(te,a.prototype),te};function N(k,U,K){if(k%1!==0||k<0)throw new RangeError("offset is not uint");if(k+U>K)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k],de=1,ge=0;for(;++ge<U&&(de*=256);)te+=this[k+ge]*de;return te},a.prototype.readUintBE=a.prototype.readUIntBE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k+--U],de=1;for(;U>0&&(de*=256);)te+=this[k+--U]*de;return te},a.prototype.readUint8=a.prototype.readUInt8=function(k,U){return k=k>>>0,U||N(k,1,this.length),this[k]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(k,U){return k=k>>>0,U||N(k,2,this.length),this[k]|this[k+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(k,U){return k=k>>>0,U||N(k,2,this.length),this[k]<<8|this[k+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(k,U){return k=k>>>0,U||N(k,4,this.length),(this[k]|this[k+1]<<8|this[k+2]<<16)+this[k+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]*16777216+(this[k+1]<<16|this[k+2]<<8|this[k+3])},a.prototype.readBigUInt64LE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=U+this[++k]*2**8+this[++k]*2**16+this[++k]*2**24,de=this[++k]+this[++k]*2**8+this[++k]*2**16+K*2**24;return BigInt(te)+(BigInt(de)<<BigInt(32))}),a.prototype.readBigUInt64BE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=U*2**24+this[++k]*2**16+this[++k]*2**8+this[++k],de=this[++k]*2**24+this[++k]*2**16+this[++k]*2**8+K;return(BigInt(te)<<BigInt(32))+BigInt(de)}),a.prototype.readIntLE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=this[k],de=1,ge=0;for(;++ge<U&&(de*=256);)te+=this[k+ge]*de;return de*=128,te>=de&&(te-=Math.pow(2,8*U)),te},a.prototype.readIntBE=function(k,U,K){k=k>>>0,U=U>>>0,K||N(k,U,this.length);let te=U,de=1,ge=this[k+--te];for(;te>0&&(de*=256);)ge+=this[k+--te]*de;return de*=128,ge>=de&&(ge-=Math.pow(2,8*U)),ge},a.prototype.readInt8=function(k,U){return k=k>>>0,U||N(k,1,this.length),this[k]&128?(255-this[k]+1)*-1:this[k]},a.prototype.readInt16LE=function(k,U){k=k>>>0,U||N(k,2,this.length);let K=this[k]|this[k+1]<<8;return K&32768?K|4294901760:K},a.prototype.readInt16BE=function(k,U){k=k>>>0,U||N(k,2,this.length);let K=this[k+1]|this[k]<<8;return K&32768?K|4294901760:K},a.prototype.readInt32LE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]|this[k+1]<<8|this[k+2]<<16|this[k+3]<<24},a.prototype.readInt32BE=function(k,U){return k=k>>>0,U||N(k,4,this.length),this[k]<<24|this[k+1]<<16|this[k+2]<<8|this[k+3]},a.prototype.readBigInt64LE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=this[k+4]+this[k+5]*2**8+this[k+6]*2**16+(K<<24);return(BigInt(te)<<BigInt(32))+BigInt(U+this[++k]*2**8+this[++k]*2**16+this[++k]*2**24)}),a.prototype.readBigInt64BE=yr(function(k){k=k>>>0,he(k,"offset");let U=this[k],K=this[k+7];(U===void 0||K===void 0)&&ue(k,this.length-8);let te=(U<<24)+this[++k]*2**16+this[++k]*2**8+this[++k];return(BigInt(te)<<BigInt(32))+BigInt(this[++k]*2**24+this[++k]*2**16+this[++k]*2**8+K)}),a.prototype.readFloatLE=function(k,U){return k=k>>>0,U||N(k,4,this.length),t.read(this,k,!0,23,4)},a.prototype.readFloatBE=function(k,U){return k=k>>>0,U||N(k,4,this.length),t.read(this,k,!1,23,4)},a.prototype.readDoubleLE=function(k,U){return k=k>>>0,U||N(k,8,this.length),t.read(this,k,!0,52,8)},a.prototype.readDoubleBE=function(k,U){return k=k>>>0,U||N(k,8,this.length),t.read(this,k,!1,52,8)};function q(k,U,K,te,de,ge){if(!a.isBuffer(k))throw new TypeError('"buffer" argument must be a Buffer instance');if(U>de||U<ge)throw new RangeError('"value" argument is out of bounds');if(K+te>k.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(k,U,K,te){if(k=+k,U=U>>>0,K=K>>>0,!te){let Ee=Math.pow(2,8*K)-1;q(this,k,U,K,Ee,0)}let de=1,ge=0;for(this[U]=k&255;++ge<K&&(de*=256);)this[U+ge]=k/de&255;return U+K},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(k,U,K,te){if(k=+k,U=U>>>0,K=K>>>0,!te){let Ee=Math.pow(2,8*K)-1;q(this,k,U,K,Ee,0)}let de=K-1,ge=1;for(this[U+de]=k&255;--de>=0&&(ge*=256);)this[U+de]=k/ge&255;return U+K},a.prototype.writeUint8=a.prototype.writeUInt8=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,1,255,0),this[U]=k&255,U+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,65535,0),this[U]=k&255,this[U+1]=k>>>8,U+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,65535,0),this[U]=k>>>8,this[U+1]=k&255,U+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,4294967295,0),this[U+3]=k>>>24,this[U+2]=k>>>16,this[U+1]=k>>>8,this[U]=k&255,U+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,4294967295,0),this[U]=k>>>24,this[U+1]=k>>>16,this[U+2]=k>>>8,this[U+3]=k&255,U+4};function W(k,U,K,te,de){le(U,te,de,k,K,7);let ge=Number(U&BigInt(4294967295));k[K++]=ge,ge=ge>>8,k[K++]=ge,ge=ge>>8,k[K++]=ge,ge=ge>>8,k[K++]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,Ee=Ee>>8,k[K++]=Ee,K}function J(k,U,K,te,de){le(U,te,de,k,K,7);let ge=Number(U&BigInt(4294967295));k[K+7]=ge,ge=ge>>8,k[K+6]=ge,ge=ge>>8,k[K+5]=ge,ge=ge>>8,k[K+4]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return k[K+3]=Ee,Ee=Ee>>8,k[K+2]=Ee,Ee=Ee>>8,k[K+1]=Ee,Ee=Ee>>8,k[K]=Ee,K+8}a.prototype.writeBigUInt64LE=yr(function(k,U=0){return W(this,k,U,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=yr(function(k,U=0){return J(this,k,U,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(k,U,K,te){if(k=+k,U=U>>>0,!te){let Wt=Math.pow(2,8*K-1);q(this,k,U,K,Wt-1,-Wt)}let de=0,ge=1,Ee=0;for(this[U]=k&255;++de<K&&(ge*=256);)k<0&&Ee===0&&this[U+de-1]!==0&&(Ee=1),this[U+de]=(k/ge>>0)-Ee&255;return U+K},a.prototype.writeIntBE=function(k,U,K,te){if(k=+k,U=U>>>0,!te){let Wt=Math.pow(2,8*K-1);q(this,k,U,K,Wt-1,-Wt)}let de=K-1,ge=1,Ee=0;for(this[U+de]=k&255;--de>=0&&(ge*=256);)k<0&&Ee===0&&this[U+de+1]!==0&&(Ee=1),this[U+de]=(k/ge>>0)-Ee&255;return U+K},a.prototype.writeInt8=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,1,127,-128),k<0&&(k=255+k+1),this[U]=k&255,U+1},a.prototype.writeInt16LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,32767,-32768),this[U]=k&255,this[U+1]=k>>>8,U+2},a.prototype.writeInt16BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,2,32767,-32768),this[U]=k>>>8,this[U+1]=k&255,U+2},a.prototype.writeInt32LE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,2147483647,-2147483648),this[U]=k&255,this[U+1]=k>>>8,this[U+2]=k>>>16,this[U+3]=k>>>24,U+4},a.prototype.writeInt32BE=function(k,U,K){return k=+k,U=U>>>0,K||q(this,k,U,4,2147483647,-2147483648),k<0&&(k=4294967295+k+1),this[U]=k>>>24,this[U+1]=k>>>16,this[U+2]=k>>>8,this[U+3]=k&255,U+4},a.prototype.writeBigInt64LE=yr(function(k,U=0){return W(this,k,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=yr(function(k,U=0){return J(this,k,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(k,U,K,te,de,ge){if(K+te>k.length)throw new RangeError("Index out of range");if(K<0)throw new RangeError("Index out of range")}function Y(k,U,K,te,de){return U=+U,K=K>>>0,de||V(k,U,K,4,34028234663852886e22,-34028234663852886e22),t.write(k,U,K,te,23,4),K+4}a.prototype.writeFloatLE=function(k,U,K){return Y(this,k,U,!0,K)},a.prototype.writeFloatBE=function(k,U,K){return Y(this,k,U,!1,K)};function F(k,U,K,te,de){return U=+U,K=K>>>0,de||V(k,U,K,8,17976931348623157e292,-17976931348623157e292),t.write(k,U,K,te,52,8),K+8}a.prototype.writeDoubleLE=function(k,U,K){return F(this,k,U,!0,K)},a.prototype.writeDoubleBE=function(k,U,K){return F(this,k,U,!1,K)},a.prototype.copy=function(k,U,K,te){if(!a.isBuffer(k))throw new TypeError("argument should be a Buffer");if(K||(K=0),!te&&te!==0&&(te=this.length),U>=k.length&&(U=k.length),U||(U=0),te>0&&te<K&&(te=K),te===K||k.length===0||this.length===0)return 0;if(U<0)throw new RangeError("targetStart out of bounds");if(K<0||K>=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),k.length-U<te-K&&(te=k.length-U+K);let de=te-K;return this===k&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(U,K,te):Uint8Array.prototype.set.call(k,this.subarray(K,te),U),de},a.prototype.fill=function(k,U,K,te){if(typeof k=="string"){if(typeof U=="string"?(te=U,U=0,K=this.length):typeof K=="string"&&(te=K,K=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!a.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(k.length===1){let ge=k.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(k=ge)}}else typeof k=="number"?k=k&255:typeof k=="boolean"&&(k=Number(k));if(U<0||this.length<U||this.length<K)throw new RangeError("Out of range index");if(K<=U)return this;U=U>>>0,K=K===void 0?this.length:K>>>0,k||(k=0);let de;if(typeof k=="number")for(de=U;de<K;++de)this[de]=k;else{let ge=a.isBuffer(k)?k:a.from(k,te),Ee=ge.length;if(Ee===0)throw new TypeError('The value "'+k+'" is invalid for argument "value"');for(de=0;de<K-U;++de)this[de+U]=ge[de%Ee]}return this};var Q={};function ie(k,U,K){Q[k]=class extends K{constructor(){super(),Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${k}]`,this.stack,delete this.name}get code(){return k}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${k}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(k){return k?`${k} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(k,U){return`The "${k}" argument must be of type number. Received type ${typeof U}`},TypeError),ie("ERR_OUT_OF_RANGE",function(k,U,K){let te=`The value of "${k}" is out of range.`,de=K;return Number.isInteger(K)&&Math.abs(K)>2**32?de=oe(String(K)):typeof K=="bigint"&&(de=String(K),(K>BigInt(2)**BigInt(32)||K<-(BigInt(2)**BigInt(32)))&&(de=oe(de)),de+="n"),te+=` It must be ${U}. Received ${de}`,te},RangeError);function oe(k){let U="",K=k.length,te=k[0]==="-"?1:0;for(;K>=te+4;K-=3)U=`_${k.slice(K-3,K)}${U}`;return`${k.slice(0,K)}${U}`}function Z(k,U,K){he(U,"offset"),(k[U]===void 0||k[U+K]===void 0)&&ue(U,k.length-(K+1))}function le(k,U,K,te,de,ge){if(k>K||k<U){let Ee=typeof U=="bigint"?"n":"",Wt;throw ge>3?U===0||U===BigInt(0)?Wt=`>= 0${Ee} and < 2${Ee} ** ${(ge+1)*8}${Ee}`:Wt=`>= -(2${Ee} ** ${(ge+1)*8-1}${Ee}) and < 2 ** ${(ge+1)*8-1}${Ee}`:Wt=`>= ${U}${Ee} and <= ${K}${Ee}`,new Q.ERR_OUT_OF_RANGE("value",Wt,k)}Z(te,de,ge)}function he(k,U){if(typeof k!="number")throw new Q.ERR_INVALID_ARG_TYPE(U,"number",k)}function ue(k,U,K){throw Math.floor(k)!==k?(he(k,K),new Q.ERR_OUT_OF_RANGE(K||"offset","an integer",k)):U<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(K||"offset",`>= ${K?1:0} and <= ${U}`,k)}var Se=/[^+/0-9A-Za-z-_]/g;function pe(k){if(k=k.split("=")[0],k=k.trim().replace(Se,""),k.length<2)return"";for(;k.length%4!==0;)k=k+"=";return k}function Ae(k,U){U=U||1/0;let K,te=k.length,de=null,ge=[];for(let Ee=0;Ee<te;++Ee){if(K=k.charCodeAt(Ee),K>55295&&K<57344){if(!de){if(K>56319){(U-=3)>-1&&ge.push(239,191,189);continue}else if(Ee+1===te){(U-=3)>-1&&ge.push(239,191,189);continue}de=K;continue}if(K<56320){(U-=3)>-1&&ge.push(239,191,189),de=K;continue}K=(de-55296<<10|K-56320)+65536}else de&&(U-=3)>-1&&ge.push(239,191,189);if(de=null,K<128){if((U-=1)<0)break;ge.push(K)}else if(K<2048){if((U-=2)<0)break;ge.push(K>>6|192,K&63|128)}else if(K<65536){if((U-=3)<0)break;ge.push(K>>12|224,K>>6&63|128,K&63|128)}else if(K<1114112){if((U-=4)<0)break;ge.push(K>>18|240,K>>12&63|128,K>>6&63|128,K&63|128)}else throw new Error("Invalid code point")}return ge}function Ot(k){let U=[];for(let K=0;K<k.length;++K)U.push(k.charCodeAt(K)&255);return U}function ai(k,U){let K,te,de,ge=[];for(let Ee=0;Ee<k.length&&!((U-=2)<0);++Ee)K=k.charCodeAt(Ee),te=K>>8,de=K%256,ge.push(de),ge.push(te);return ge}function Lr(k){return e.toByteArray(pe(k))}function ds(k,U,K,te){let de;for(de=0;de<te&&!(de+K>=U.length||de>=k.length);++de)U[de+K]=k[de];return de}function Ye(k,U){return k instanceof U||k!=null&&k.constructor!=null&&k.constructor.name!=null&&k.constructor.name===U.name}function ar(k){return k!==k}var qr=function(){let k="0123456789abcdef",U=new Array(256);for(let K=0;K<16;++K){let te=K*16;for(let de=0;de<16;++de)U[te+de]=k[K]+k[de]}return U}();function yr(k){return typeof BigInt>"u"?Gt:k}function Gt(){throw new Error("BigInt not supported")}}),nF=Xt((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),iF=Xt(r=>{"use strict";var e=il(),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}),oF=Xt(r=>{"use strict";var{Buffer:e}=s5()||{},{Encoding:t}=iF(),n=nF(),i=class extends t{constructor(a){super({...a,format:"buffer"})}createViewTranscoder(){return new s({encode:this.encode,decode:a=>this.decode(e.from(a.buffer,a.byteOffset,a.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},s=class extends t{constructor(a){super({...a,format:"view"})}createBufferTranscoder(){return new i({encode:a=>{let d=this.encode(a);return e.from(d.buffer,d.byteOffset,d.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends t{constructor(a){super({...a,format:"utf8"})}createBufferTranscoder(){return new i({encode:a=>e.from(this.encode(a),"utf8"),decode:a=>this.decode(a.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:a,textDecoder:d}=n();return new s({encode:l=>a.encode(this.encode(l)),decode:l=>this.decode(d.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=s,r.UTF8Format=o}),sfe=Xt(r=>{"use strict";var{Buffer:e}=s5()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=nF()(),{BufferFormat:i,ViewFormat:s,UTF8Format:o}=oF(),a=d=>d;r.utf8=new o({encode:function(d){return e.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?n.decode(d):String(d)},decode:a,name:"utf8",createViewTranscoder(){return new s({encode:function(d){return ArrayBuffer.isView(d)?d:t.encode(d)},decode:function(d){return n.decode(d)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:function(d){return d.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:a,name:"buffer",createViewTranscoder(){return new s({encode:function(d){return ArrayBuffer.isView(d)?d:e.from(String(d),"utf8")},decode:function(d){return e.from(d.buffer,d.byteOffset,d.byteLength)},name:`${this.name}+view`})}}),r.view=new s({encode:function(d){return ArrayBuffer.isView(d)?d:t.encode(d)},decode:a,name:"view",createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:a,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"hex")},decode:function(d){return d.toString("hex")},name:"hex"}),r.base64=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"base64")},decode:function(d){return d.toString("base64")},name:"base64"})}),afe=Xt(r=>{"use strict";var e=il(),t=sfe(),{Encoding:n}=iF(),{BufferFormat:i,ViewFormat:s,UTF8Format:o}=oF(),a=Symbol("formats"),d=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),c=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[d]=new Map,this[a]=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[d].values()))}encoding(y){let v=this[d].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=p[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:b}=v;if(!this[a].has(b))if(this[a].has("view"))v=v.createViewTranscoder();else if(this[a].has("buffer"))v=v.createBufferTranscoder();else if(this[a].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let T of[y,w,v.name,v.commonName])this[d].set(T,v)}return v}};r.Transcoder=c;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 s({...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 h={binary:t.buffer,"utf-8":t.utf8},p={...t,...h},m=0}),cfe=Xt((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 s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,f||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function d(){this._events=new i,this._eventsCount=0}d.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)t.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},d.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,h=u.length,p=new Array(h);f<h;f++)p[f]=u[f].fn;return p},d.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},d.prototype.emit=function(l,c,u,f,h,p){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,b;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,c),!0;case 3:return y.fn.call(y.context,c,u),!0;case 4:return y.fn.call(y.context,c,u,f),!0;case 5:return y.fn.call(y.context,c,u,f,h),!0;case 6:return y.fn.call(y.context,c,u,f,h,p),!0}for(b=1,w=new Array(v-1);b<v;b++)w[b-1]=arguments[b];y.fn.apply(y.context,w)}else{var T=y.length,D;for(b=0;b<T;b++)switch(y[b].once&&this.removeListener(l,y[b].fn,void 0,!0),v){case 1:y[b].fn.call(y[b].context);break;case 2:y[b].fn.call(y[b].context,c);break;case 3:y[b].fn.call(y[b].context,c,u);break;case 4:y[b].fn.call(y[b].context,c,u,f);break;default:if(!w)for(D=1,w=new Array(v-1);D<v;D++)w[D-1]=arguments[D];y[b].fn.apply(y[b].context,w)}}return!0},d.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},d.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},d.prototype.removeListener=function(l,c,u,f){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return a(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!f||p.once)&&(!u||p.context===u)&&a(this,h);else{for(var m=0,y=[],v=p.length;m<v;m++)(p[m].fn!==c||f&&!p[m].once||u&&p[m].context!==u)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:a(this,h)}return this},d.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)}),dfe=Xt((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),fE=Xt(r=>{"use strict";var e=dfe();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(s,o){t=function(a,d){a?o(a):s(d)}});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))})}}),a5=Xt(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:{}}}),Wp=Xt(r=>{"use strict";var{fromCallback:e}=fE(),t=il(),{getOptions:n,getCallback:i}=a5(),s=Symbol("promise"),o=Symbol("callback"),a=Symbol("working"),d=Symbol("handleOne"),l=Symbol("handleMany"),c=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),b=Symbol("abortOnClose"),T=Symbol("legacy"),D=Symbol("keys"),I=Symbol("values"),M=Symbol("limit"),C=Symbol("count"),z=Object.freeze({}),L=()=>{},B=!1,H=class{constructor(P,_,S){if(typeof P!="object"||P===null){let A=P===null?"null":typeof P;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof _!="object"||_===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[a]=!1,this[h]=!1,this[c]=!1,this[o]=null,this[d]=this[d].bind(this),this[l]=this[l].bind(this),this[p]=this[p].bind(this),this[v]=_[v],this[w]=_[w],this[T]=S,this[M]=Number.isInteger(_.limit)&&_.limit>=0?_.limit:1/0,this[C]=0,this[b]=!!_.abortOnClose,this.db=P,this.db.attachResource(this),this.nextTick=P.nextTick}get count(){return this[C]}get limit(){return this[M]}next(P){let _;if(P===void 0)_=new Promise((S,A)=>{P=(N,q,W)=>{N?A(N):this[T]?q===void 0&&W===void 0?S():S([q,W]):S(q)}});else if(typeof P!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(P,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(P,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[a]=!0,this[o]=P,this[C]>=this[M]?this.nextTick(this[d],null):this._next(this[d])),_}_next(P){this.nextTick(P)}nextv(P,_,S){return S=i(_,S),S=e(S,s),_=n(_,z),Number.isInteger(P)?(this[h]?this.nextTick(S,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(S,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(P<1&&(P=1),this[M]<1/0&&(P=Math.min(P,this[M]-this[C])),this[a]=!0,this[o]=S,P<=0?this.nextTick(this[l],null,[]):this._nextv(P,_,this[l])),S[s]):(this.nextTick(S,new TypeError("The first argument 'size' must be an integer")),S[s])}_nextv(P,_,S){let A=[],N=(q,W,J)=>{if(q)return S(q);if(this[T]?W===void 0&&J===void 0:W===void 0)return S(null,A);A.push(this[T]?[W,J]:W),A.length===P?S(null,A):this._next(N)};this._next(N)}all(P,_){return _=i(P,_),_=e(_,s),P=n(P,z),this[h]?this.nextTick(_,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[a]?this.nextTick(_,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[a]=!0,this[o]=_,this[c]=!0,this[C]>=this[M]?this.nextTick(this[l],null,[]):this._all(P,this[l])),_[s]}_all(P,_){let S=this[C],A=[],N=()=>{let W=this[M]<1/0?Math.min(1e3,this[M]-S):1e3;W<=0?this.nextTick(_,null,A):this._nextv(W,z,q)},q=(W,J)=>{W?_(W):J.length===0?_(null,A):(A.push.apply(A,J),S+=J.length,N())};N()}[u](){let P=this[o];return this[b]&&P===null?L:(this[a]=!1,this[o]=null,this[h]&&this._close(this[p]),P)}[f](P,_,S){this[c]?this.close(P.bind(null,_,S)):P(_,S)}seek(P,_){if(_=n(_,z),!this[h]){if(this[a])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let S=this.db.keyEncoding(_.keyEncoding||this[v]),A=S.format;_.keyEncoding!==A&&(_={..._,keyEncoding:A});let N=this.db.prefixKey(S.encode(P),A);this._seek(N,_)}}}_seek(P,_){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(P){return P=e(P,s),this[m]?this.nextTick(P):this[h]?this[y].push(P):(this[h]=!0,this[y].push(P),this[a]?this[b]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),P[s]}_close(P){this.nextTick(P)}[p](){this[m]=!0,this.db.detachResource(this);let P=this[y];this[y]=[];for(let _ of P)_()}async*[Symbol.asyncIterator](){try{let P;for(;(P=await this.next())!==void 0;)yield P}finally{this[m]||await this.close()}}},ee=class extends H{constructor(P,_){super(P,_,!0),this[D]=_.keys!==!1,this[I]=_.values!==!1}[d](P,_,S){let A=this[u]();if(P)return A(P);try{_=this[D]&&_!==void 0?this[v].decode(_):void 0,S=this[I]&&S!==void 0?this[w].decode(S):void 0}catch(N){return A(new E("entry",N))}_===void 0&&S===void 0||this[C]++,A(null,_,S)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A of _){let N=A[0],q=A[1];A[0]=this[D]&&N!==void 0?this[v].decode(N):void 0,A[1]=this[I]&&q!==void 0?this[w].decode(q):void 0}}catch(A){return this[f](S,new E("entries",A))}this[C]+=_.length,this[f](S,null,_)}end(P){return!B&&typeof console<"u"&&(B=!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(P)}},R=class extends H{constructor(P,_){super(P,_,!1)}[d](P,_){let S=this[u]();if(P)return S(P);try{_=_!==void 0?this[v].decode(_):void 0}catch(A){return S(new E("key",A))}_!==void 0&&this[C]++,S(null,_)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A=0;A<_.length;A++){let N=_[A];_[A]=N!==void 0?this[v].decode(N):void 0}}catch(A){return this[f](S,new E("keys",A))}this[C]+=_.length,this[f](S,null,_)}},$=class extends H{constructor(P,_){super(P,_,!1)}[d](P,_){let S=this[u]();if(P)return S(P);try{_=_!==void 0?this[w].decode(_):void 0}catch(A){return S(new E("value",A))}_!==void 0&&this[C]++,S(null,_)}[l](P,_){let S=this[u]();if(P)return this[f](S,P);try{for(let A=0;A<_.length;A++){let N=_[A];_[A]=N!==void 0?this[w].decode(N):void 0}}catch(A){return this[f](S,new E("values",A))}this[C]+=_.length,this[f](S,null,_)}},E=class extends t{constructor(P,_){super(`Iterator could not decode ${P}`,{code:"LEVEL_DECODE_ERROR",cause:_})}};for(let P of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,P.split(" ")[0],{get(){throw new t(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=v,ee.valueEncoding=w,r.AbstractIterator=ee,r.AbstractKeyIterator=R,r.AbstractValueIterator=$}),lfe=Xt(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=Wp(),n=Symbol("iterator"),i=Symbol("callback"),s=Symbol("handleOne"),o=Symbol("handleMany"),a=class extends e{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!0,values:!1}),this[s]=this[s].bind(this),this[o]=this[o].bind(this)}},d=class extends t{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!1,values:!0}),this[s]=this[s].bind(this),this[o]=this[o].bind(this)}};for(let l of[a,d]){let c=l===a,u=c?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[s])},l.prototype[s]=function(f,h,p){let m=this[i];f?m(f):m(null,c?h:p)},l.prototype._nextv=function(f,h,p){this[i]=p,this[n].nextv(f,h,this[o])},l.prototype._all=function(f,h){this[i]=h,this[n].all(f,this[o])},l.prototype[o]=function(f,h){let p=this[i];f?p(f):p(null,h.map(u))},l.prototype._seek=function(f,h){this[n].seek(f,h)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=a,r.DefaultValueIterator=d}),ufe=Xt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=Wp(),i=il(),s=Symbol("nut"),o=Symbol("undefer"),a=Symbol("factory"),d=class extends e{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.iterator(f),this.db.defer(()=>this[o]())}},l=class extends t{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.keys(f),this.db.defer(()=>this[o]())}},c=class extends n{constructor(u,f){super(u,f),this[s]=null,this[a]=()=>u.values(f),this.db.defer(()=>this[o]())}};for(let u of[d,l,c])u.prototype[o]=function(){this.db.status==="open"&&(this[s]=this[a]())},u.prototype._next=function(f){this[s]!==null?this[s].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,h,p){this[s]!==null?this[s].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,h){this[s]!==null?this[s].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,h){this[s]!==null?this[s]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},u.prototype._close=function(f){this[s]!==null?this[s].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=d,r.DeferredKeyIterator=l,r.DeferredValueIterator=c}),sF=Xt(r=>{"use strict";var{fromCallback:e}=fE(),t=il(),{getCallback:n,getOptions:i}=a5(),s=Symbol("promise"),o=Symbol("status"),a=Symbol("operations"),d=Symbol("finishClose"),l=Symbol("closeCallbacks"),c=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[a]=[],this[l]=[],this[o]="open",this[d]=this[d].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[a].length}put(u,f,h){if(this[o]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,v=m.keyEncoding(h&&h.keyEncoding),w=m.valueEncoding(h&&h.valueEncoding),b=v.format;h={...h,keyEncoding:b,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let T=m.prefixKey(v.encode(u),b),D=w.encode(f);return this._put(T,D,h),this[a].push({...y,type:"put",key:u,value:f}),this}_put(u,f,h){}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 h=this.db._checkKey(u);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(u),v),f),this[a].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[a]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,s),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,h=>{this[o]="closing",this[l].push(()=>f(h)),h||this.db.emit("batch",this[a]),this._close(this[d])})),f[s]}_write(u,f){}close(u){return u=e(u,s),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[d]))),u[s]}_close(u){this.nextTick(u)}[d](){this[o]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=c}),ffe=Xt(r=>{"use strict";var{AbstractChainedBatch:e}=sF(),t=il(),n=Symbol("encoded"),i=class extends e{constructor(s){super(s),this[n]=[]}_put(s,o,a){this[n].push({...a,type:"put",key:s,value:o})}_del(s,o){this[n].push({...o,type:"del",key:s})}_clear(){this[n]=[]}_write(s,o){this.db.status==="opening"?this.db.defer(()=>this._write(s,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],s,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}),hfe=Xt((r,e)=>{"use strict";var t=il(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(s,o){let a={};for(let d in s)if(n.call(s,d)&&!(d==="keyEncoding"||d==="valueEncoding")){if(d==="start"||d==="end")throw new t(`The legacy range option '${d}' has been removed`,{code:"LEVEL_LEGACY"});if(d==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(d)?a[d]=o.encode(s[d]):a[d]=s[d]}return a.reverse=!!a.reverse,a.limit=Number.isInteger(a.limit)&&a.limit>=0?a.limit:-1,a}}),aF=Xt((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))}),pfe=Xt((r,e)=>{"use strict";var t=aF();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),mfe=Xt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=Wp(),i=Symbol("unfix"),s=Symbol("iterator"),o=Symbol("handleOne"),a=Symbol("handleMany"),d=Symbol("callback"),l=class extends e{constructor(f,h,p,m){super(f,h),this[s]=p,this[i]=m,this[o]=this[o].bind(this),this[a]=this[a].bind(this),this[d]=null}[o](f,h,p){let m=this[d];if(f)return m(f);h!==void 0&&(h=this[i](h)),m(f,h,p)}[a](f,h){let p=this[d];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[i](y))}p(f,h)}},c=class extends t{constructor(f,h,p,m){super(f,h),this[s]=p,this[i]=m,this[o]=this[o].bind(this),this[a]=this[a].bind(this),this[d]=null}[o](f,h){let p=this[d];if(f)return p(f);h!==void 0&&(h=this[i](h)),p(f,h)}[a](f,h){let p=this[d];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[i](y))}p(f,h)}},u=class extends n{constructor(f,h,p){super(f,h),this[s]=p}};for(let f of[l,c])f.prototype._next=function(h){this[d]=h,this[s].next(this[o])},f.prototype._nextv=function(h,p,m){this[d]=m,this[s].nextv(h,p,this[a])},f.prototype._all=function(h,p){this[d]=p,this[s].all(h,this[a])};for(let f of[u])f.prototype._next=function(h){this[s].next(h)},f.prototype._nextv=function(h,p,m){this[s].nextv(h,p,m)},f.prototype._all=function(h,p){this[s].all(h,p)};for(let f of[l,c,u])f.prototype._seek=function(h,p){this[s].seek(h,p)},f.prototype._close=function(h){this[s].close(h)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=c,r.AbstractSublevelValueIterator=u}),yfe=Xt((r,e)=>{"use strict";var t=il(),{Buffer:n}=s5()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:s,AbstractSublevelValueIterator:o}=mfe(),a=Symbol("prefix"),d=Symbol("upperBound"),l=Symbol("prefixRange"),c=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:b}){class T extends b{static defaults(I){if(typeof I=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(I&&I.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return I==null?h:I.separator?I:{...I,separator:"!"}}constructor(I,M,C){let{separator:z,manifest:L,...B}=T.defaults(C);M=w(M,z);let H=z.charCodeAt(0)+1,ee=I[c]||I;if(!f.encode(M).every(E=>E>H&&E<127))throw new t(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,L),B);let R=(I.prefix||"")+z+M+z,$=R.slice(0,-1)+String.fromCharCode(H);this[c]=ee,this[a]=new y(R),this[d]=new y($),this[u]=new v,this.nextTick=ee.nextTick}prefixKey(I,M){if(M==="utf8")return this[a].utf8+I;if(I.byteLength===0)return this[a][M];if(M==="view"){let C=this[a].view,z=new Uint8Array(C.byteLength+I.byteLength);return z.set(C,0),z.set(I,C.byteLength),z}else{let C=this[a].buffer;return n.concat([C,I],C.byteLength+I.byteLength)}}[l](I,M){I.gte!==void 0?I.gte=this.prefixKey(I.gte,M):I.gt!==void 0?I.gt=this.prefixKey(I.gt,M):I.gte=this[a][M],I.lte!==void 0?I.lte=this.prefixKey(I.lte,M):I.lt!==void 0?I.lt=this.prefixKey(I.lt,M):I.lte=this[d][M]}get prefix(){return this[a].utf8}get db(){return this[c]}_open(I,M){this[c].open({passive:!0},M)}_put(I,M,C,z){this[c].put(I,M,C,z)}_get(I,M,C){this[c].get(I,M,C)}_getMany(I,M,C){this[c].getMany(I,M,C)}_del(I,M,C){this[c].del(I,M,C)}_batch(I,M,C){this[c].batch(I,M,C)}_clear(I,M){this[l](I,I.keyEncoding),this[c].clear(I,M)}_iterator(I){this[l](I,I.keyEncoding);let M=this[c].iterator(I),C=this[u].get(this[a].utf8.length,I.keyEncoding);return new i(this,I,M,C)}_keys(I){this[l](I,I.keyEncoding);let M=this[c].keys(I),C=this[u].get(this[a].utf8.length,I.keyEncoding);return new s(this,I,M,C)}_values(I){this[l](I,I.keyEncoding);let M=this[c].values(I);return new o(this,I,M)}}return{AbstractSublevel:T}};var p=function(b,T){return{...b.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...T,encodings:{utf8:m(b,"utf8"),buffer:m(b,"buffer"),view:m(b,"view")}}},m=function(b,T){return b.supports.encodings[T]?b.keyEncoding(T).name===T:!1},y=class{constructor(b){this.utf8=b,this.view=f.encode(b),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(b,T){let D=this.cache.get(T);return D===void 0&&(T==="view"?D=(function(I,M){return M.subarray(I)}).bind(null,b):D=(function(I,M){return M.slice(I)}).bind(null,b),this.cache.set(T,D)),D}},w=function(b,T){let D=0,I=b.length;for(;D<I&&b[D]===T;)D++;for(;I>D&&b[I-1]===T;)I--;return b.slice(D,I)}}),Uz=Xt(r=>{"use strict";var{supports:e}=nfe(),{Transcoder:t}=afe(),{EventEmitter:n}=cfe(),{fromCallback:i}=fE(),s=il(),{AbstractIterator:o}=Wp(),{DefaultKeyIterator:a,DefaultValueIterator:d}=lfe(),{DeferredIterator:l,DeferredKeyIterator:c,DeferredValueIterator:u}=ufe(),{DefaultChainedBatch:f}=ffe(),{getCallback:h,getOptions:p}=a5(),m=hfe(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),b=Symbol("closeResources"),T=Symbol("operations"),D=Symbol("undefer"),I=Symbol("deferOpen"),M=Symbol("options"),C=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),B=Symbol("keyEncoding"),H=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(_,S){if(super(),typeof _!="object"||_===null)throw new TypeError("The first argument 'manifest' must be an object");S=p(S);let{keyEncoding:A,valueEncoding:N,passive:q,...W}=S;this[w]=new Set,this[T]=[],this[I]=!0,this[M]=W,this[C]="opening",this.supports=e(_,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:_.snapshots!==!1,permanence:_.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:_.encodings||{},events:Object.assign({},_.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(P(this)),this[B]=this[L].encoding(A||"utf8"),this[H]=this[L].encoding(N||"utf8");for(let J of this[L].encodings())this.supports.encodings[J.commonName]||(this.supports.encodings[J.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[H].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[I]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(_){return this[L].encoding(_??this[B])}valueEncoding(_){return this[L].encoding(_??this[H])}open(_,S){S=h(_,S),S=i(S,y),_={...this[M],...p(_)},_.createIfMissing=_.createIfMissing!==!1,_.errorIfExists=!!_.errorIfExists;let A=N=>{this[C]==="closing"||this[C]==="opening"?this.once(v,N?()=>A(N):A):this[C]!=="open"?S(new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:N})):S()};return _.passive?this[C]==="opening"?this.once(v,A):this.nextTick(A):this[C]==="closed"||this[I]?(this[I]=!1,this[C]="opening",this.emit("opening"),this._open(_,N=>{if(N){this[C]="closed",this[b](()=>{this.emit(v),A(N)}),this[D]();return}this[C]="open",this[D](),this.emit(v),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),A()})):this[C]==="open"?this.nextTick(A):this.once(v,()=>this.open(_,S)),S[y]}_open(_,S){this.nextTick(S)}close(_){_=i(_,y);let S=A=>{this[C]==="opening"||this[C]==="closing"?this.once(v,A?S(A):S):this[C]!=="closed"?_(new s("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):_()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let A=N=>{this[C]="open",this[D](),this.emit(v),S(N)};this[b](()=>{this._close(N=>{if(N)return A(N);this[C]="closed",this[D](),this.emit(v),this[C]==="closed"&&this.emit("closed"),S()})})}else this[C]==="closed"?this.nextTick(S):this.once(v,()=>this.close(_));return _[y]}[b](_){if(this[w].size===0)return this.nextTick(_);let S=this[w].size,A=!0,N=()=>{--S===0&&(A?this.nextTick(_):_())};for(let q of this[w])q.close(N);A=!1,this[w].clear()}_close(_){this.nextTick(_)}get(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].entry),this[C]==="opening")return this.defer(()=>this.get(_,S,A)),A[y];if(E(this,A))return A[y];let N=this._checkKey(_);if(N)return this.nextTick(A,N),A[y];let q=this.keyEncoding(S.keyEncoding),W=this.valueEncoding(S.valueEncoding),J=q.format,V=W.format;return(S.keyEncoding!==J||S.valueEncoding!==V)&&(S=Object.assign({},S,{keyEncoding:J,valueEncoding:V})),this._get(this.prefixKey(q.encode(_),J),S,(Y,F)=>{if(Y)return(Y.code==="LEVEL_NOT_FOUND"||Y.notFound||/NotFound/i.test(Y))&&(Y.code||(Y.code="LEVEL_NOT_FOUND"),Y.notFound||(Y.notFound=!0),Y.status||(Y.status=404)),A(Y);try{F=W.decode(F)}catch(Q){return A(new s("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,F)}),A[y]}_get(_,S,A){this.nextTick(A,new Error("NotFound"))}getMany(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].entry),this[C]==="opening")return this.defer(()=>this.getMany(_,S,A)),A[y];if(E(this,A))return A[y];if(!Array.isArray(_))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(_.length===0)return this.nextTick(A,null,[]),A[y];let N=this.keyEncoding(S.keyEncoding),q=this.valueEncoding(S.valueEncoding),W=N.format,J=q.format;(S.keyEncoding!==W||S.valueEncoding!==J)&&(S=Object.assign({},S,{keyEncoding:W,valueEncoding:J}));let V=new Array(_.length);for(let Y=0;Y<_.length;Y++){let F=_[Y],Q=this._checkKey(F);if(Q)return this.nextTick(A,Q),A[y];V[Y]=this.prefixKey(N.encode(F),W)}return this._getMany(V,S,(Y,F)=>{if(Y)return A(Y);try{for(let Q=0;Q<F.length;Q++)F[Q]!==void 0&&(F[Q]=q.decode(F[Q]))}catch(Q){return A(new s(`Could not decode one or more of ${F.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,F)}),A[y]}_getMany(_,S,A){this.nextTick(A,null,new Array(_.length).fill(void 0))}put(_,S,A,N){if(N=h(A,N),N=i(N,y),A=p(A,this[z].entry),this[C]==="opening")return this.defer(()=>this.put(_,S,A,N)),N[y];if(E(this,N))return N[y];let q=this._checkKey(_)||this._checkValue(S);if(q)return this.nextTick(N,q),N[y];let W=this.keyEncoding(A.keyEncoding),J=this.valueEncoding(A.valueEncoding),V=W.format,Y=J.format;(A.keyEncoding!==V||A.valueEncoding!==Y)&&(A=Object.assign({},A,{keyEncoding:V,valueEncoding:Y}));let F=this.prefixKey(W.encode(_),V),Q=J.encode(S);return this._put(F,Q,A,ie=>{if(ie)return N(ie);this.emit("put",_,S),N()}),N[y]}_put(_,S,A,N){this.nextTick(N)}del(_,S,A){if(A=h(S,A),A=i(A,y),S=p(S,this[z].key),this[C]==="opening")return this.defer(()=>this.del(_,S,A)),A[y];if(E(this,A))return A[y];let N=this._checkKey(_);if(N)return this.nextTick(A,N),A[y];let q=this.keyEncoding(S.keyEncoding),W=q.format;return S.keyEncoding!==W&&(S=Object.assign({},S,{keyEncoding:W})),this._del(this.prefixKey(q.encode(_),W),S,J=>{if(J)return A(J);this.emit("del",_),A()}),A[y]}_del(_,S,A){this.nextTick(A)}batch(_,S,A){if(!arguments.length){if(this[C]==="opening")return new f(this);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof _=="function"?A=_:A=h(S,A),A=i(A,y),S=p(S,this[z].empty),this[C]==="opening")return this.defer(()=>this.batch(_,S,A)),A[y];if(E(this,A))return A[y];if(!Array.isArray(_))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(_.length===0)return this.nextTick(A),A[y];let N=new Array(_.length),{keyEncoding:q,valueEncoding:W,...J}=S;for(let V=0;V<_.length;V++){if(typeof _[V]!="object"||_[V]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let Y=Object.assign({},_[V]);if(Y.type!=="put"&&Y.type!=="del")return this.nextTick(A,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),A[y];let F=this._checkKey(Y.key);if(F)return this.nextTick(A,F),A[y];let Q=Y.sublevel!=null?Y.sublevel:this,ie=Q.keyEncoding(Y.keyEncoding||q),oe=ie.format;if(Y.key=Q.prefixKey(ie.encode(Y.key),oe),Y.keyEncoding=oe,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(A,Z),A[y];let le=Q.valueEncoding(Y.valueEncoding||W);Y.value=le.encode(Y.value),Y.valueEncoding=le.format}Q!==this&&(Y.sublevel=null),N[V]=Y}return this._batch(N,J,V=>{if(V)return A(V);this.emit("batch",_),A()}),A[y]}_batch(_,S,A){this.nextTick(A)}sublevel(_,S){return this._sublevel(_,$.defaults(S))}_sublevel(_,S){return new $(this,_,S)}prefixKey(_,S){return _}clear(_,S){if(S=h(_,S),S=i(S,y),_=p(_,this[z].empty),this[C]==="opening")return this.defer(()=>this.clear(_,S)),S[y];if(E(this,S))return S[y];let A=_,N=this.keyEncoding(_.keyEncoding);return _=m(_,N),_.keyEncoding=N.format,_.limit===0?this.nextTick(S):this._clear(_,q=>{if(q)return S(q);this.emit("clear",A),S()}),S[y]}_clear(_,S){this.nextTick(S)}iterator(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_.keys=_.keys!==!1,_.values=_.values!==!1,_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new l(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(_)}_iterator(_){return new o(this,_)}keys(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new c(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(_)}_keys(_){return new a(this,_)}values(_){let S=this.keyEncoding(_&&_.keyEncoding),A=this.valueEncoding(_&&_.valueEncoding);if(_=m(_,S),_[o.keyEncoding]=S,_[o.valueEncoding]=A,_.keyEncoding=S.format,_.valueEncoding=A.format,this[C]==="opening")return new u(this,_);if(this[C]!=="open")throw new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(_)}_values(_){return new d(this,_)}defer(_){if(typeof _!="function")throw new TypeError("The first argument must be a function");this[T].push(_)}[D](){if(this[T].length===0)return;let _=this[T];this[T]=[];for(let S of _)S()}attachResource(_){if(typeof _!="object"||_===null||typeof _.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(_)}detachResource(_){this[w].delete(_)}_chainedBatch(){return new f(this)}_checkKey(_){if(_==null)return new s("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(_){if(_==null)return new s("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=pfe();var{AbstractSublevel:$}=yfe()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=$;var E=function(_,S){return _[C]!=="open"?(_.nextTick(S,new s("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},P=function(_){return Object.keys(_.supports.encodings).filter(S=>!!_.supports.encodings[S])}}),cF=Xt(r=>{"use strict";r.AbstractLevel=Uz().AbstractLevel,r.AbstractSublevel=Uz().AbstractSublevel,r.AbstractIterator=Wp().AbstractIterator,r.AbstractKeyIterator=Wp().AbstractKeyIterator,r.AbstractValueIterator=Wp().AbstractValueIterator,r.AbstractChainedBatch=sF().AbstractChainedBatch}),gfe=Xt((r,e)=>{e.exports=n;var t=aF();function n(i,s,o){if(typeof s!="number")throw new Error("second argument must be a Number");let a,d,l,c,u,f=!0,h;Array.isArray(i)?(a=[],l=d=i.length):(c=Object.keys(i),a={},l=d=c.length);function p(y){function v(){o&&o(y,a),o=null}f?t(v):v()}function m(y,v,w){if(a[y]=w,v&&(u=!0),--l===0||v)p(v);else if(!u&&h<d){let b;c?(b=c[h],h+=1,i[b](function(T,D){m(b,T,D)})):(b=h,h+=1,i[b](function(T,D){m(b,T,D)}))}}h=s,l?c?c.some(function(y,v){return i[y](function(w,b){m(y,w,b)}),v===s-1}):i.some(function(y,v){return y(function(w,b){m(v,w,b)}),v===s-1}):p(null),f=!1}}),dF=Xt((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,s=t.gte===void 0,o=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,s,o):n!==void 0?IDBKeyRange.lowerBound(n,s):i!==void 0?IDBKeyRange.upperBound(i,o):null}}),lF=Xt((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)}}),wfe=Xt(r=>{"use strict";var{AbstractIterator:e}=cF(),t=dF(),n=lF(),i=Symbol("cache"),s=Symbol("finished"),o=Symbol("options"),a=Symbol("currentOptions"),d=Symbol("position"),l=Symbol("location"),c=Symbol("first"),u={},f=class extends e{constructor(p,m,y){super(p,y),this[i]=[],this[s]=this.limit===0,this[o]=y,this[a]={...y},this[d]=void 0,this[l]=m,this[c]=!0}_nextv(p,m,y){if(this[c]=!1,this[s])return this.nextTick(y,null,[]);if(this[i].length>0)return p=Math.min(p,this[i].length),this.nextTick(y,null,this[i].splice(0,p));this[d]!==void 0&&(this[o].reverse?(this[a].lt=this[d],this[a].lte=void 0):(this[a].gt=this[d],this[a].gte=void 0));let v;try{v=t(this[a])}catch{return this[s]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),b=w.objectStore(this[l]),T=[];if(this[o].reverse){let D=!this[o].values&&b.openKeyCursor?"openKeyCursor":"openCursor";b[D](v,"prev").onsuccess=I=>{let M=I.target.result;if(M){let{key:C,value:z}=M;this[d]=C,T.push([this[o].keys&&C!==void 0?n(C):void 0,this[o].values&&z!==void 0?n(z):void 0]),T.length<p?M.continue():h(w)}else this[s]=!0}}else{let D,I,M=()=>{if(D===void 0||I===void 0)return;let C=Math.max(D.length,I.length);C===0||p===1/0?this[s]=!0:this[d]=D[C-1],T.length=C;for(let z=0;z<C;z++){let L=D[z],B=I[z];T[z]=[this[o].keys&&L!==void 0?n(L):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(w)};this[o].keys||p<1/0?b.getAllKeys(v,p<1/0?p:void 0).onsuccess=C=>{D=C.target.result,M()}:(D=[],this.nextTick(M)),this[o].values?b.getAll(v,p<1/0?p:void 0).onsuccess=C=>{I=C.target.result,M()}:(I=[],this.nextTick(M))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,T),y=null}}_next(p){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(p,null,m,y)}else if(this[s])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[c]&&(this[c]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return p(y);this[i]=v,this._next(p)})}}_all(p,m){this[c]=!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,b)=>{if(w)return m(w);y.length>0&&(b=y.concat(b)),m(null,b)})}_seek(p,m){this[c]=!0,this[i]=[],this[s]=!1,this[d]=void 0,this[a]={...this[o]};let y;try{y=t(this[o])}catch{this[s]=!0;return}y!==null&&!y.includes(p)?this[s]=!0:this[o].reverse?this[a].lte=p:this[a].gte=p}};r.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),vfe=Xt((r,e)=>{"use strict";e.exports=function(t,n,i,s,o){if(s.limit===0)return t.nextTick(o);let a=t.db.transaction([n],"readwrite"),d=a.objectStore(n),l=0;a.oncomplete=function(){o()},a.onabort=function(){o(a.error||new Error("aborted by user"))};let c=d.openKeyCursor?"openKeyCursor":"openCursor",u=s.reverse?"prev":"next";d[c](i,u).onsuccess=function(f){let h=f.target.result;h&&(d.delete(h.key).onsuccess=function(){(s.limit<=0||++l<s.limit)&&h.continue()})}}}),bfe=Xt(r=>{"use strict";var{AbstractLevel:e}=cF(),t=il(),n=gfe(),{fromCallback:i}=fE(),{Iterator:s}=wfe(),o=lF(),a=vfe(),d=dF(),l="level-js-",c=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,b,T){if(typeof b=="function"||typeof T=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:D,version:I,...M}=b||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},M),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=D??l,this[h]=parseInt(I||1,10),this[c]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[h]}get db(){return this[c]}get type(){return"browser-level"}_open(w,b){let T=indexedDB.open(this[u]+this[f],this[h]);T.onerror=function(){b(T.error||new Error("unknown error"))},T.onsuccess=()=>{this[c]=T.result,b()},T.onupgradeneeded=D=>{let I=D.target.result;I.objectStoreNames.contains(this[f])||I.createObjectStore(this[f])}}[p](w){return this[c].transaction([this[f]],w).objectStore(this[f])}[m](w,b){let T=w.transaction;T.onabort=function(){b(T.error||new Error("aborted by user"))},T.oncomplete=function(){b(null,w.result)}}_get(w,b,T){let D=this[p]("readonly"),I;try{I=D.get(w)}catch(M){return this.nextTick(T,M)}this[m](I,function(M,C){if(M)return T(M);if(C===void 0)return T(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));T(null,o(C))})}_getMany(w,b,T){let D=this[p]("readonly"),I=w.map(M=>C=>{let z;try{z=D.get(M)}catch(L){return C(L)}z.onsuccess=()=>{let L=z.result;C(null,L===void 0?L:o(L))},z.onerror=L=>{L.stopPropagation(),C(z.error)}});n(I,16,T)}_del(w,b,T){let D=this[p]("readwrite"),I;try{I=D.delete(w)}catch(M){return this.nextTick(T,M)}this[m](I,T)}_put(w,b,T,D){let I=this[p]("readwrite"),M;try{M=I.put(b,w)}catch(C){return this.nextTick(D,C)}this[m](M,D)}_iterator(w){return new s(this,this[f],w)}_batch(w,b,T){let D=this[p]("readwrite"),I=D.transaction,M=0,C;I.onabort=function(){T(C||I.error||new Error("aborted by user"))},I.oncomplete=function(){T()};function z(){let L=w[M++],B=L.key,H;try{H=L.type==="del"?D.delete(B):D.put(L.value,B)}catch(ee){C=ee,I.abort();return}M<w.length?H.onsuccess=z:typeof I.commit=="function"&&I.commit()}z()}_clear(w,b){let T,D;try{T=d(w)}catch{return this.nextTick(b)}if(w.limit>=0)return a(this,this[f],T,w,b);try{let I=this[p]("readwrite");D=T?I.delete(T):I.clear()}catch(I){return this.nextTick(b,I)}this[m](D,b)}_close(w){this[c].close(),this.nextTick(w)}};v.destroy=function(w,b,T){typeof b=="function"&&(T=b,b=l),T=i(T,y);let D=indexedDB.deleteDatabase(b+w);return D.onsuccess=function(){T()},D.onerror=function(I){T(I)},T[y]},r.BrowserLevel=v}),uF=Xt(r=>{r.Level=bfe().BrowserLevel}),xfe=Xt((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 X=arguments.length,se=Array(X),ce=0;ce<X;ce++)se[ce]=arguments[ce];if(se.length>1){se[0]=se[0].slice(0,-1);for(var be=se.length-1,Pe=1;Pe<be;++Pe)se[Pe]=se[Pe].slice(1,-1);return se[be]=se[be].slice(1),se.join("")}else return se[0]}function i(X){return"(?:"+X+")"}function s(X){return X===void 0?"undefined":X===null?"null":Object.prototype.toString.call(X).split(" ").pop().split("]").shift().toLowerCase()}function o(X){return X.toUpperCase()}function a(X){return X!=null?X instanceof Array?X:typeof X.length!="number"||X.split||X.setInterval||X.call?[X]:Array.prototype.slice.call(X):[]}function d(X,se){var ce=X;if(se)for(var be in se)ce[be]=se[be];return ce}function l(X){var se="[A-Za-z]",ce="[\\x0D]",be="[0-9]",Pe="[\\x22]",We=n(be,"[A-Fa-f]"),Nt="[\\x0A]",Pr="[\\x20]",tn=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),rn="[\\:\\/\\?\\#\\[\\]\\@]",fr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",In=n(rn,fr),ti=X?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",_n=X?"[\\uE000-\\uF8FF]":"[]",Rr=n(se,be,"[\\-\\.\\_\\~]",ti),kr=i(se+n(se,be,"[\\+\\-\\.]")+"*"),mo=i(i(tn+"|"+n(Rr,fr,"[\\:]"))+"*"),_w=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),ls=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),ac=i(ls+"\\."+ls+"\\."+ls+"\\."+ls),Cr=i(We+"{1,4}"),Bs=i(i(Cr+"\\:"+Cr)+"|"+ac),ga=i(i(Cr+"\\:")+"{6}"+Bs),ul=i("\\:\\:"+i(Cr+"\\:")+"{5}"+Bs),Ph=i(i(Cr)+"?\\:\\:"+i(Cr+"\\:")+"{4}"+Bs),ed=i(i(i(Cr+"\\:")+"{0,1}"+Cr)+"?\\:\\:"+i(Cr+"\\:")+"{3}"+Bs),q1=i(i(i(Cr+"\\:")+"{0,2}"+Cr)+"?\\:\\:"+i(Cr+"\\:")+"{2}"+Bs),z1=i(i(i(Cr+"\\:")+"{0,3}"+Cr)+"?\\:\\:"+Cr+"\\:"+Bs),Bm=i(i(i(Cr+"\\:")+"{0,4}"+Cr)+"?\\:\\:"+Bs),jm=i(i(i(Cr+"\\:")+"{0,5}"+Cr)+"?\\:\\:"+Cr),Nm=i(i(i(Cr+"\\:")+"{0,6}"+Cr)+"?\\:\\:"),_h=i([ga,ul,Ph,ed,q1,z1,Bm,jm,Nm].join("|")),Mm=i(i(Rr+"|"+tn)+"+"),Um=i(_h+"\\%25"+Mm),GJ=i(_h+i("\\%25|\\%(?!"+We+"{2})")+Mm),WJ=i("[vV]"+We+"+\\."+n(Rr,fr,"[\\:]")+"+"),HJ=i("\\["+i(GJ+"|"+_h+"|"+WJ)+"\\]"),nO=i(i(tn+"|"+n(Rr,fr))+"*"),Ew=i(HJ+"|"+ac+"(?!"+nO+")|"+nO),Sw=i(be+"*"),iO=i(i(mo+"@")+"?"+Ew+i("\\:"+Sw)+"?"),Tw=i(tn+"|"+n(Rr,fr,"[\\:\\@]")),VJ=i(Tw+"*"),oO=i(Tw+"+"),JJ=i(i(tn+"|"+n(Rr,fr,"[\\@]"))+"+"),fl=i(i("\\/"+VJ)+"*"),Km=i("\\/"+i(oO+fl)+"?"),ZS=i(JJ+fl),F1=i(oO+fl),Lm="(?!"+Tw+")",$be=i(fl+"|"+Km+"|"+ZS+"|"+F1+"|"+Lm),qm=i(i(Tw+"|"+n("[\\/\\?]",_n))+"*"),Dw=i(i(Tw+"|[\\/\\?]")+"*"),sO=i(i("\\/\\/"+iO+fl)+"|"+Km+"|"+F1+"|"+Lm),YJ=i(kr+"\\:"+sO+i("\\?"+qm)+"?"+i("\\#"+Dw)+"?"),ZJ=i(i("\\/\\/"+iO+fl)+"|"+Km+"|"+ZS+"|"+Lm),QJ=i(ZJ+i("\\?"+qm)+"?"+i("\\#"+Dw)+"?"),Obe=i(YJ+"|"+QJ),Bbe=i(kr+"\\:"+sO+i("\\?"+qm)+"?"),jbe="^("+kr+")\\:"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+F1+"|"+Lm+")")+i("\\?("+qm+")")+"?"+i("\\#("+Dw+")")+"?$",Nbe="^(){0}"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+ZS+"|"+Lm+")")+i("\\?("+qm+")")+"?"+i("\\#("+Dw+")")+"?$",Mbe="^("+kr+")\\:"+i(i("\\/\\/("+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?)")+"?("+fl+"|"+Km+"|"+F1+"|"+Lm+")")+i("\\?("+qm+")")+"?$",Ube="^"+i("\\#("+Dw+")")+"?$",Kbe="^"+i("("+mo+")@")+"?("+Ew+")"+i("\\:("+Sw+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",se,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Rr,fr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Rr,fr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Rr,fr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Rr,fr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Rr,fr,"[\\:\\@\\/\\?]",_n),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Rr,fr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Rr,fr),"g"),UNRESERVED:new RegExp(Rr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Rr,In),"g"),PCT_ENCODED:new RegExp(tn,"g"),IPV4ADDRESS:new RegExp("^("+ac+")$"),IPV6ADDRESS:new RegExp("^\\[?("+_h+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+Mm+")")+"?\\]?$")}}var c=l(!1),u=l(!0),f=function(){function X(se,ce){var be=[],Pe=!0,We=!1,Nt=void 0;try{for(var Pr=se[Symbol.iterator](),tn;!(Pe=(tn=Pr.next()).done)&&(be.push(tn.value),!(ce&&be.length===ce));Pe=!0);}catch(rn){We=!0,Nt=rn}finally{try{!Pe&&Pr.return&&Pr.return()}finally{if(We)throw Nt}}return be}return function(se,ce){if(Array.isArray(se))return se;if(Symbol.iterator in Object(se))return X(se,ce);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(X){if(Array.isArray(X)){for(var se=0,ce=Array(X.length);se<X.length;se++)ce[se]=X[se];return ce}else return Array.from(X)},p=2147483647,m=36,y=1,v=26,w=38,b=700,T=72,D=128,I="-",M=/^xn--/,C=/[^\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"},B=m-y,H=Math.floor,ee=String.fromCharCode;function R(X){throw new RangeError(L[X])}function $(X,se){for(var ce=[],be=X.length;be--;)ce[be]=se(X[be]);return ce}function E(X,se){var ce=X.split("@"),be="";ce.length>1&&(be=ce[0]+"@",X=ce[1]),X=X.replace(z,".");var Pe=X.split("."),We=$(Pe,se).join(".");return be+We}function P(X){for(var se=[],ce=0,be=X.length;ce<be;){var Pe=X.charCodeAt(ce++);if(Pe>=55296&&Pe<=56319&&ce<be){var We=X.charCodeAt(ce++);(We&64512)==56320?se.push(((Pe&1023)<<10)+(We&1023)+65536):(se.push(Pe),ce--)}else se.push(Pe)}return se}var _=function(X){return String.fromCodePoint.apply(String,h(X))},S=function(X){return X-48<10?X-22:X-65<26?X-65:X-97<26?X-97:m},A=function(X,se){return X+22+75*(X<26)-((se!=0)<<5)},N=function(X,se,ce){var be=0;for(X=ce?H(X/b):X>>1,X+=H(X/se);X>B*v>>1;be+=m)X=H(X/B);return H(be+(B+1)*X/(X+w))},q=function(X){var se=[],ce=X.length,be=0,Pe=D,We=T,Nt=X.lastIndexOf(I);Nt<0&&(Nt=0);for(var Pr=0;Pr<Nt;++Pr)X.charCodeAt(Pr)>=128&&R("not-basic"),se.push(X.charCodeAt(Pr));for(var tn=Nt>0?Nt+1:0;tn<ce;){for(var rn=be,fr=1,In=m;;In+=m){tn>=ce&&R("invalid-input");var ti=S(X.charCodeAt(tn++));(ti>=m||ti>H((p-be)/fr))&&R("overflow"),be+=ti*fr;var _n=In<=We?y:In>=We+v?v:In-We;if(ti<_n)break;var Rr=m-_n;fr>H(p/Rr)&&R("overflow"),fr*=Rr}var kr=se.length+1;We=N(be-rn,kr,rn==0),H(be/kr)>p-Pe&&R("overflow"),Pe+=H(be/kr),be%=kr,se.splice(be++,0,Pe)}return String.fromCodePoint.apply(String,se)},W=function(X){var se=[];X=P(X);var ce=X.length,be=D,Pe=0,We=T,Nt=!0,Pr=!1,tn=void 0;try{for(var rn=X[Symbol.iterator](),fr;!(Nt=(fr=rn.next()).done);Nt=!0){var In=fr.value;In<128&&se.push(ee(In))}}catch(Um){Pr=!0,tn=Um}finally{try{!Nt&&rn.return&&rn.return()}finally{if(Pr)throw tn}}var ti=se.length,_n=ti;for(ti&&se.push(I);_n<ce;){var Rr=p,kr=!0,mo=!1,_w=void 0;try{for(var ls=X[Symbol.iterator](),ac;!(kr=(ac=ls.next()).done);kr=!0){var Cr=ac.value;Cr>=be&&Cr<Rr&&(Rr=Cr)}}catch(Um){mo=!0,_w=Um}finally{try{!kr&&ls.return&&ls.return()}finally{if(mo)throw _w}}var Bs=_n+1;Rr-be>H((p-Pe)/Bs)&&R("overflow"),Pe+=(Rr-be)*Bs,be=Rr;var ga=!0,ul=!1,Ph=void 0;try{for(var ed=X[Symbol.iterator](),q1;!(ga=(q1=ed.next()).done);ga=!0){var z1=q1.value;if(z1<be&&++Pe>p&&R("overflow"),z1==be){for(var Bm=Pe,jm=m;;jm+=m){var Nm=jm<=We?y:jm>=We+v?v:jm-We;if(Bm<Nm)break;var _h=Bm-Nm,Mm=m-Nm;se.push(ee(A(Nm+_h%Mm,0))),Bm=H(_h/Mm)}se.push(ee(A(Bm,0))),We=N(Pe,Bs,_n==ti),Pe=0,++_n}}}catch(Um){ul=!0,Ph=Um}finally{try{!ga&&ed.return&&ed.return()}finally{if(ul)throw Ph}}++Pe,++be}return se.join("")},J=function(X){return E(X,function(se){return M.test(se)?q(se.slice(4).toLowerCase()):se})},V=function(X){return E(X,function(se){return C.test(se)?"xn--"+W(se):se})},Y={version:"2.1.0",ucs2:{decode:P,encode:_},decode:q,encode:W,toASCII:V,toUnicode:J},F={};function Q(X){var se=X.charCodeAt(0),ce=void 0;return se<16?ce="%0"+se.toString(16).toUpperCase():se<128?ce="%"+se.toString(16).toUpperCase():se<2048?ce="%"+(se>>6|192).toString(16).toUpperCase()+"%"+(se&63|128).toString(16).toUpperCase():ce="%"+(se>>12|224).toString(16).toUpperCase()+"%"+(se>>6&63|128).toString(16).toUpperCase()+"%"+(se&63|128).toString(16).toUpperCase(),ce}function ie(X){for(var se="",ce=0,be=X.length;ce<be;){var Pe=parseInt(X.substr(ce+1,2),16);if(Pe<128)se+=String.fromCharCode(Pe),ce+=3;else if(Pe>=194&&Pe<224){if(be-ce>=6){var We=parseInt(X.substr(ce+4,2),16);se+=String.fromCharCode((Pe&31)<<6|We&63)}else se+=X.substr(ce,6);ce+=6}else if(Pe>=224){if(be-ce>=9){var Nt=parseInt(X.substr(ce+4,2),16),Pr=parseInt(X.substr(ce+7,2),16);se+=String.fromCharCode((Pe&15)<<12|(Nt&63)<<6|Pr&63)}else se+=X.substr(ce,9);ce+=9}else se+=X.substr(ce,3),ce+=3}return se}function oe(X,se){function ce(be){var Pe=ie(be);return Pe.match(se.UNRESERVED)?Pe:be}return X.scheme&&(X.scheme=String(X.scheme).replace(se.PCT_ENCODED,ce).toLowerCase().replace(se.NOT_SCHEME,"")),X.userinfo!==void 0&&(X.userinfo=String(X.userinfo).replace(se.PCT_ENCODED,ce).replace(se.NOT_USERINFO,Q).replace(se.PCT_ENCODED,o)),X.host!==void 0&&(X.host=String(X.host).replace(se.PCT_ENCODED,ce).toLowerCase().replace(se.NOT_HOST,Q).replace(se.PCT_ENCODED,o)),X.path!==void 0&&(X.path=String(X.path).replace(se.PCT_ENCODED,ce).replace(X.scheme?se.NOT_PATH:se.NOT_PATH_NOSCHEME,Q).replace(se.PCT_ENCODED,o)),X.query!==void 0&&(X.query=String(X.query).replace(se.PCT_ENCODED,ce).replace(se.NOT_QUERY,Q).replace(se.PCT_ENCODED,o)),X.fragment!==void 0&&(X.fragment=String(X.fragment).replace(se.PCT_ENCODED,ce).replace(se.NOT_FRAGMENT,Q).replace(se.PCT_ENCODED,o)),X}function Z(X){return X.replace(/^0*(.*)/,"$1")||"0"}function le(X,se){var ce=X.match(se.IPV4ADDRESS)||[],be=f(ce,2),Pe=be[1];return Pe?Pe.split(".").map(Z).join("."):X}function he(X,se){var ce=X.match(se.IPV6ADDRESS)||[],be=f(ce,3),Pe=be[1],We=be[2];if(Pe){for(var Nt=Pe.toLowerCase().split("::").reverse(),Pr=f(Nt,2),tn=Pr[0],rn=Pr[1],fr=rn?rn.split(":").map(Z):[],In=tn.split(":").map(Z),ti=se.IPV4ADDRESS.test(In[In.length-1]),_n=ti?7:8,Rr=In.length-_n,kr=Array(_n),mo=0;mo<_n;++mo)kr[mo]=fr[mo]||In[Rr+mo]||"";ti&&(kr[_n-1]=le(kr[_n-1],se));var _w=kr.reduce(function(ga,ul,Ph){if(!ul||ul==="0"){var ed=ga[ga.length-1];ed&&ed.index+ed.length===Ph?ed.length++:ga.push({index:Ph,length:1})}return ga},[]),ls=_w.sort(function(ga,ul){return ul.length-ga.length})[0],ac=void 0;if(ls&&ls.length>1){var Cr=kr.slice(0,ls.index),Bs=kr.slice(ls.index+ls.length);ac=Cr.join(":")+"::"+Bs.join(":")}else ac=kr.join(":");return We&&(ac+="%"+We),ac}else return X}var ue=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function pe(X){var se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce={},be=se.iri!==!1?u:c;se.reference==="suffix"&&(X=(se.scheme?se.scheme+":":"")+"//"+X);var Pe=X.match(ue);if(Pe){Se?(ce.scheme=Pe[1],ce.userinfo=Pe[3],ce.host=Pe[4],ce.port=parseInt(Pe[5],10),ce.path=Pe[6]||"",ce.query=Pe[7],ce.fragment=Pe[8],isNaN(ce.port)&&(ce.port=Pe[5])):(ce.scheme=Pe[1]||void 0,ce.userinfo=X.indexOf("@")!==-1?Pe[3]:void 0,ce.host=X.indexOf("//")!==-1?Pe[4]:void 0,ce.port=parseInt(Pe[5],10),ce.path=Pe[6]||"",ce.query=X.indexOf("?")!==-1?Pe[7]:void 0,ce.fragment=X.indexOf("#")!==-1?Pe[8]:void 0,isNaN(ce.port)&&(ce.port=X.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Pe[4]:void 0)),ce.host&&(ce.host=he(le(ce.host,be),be)),ce.scheme===void 0&&ce.userinfo===void 0&&ce.host===void 0&&ce.port===void 0&&!ce.path&&ce.query===void 0?ce.reference="same-document":ce.scheme===void 0?ce.reference="relative":ce.fragment===void 0?ce.reference="absolute":ce.reference="uri",se.reference&&se.reference!=="suffix"&&se.reference!==ce.reference&&(ce.error=ce.error||"URI is not a "+se.reference+" reference.");var We=F[(se.scheme||ce.scheme||"").toLowerCase()];if(!se.unicodeSupport&&(!We||!We.unicodeSupport)){if(ce.host&&(se.domainHost||We&&We.domainHost))try{ce.host=Y.toASCII(ce.host.replace(be.PCT_ENCODED,ie).toLowerCase())}catch(Nt){ce.error=ce.error||"Host's domain name can not be converted to ASCII via punycode: "+Nt}oe(ce,c)}else oe(ce,be);We&&We.parse&&We.parse(ce,se)}else ce.error=ce.error||"URI can not be parsed.";return ce}function Ae(X,se){var ce=se.iri!==!1?u:c,be=[];return X.userinfo!==void 0&&(be.push(X.userinfo),be.push("@")),X.host!==void 0&&be.push(he(le(String(X.host),ce),ce).replace(ce.IPV6ADDRESS,function(Pe,We,Nt){return"["+We+(Nt?"%25"+Nt:"")+"]"})),(typeof X.port=="number"||typeof X.port=="string")&&(be.push(":"),be.push(String(X.port))),be.length?be.join(""):void 0}var Ot=/^\.\.?\//,ai=/^\/\.(\/|$)/,Lr=/^\/\.\.(\/|$)/,ds=/^\/?(?:.|\n)*?(?=\/|$)/;function Ye(X){for(var se=[];X.length;)if(X.match(Ot))X=X.replace(Ot,"");else if(X.match(ai))X=X.replace(ai,"/");else if(X.match(Lr))X=X.replace(Lr,"/"),se.pop();else if(X==="."||X==="..")X="";else{var ce=X.match(ds);if(ce){var be=ce[0];X=X.slice(be.length),se.push(be)}else throw new Error("Unexpected dot segment condition")}return se.join("")}function ar(X){var se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce=se.iri?u:c,be=[],Pe=F[(se.scheme||X.scheme||"").toLowerCase()];if(Pe&&Pe.serialize&&Pe.serialize(X,se),X.host&&!ce.IPV6ADDRESS.test(X.host)&&(se.domainHost||Pe&&Pe.domainHost))try{X.host=se.iri?Y.toUnicode(X.host):Y.toASCII(X.host.replace(ce.PCT_ENCODED,ie).toLowerCase())}catch(Pr){X.error=X.error||"Host's domain name can not be converted to "+(se.iri?"Unicode":"ASCII")+" via punycode: "+Pr}oe(X,ce),se.reference!=="suffix"&&X.scheme&&(be.push(X.scheme),be.push(":"));var We=Ae(X,se);if(We!==void 0&&(se.reference!=="suffix"&&be.push("//"),be.push(We),X.path&&X.path.charAt(0)!=="/"&&be.push("/")),X.path!==void 0){var Nt=X.path;!se.absolutePath&&(!Pe||!Pe.absolutePath)&&(Nt=Ye(Nt)),We===void 0&&(Nt=Nt.replace(/^\/\//,"/%2F")),be.push(Nt)}return X.query!==void 0&&(be.push("?"),be.push(X.query)),X.fragment!==void 0&&(be.push("#"),be.push(X.fragment)),be.join("")}function qr(X,se){var ce=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Pe={};return be||(X=pe(ar(X,ce),ce),se=pe(ar(se,ce),ce)),ce=ce||{},!ce.tolerant&&se.scheme?(Pe.scheme=se.scheme,Pe.userinfo=se.userinfo,Pe.host=se.host,Pe.port=se.port,Pe.path=Ye(se.path||""),Pe.query=se.query):(se.userinfo!==void 0||se.host!==void 0||se.port!==void 0?(Pe.userinfo=se.userinfo,Pe.host=se.host,Pe.port=se.port,Pe.path=Ye(se.path||""),Pe.query=se.query):(se.path?(se.path.charAt(0)==="/"?Pe.path=Ye(se.path):((X.userinfo!==void 0||X.host!==void 0||X.port!==void 0)&&!X.path?Pe.path="/"+se.path:X.path?Pe.path=X.path.slice(0,X.path.lastIndexOf("/")+1)+se.path:Pe.path=se.path,Pe.path=Ye(Pe.path)),Pe.query=se.query):(Pe.path=X.path,se.query!==void 0?Pe.query=se.query:Pe.query=X.query),Pe.userinfo=X.userinfo,Pe.host=X.host,Pe.port=X.port),Pe.scheme=X.scheme),Pe.fragment=se.fragment,Pe}function yr(X,se,ce){var be=d({scheme:"null"},ce);return ar(qr(pe(X,be),pe(se,be),be,!0),be)}function Gt(X,se){return typeof X=="string"?X=ar(pe(X,se),se):s(X)==="object"&&(X=pe(ar(X,se),se)),X}function k(X,se,ce){return typeof X=="string"?X=ar(pe(X,ce),ce):s(X)==="object"&&(X=ar(X,ce)),typeof se=="string"?se=ar(pe(se,ce),ce):s(se)==="object"&&(se=ar(se,ce)),X===se}function U(X,se){return X&&X.toString().replace(!se||!se.iri?c.ESCAPE:u.ESCAPE,Q)}function K(X,se){return X&&X.toString().replace(!se||!se.iri?c.PCT_ENCODED:u.PCT_ENCODED,ie)}var te={scheme:"http",domainHost:!0,parse:function(X,se){return X.host||(X.error=X.error||"HTTP URIs must have a host."),X},serialize:function(X,se){var ce=String(X.scheme).toLowerCase()==="https";return(X.port===(ce?443:80)||X.port==="")&&(X.port=void 0),X.path||(X.path="/"),X}},de={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(X){return typeof X.secure=="boolean"?X.secure:String(X.scheme).toLowerCase()==="wss"}var Ee={scheme:"ws",domainHost:!0,parse:function(X,se){var ce=X;return ce.secure=ge(ce),ce.resourceName=(ce.path||"/")+(ce.query?"?"+ce.query:""),ce.path=void 0,ce.query=void 0,ce},serialize:function(X,se){if((X.port===(ge(X)?443:80)||X.port==="")&&(X.port=void 0),typeof X.secure=="boolean"&&(X.scheme=X.secure?"wss":"ws",X.secure=void 0),X.resourceName){var ce=X.resourceName.split("?"),be=f(ce,2),Pe=be[0],We=be[1];X.path=Pe&&Pe!=="/"?Pe:void 0,X.query=We,X.resourceName=void 0}return X.fragment=void 0,X}},Wt={scheme:"wss",domainHost:Ee.domainHost,parse:Ee.parse,serialize:Ee.serialize},ci={},Vr=!0,Dr="[A-Za-z0-9\\-\\.\\_\\~"+(Vr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",gr="[0-9A-Fa-f]",BJ=i(i("%[EFef]"+gr+"%"+gr+gr+"%"+gr+gr)+"|"+i("%[89A-Fa-f]"+gr+"%"+gr+gr)+"|"+i("%"+gr+gr)),jJ="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",NJ="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",MJ=n(NJ,'[\\"\\\\]'),UJ="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",KJ=new RegExp(Dr,"g"),Om=new RegExp(BJ,"g"),LJ=new RegExp(n("[^]",jJ,"[\\.]",'[\\"]',MJ),"g"),X$=new RegExp(n("[^]",Dr,UJ),"g"),qJ=X$;function YS(X){var se=ie(X);return se.match(KJ)?se:X}var eO={scheme:"mailto",parse:function(X,se){var ce=X,be=ce.to=ce.path?ce.path.split(","):[];if(ce.path=void 0,ce.query){for(var Pe=!1,We={},Nt=ce.query.split("&"),Pr=0,tn=Nt.length;Pr<tn;++Pr){var rn=Nt[Pr].split("=");switch(rn[0]){case"to":for(var fr=rn[1].split(","),In=0,ti=fr.length;In<ti;++In)be.push(fr[In]);break;case"subject":ce.subject=K(rn[1],se);break;case"body":ce.body=K(rn[1],se);break;default:Pe=!0,We[K(rn[0],se)]=K(rn[1],se);break}}Pe&&(ce.headers=We)}ce.query=void 0;for(var _n=0,Rr=be.length;_n<Rr;++_n){var kr=be[_n].split("@");if(kr[0]=K(kr[0]),se.unicodeSupport)kr[1]=K(kr[1],se).toLowerCase();else try{kr[1]=Y.toASCII(K(kr[1],se).toLowerCase())}catch(mo){ce.error=ce.error||"Email address's domain name can not be converted to ASCII via punycode: "+mo}be[_n]=kr.join("@")}return ce},serialize:function(X,se){var ce=X,be=a(X.to);if(be){for(var Pe=0,We=be.length;Pe<We;++Pe){var Nt=String(be[Pe]),Pr=Nt.lastIndexOf("@"),tn=Nt.slice(0,Pr).replace(Om,YS).replace(Om,o).replace(LJ,Q),rn=Nt.slice(Pr+1);try{rn=se.iri?Y.toUnicode(rn):Y.toASCII(K(rn,se).toLowerCase())}catch(_n){ce.error=ce.error||"Email address's domain name can not be converted to "+(se.iri?"Unicode":"ASCII")+" via punycode: "+_n}be[Pe]=tn+"@"+rn}ce.path=be.join(",")}var fr=X.headers=X.headers||{};X.subject&&(fr.subject=X.subject),X.body&&(fr.body=X.body);var In=[];for(var ti in fr)fr[ti]!==ci[ti]&&In.push(ti.replace(Om,YS).replace(Om,o).replace(X$,Q)+"="+fr[ti].replace(Om,YS).replace(Om,o).replace(qJ,Q));return In.length&&(ce.query=In.join("&")),ce}},zJ=/^([^\:]+)\:(.*)/,tO={scheme:"urn",parse:function(X,se){var ce=X.path&&X.path.match(zJ),be=X;if(ce){var Pe=se.scheme||be.scheme||"urn",We=ce[1].toLowerCase(),Nt=ce[2],Pr=Pe+":"+(se.nid||We),tn=F[Pr];be.nid=We,be.nss=Nt,be.path=void 0,tn&&(be=tn.parse(be,se))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(X,se){var ce=se.scheme||X.scheme||"urn",be=X.nid,Pe=ce+":"+(se.nid||be),We=F[Pe];We&&(X=We.serialize(X,se));var Nt=X,Pr=X.nss;return Nt.path=(be||se.nid)+":"+Pr,Nt}},FJ=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,rO={scheme:"urn:uuid",parse:function(X,se){var ce=X;return ce.uuid=ce.nss,ce.nss=void 0,!se.tolerant&&(!ce.uuid||!ce.uuid.match(FJ))&&(ce.error=ce.error||"UUID is not valid."),ce},serialize:function(X,se){var ce=X;return ce.nss=(X.uuid||"").toLowerCase(),ce}};F[te.scheme]=te,F[de.scheme]=de,F[Ee.scheme]=Ee,F[Wt.scheme]=Wt,F[eO.scheme]=eO,F[tO.scheme]=tO,F[rO.scheme]=rO,t.SCHEMES=F,t.pctEncChar=Q,t.pctDecChars=ie,t.parse=pe,t.removeDotSegments=Ye,t.serialize=ar,t.resolveComponents=qr,t.resolve=yr,t.normalize=Gt,t.equal=k,t.escapeComponent=U,t.unescapeComponent=K,Object.defineProperty(t,"__esModule",{value:!0})})}),Pfe=Xt((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,s,o)=>`${i}${o===0?"":","}${t(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,s)=>{if(n[s]===void 0||typeof n[s]=="symbol")return i;let o=i.length===0?"":",";return`${i}${o}${t(s)}:${t(n[s])}`},"")}}`}}),fF=Xt((r,e)=>{var t=1e3,n=t*60,i=n*60,s=i*24,o=s*7,a=s*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return d(f);if(p==="number"&&isFinite(f))return h.long?c(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function d(f){if(f=String(f),!(f.length>100)){var h=/^(-?(?:\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(h){var p=parseFloat(h[1]),m=(h[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return p*a;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*s;case"hours":case"hour":case"hrs":case"hr":case"h":return p*i;case"minutes":case"minute":case"mins":case"min":case"m":return p*n;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function l(f){var h=Math.abs(f);return h>=s?Math.round(f/s)+"d":h>=i?Math.round(f/i)+"h":h>=n?Math.round(f/n)+"m":h>=t?Math.round(f/t)+"s":f+"ms"}function c(f){var h=Math.abs(f);return h>=s?u(f,h,s,"day"):h>=i?u(f,h,i,"hour"):h>=n?u(f,h,n,"minute"):h>=t?u(f,h,t,"second"):f+" ms"}function u(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),hE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(hE||{}),fo={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},oo=class hF{constructor({method:e,id:t,path:n,query:i,fragment:s,params:o}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=s,this.params=o}static parse(e){if(!e||e.length>2048)return null;let t=hF.DID_URI_PATTERN.exec(e);if(!t?.groups)return null;let{method:n,id:i,path:s,query:o,fragment:a}=t.groups,d={uri:`did:${n}:${i}`,method:n,id:i};if(s&&(d.path=s),o&&(d.query=o.slice(1)),a&&(d.fragment=a.slice(1)),o){let l={},c=o.slice(1).split("&");for(let u of c){let[f,h]=u.split("=");l[f]=h}d.params=l}return d}};oo.METHOD_PATTERN="([a-z0-9]+)",oo.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",oo.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${oo.PCT_ENCODED_PATTERN})`,oo.METHOD_ID_PATTERN=`((?:${oo.ID_CHAR_PATTERN}*:)*(${oo.ID_CHAR_PATTERN}+))`,oo.PATH_PATTERN="(/[^#?]*)?",oo.QUERY_PATTERN="([?][^#]*)?",oo.FRAGMENT_PATTERN="(#.*)?",oo.DID_URI_PATTERN=new RegExp("^did:(?<method>"+oo.METHOD_PATTERN+"):(?<id>"+oo.METHOD_ID_PATTERN+")(?<path>"+oo.PATH_PATTERN+")(?<query>"+oo.QUERY_PATTERN+")(?<fragment>"+oo.FRAGMENT_PATTERN+")$");Qn=oo,rt=class pF 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,pF)}},_fe=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidGatewayUri="invalidGatewayUri",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))(_fe||{}),Qa=class mF extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,mF)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(ks||(ks={}));Efe=Xp(rfe(),1);Tfe=Sfe,Dfe=Tfe,kfe=Dfe,P9e=new Uint8Array(0),Afe=(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},c5=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")},Ife=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")}},Rfe=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 yF(this,r)}},Cfe=class{constructor(r){this.decoders=r}or(r){return yF(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`)}},yF=(r,e)=>new Cfe({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),$fe=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Ife(r,e,t),this.decoder=new Rfe(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},gF=({name:r,prefix:e,encode:t,decode:n})=>new $fe(r,e,t,n),wF=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=kfe(t,e);return gF({prefix:r,name:e,encode:n,decode:s=>c5(i(s))})},Ofe=(r,e,t,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,d=0,l=0;for(let c=0;c<s;++c){let u=i[r[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&d>>a)}if(a>=t||255&d<<8-a)throw new SyntaxError("Unexpected end of data");return o},Bfe=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let d=0;d<r.length;++d)for(a=a<<8|r[d],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},ua=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>gF({prefix:e,name:r,encode(i){return Bfe(i,n,t)},decode(i){return Ofe(i,n,t,r)}}),$2=ua({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_9e=ua({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),E9e=ua({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),S9e=ua({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),T9e=ua({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),D9e=ua({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),k9e=ua({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),A9e=ua({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Kz=ua({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ya=wF({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),I9e=wF({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),R9e=ua({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),C9e=ua({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),au=ua({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$9e=ua({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});pb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Lz=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(s){t[s]=r[s]&&function(o){return new Promise(function(a,d){o=r[s](o),i(a,d,o.done,o.value)})}}function i(s,o,a,d){Promise.resolve(d).then(function(l){s({value:l,done:a})},o)}},S2=new TextEncoder,Up=new TextDecoder,ot=class Ts{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new Ts(e,"ArrayBuffer")}static asyncIterable(e){if(!Nfe(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ts(e,"AsyncIterable")}static base32Z(e){return new Ts(e,"Base32Z")}static base58Btc(e){return new Ts(e,"Base58Btc")}static base64Url(e){return new Ts(e,"Base64Url")}static bufferSource(e){return new Ts(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 Ts(e,"Hex")}static multibase(e){return new Ts(e,"Multibase")}static object(e){return new Ts(e,"Object")}static string(e){return new Ts(e,"String")}static uint8Array(e){return new Ts(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ya.baseDecode(this.data).buffer;case"Base64Url":return au.baseDecode(this.data).buffer;case"BufferSource":{if(M6(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return jfe(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 pb(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 Kz.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 Ya.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ya.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 au.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return au.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=S2.encode(e);return au.baseEncode(t)}case"String":{let e=S2.encode(this.data);return au.baseEncode(e)}case"Uint8Array":return au.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return pb(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let d=[];try{for(var s=!0,o=Lz(this.data),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;let l=i;d.push(l)}}catch(l){t={error:l}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return new Blob(d)}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 Ts.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return Ts.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=au.baseDecode(this.data),t=Up.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Up.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return pb(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 Up.decode(this.data);case"Base64Url":{let e=au.baseDecode(this.data);return Up.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Up.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return pb(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let d="";try{for(var s=!0,o=Lz(this.data),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;let l=i;typeof l=="string"?d+=l:d+=Up.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return d+=Up.decode(void 0,{stream:!1}),d}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 Kz.baseDecode(this.data);case"Base58Btc":return Ya.baseDecode(this.data);case"Base64Url":return au.baseDecode(this.data);case"BufferSource":{let e=M6(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 S2.encode(e)}case"String":return S2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return pb(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"})(jb||(jb={}));Mfe=class{constructor(){this.logLevel=jb.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==jb.Silent&&console.info(r)}error(r){this.logLevel!==jb.Silent&&console.error(r)}},Ufe=new Mfe;typeof window<"u"&&(window.enboxLogger=Ufe);xb={};o5(xb,{decode:()=>tE,encodeTo:()=>Mb,encodingLength:()=>Ub});Kfe=vF,qz=128,Lfe=127,qfe=~Lfe,zfe=Math.pow(2,31);Ffe=U6,Gfe=128,zz=127;Wfe=Math.pow(2,7),Hfe=Math.pow(2,14),Vfe=Math.pow(2,21),Jfe=Math.pow(2,28),Yfe=Math.pow(2,35),Zfe=Math.pow(2,42),Qfe=Math.pow(2,49),Xfe=Math.pow(2,56),ehe=Math.pow(2,63),the=function(r){return r<Wfe?1:r<Hfe?2:r<Vfe?3:r<Jfe?4:r<Yfe?5:r<Zfe?6:r<Qfe?7:r<Xfe?8:r<ehe?9:10},rhe={encode:Kfe,decode:Ffe,encodingLength:the},nhe=rhe,eE=nhe,tE=(r,e=0)=>[eE.decode(r,e),eE.decode.bytes],Mb=(r,e,t=0)=>(eE.encode(r,e,t),e),Ub=r=>eE.encodingLength(r),ihe=(r,e)=>{let t=e.byteLength,n=Ub(r),i=n+Ub(t),s=new Uint8Array(i+t);return Mb(r,s,0),Mb(t,s,n),s.set(e,i),new d5(r,t,e,s)},ohe=r=>{let e=c5(r),[t,n]=tE(e),[i,s]=tE(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new d5(t,i,o,e)},she=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Afe(r.bytes,t.bytes)}},d5=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},Fz=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return che(t,K6(r),e||Ya.encoder);default:return dhe(t,K6(r),e||$2.encoder)}},Gz=new WeakMap,K6=r=>{let e=Gz.get(r);if(e==null){let t=new Map;return Gz.set(r,t),t}return e},O9e=class ko{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!==mb)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==lhe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ko.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=ihe(e,t);return ko.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 ko.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&she(e.multihash,n.multihash)}toString(e){return Fz(this,e)}toJSON(){return{"/":Fz(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 ko)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new ko(n,i,s,o||Wz(n,i,s.bytes))}else if(t[uhe]===!0){let{version:n,multihash:i,code:s}=t,o=ohe(i);return ko.create(n,s,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!==mb)throw new Error(`Version 0 CID must use dag-pb (code: ${mb}) block encoding`);return new ko(e,t,n,n.bytes)}case 1:{let i=Wz(e,t,n.bytes);return new ko(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ko.create(0,mb,e)}static createV1(e,t){return ko.create(1,e,t)}static decode(e){let[t,n]=ko.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ko.inspectBytes(e),n=t.size-t.multihashSize,i=c5(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new d5(t.multihashCode,t.digestSize,s,i);return[t.version===0?ko.createV0(o):ko.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=tE(e.subarray(t));return t+=f,u},i=n(),s=mb;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),d=n(),l=t+d,c=l-o;return{version:i,codec:s,multihashCode:a,digestSize:d,multihashSize:c,size:l}}static parse(e,t){let[n,i]=ahe(e,t),s=ko.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return K6(s).set(n,e),s}},ahe=(r,e)=>{switch(r[0]){case"Q":{let t=e||Ya;return[Ya.prefix,t.decode(`${Ya.prefix}${r}`)]}case Ya.prefix:{let t=e||Ya;return[Ya.prefix,t.decode(r)]}case $2.prefix:{let t=e||$2;return[$2.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)]}}},che=(r,e,t)=>{let{prefix:n}=t;if(n!==Ya.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},dhe=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},mb=112,lhe=18,Wz=(r,e,t)=>{let n=Ub(r),i=n+Ub(e),s=new Uint8Array(i+t.byteLength);return Mb(r,s,0),Mb(e,s,n),s.set(t,i),s},uhe=Symbol.for("@ipld/js-cid/CID"),ec=class eh{static addPrefix(e){var t;let{code:n,data:i,name:s}=e;if(!(s?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=eh.codeToName.has(n)?n:eh.nameToCode.get(s),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let o=xb.encodingLength(n),a=new Uint8Array(o+i.byteLength);return a.set(i,o),xb.encodeTo(n,a),a}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=xb.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=eh.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=eh.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){eh.codeToName.set(e.code,e.name),eh.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=xb.decode(t),s=eh.codeToName.get(n);if(s===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:s}}};ec.codeToName=new Map;ec.nameToCode=new Map;ec.registerCodec({code:237,name:"ed25519-pub"});ec.registerCodec({code:4864,name:"ed25519-priv"});ec.registerCodec({code:236,name:"x25519-pub"});ec.registerCodec({code:4866,name:"x25519-priv"});ec.registerCodec({code:231,name:"secp256k1-pub"});ec.registerCodec({code:4865,name:"secp256k1-priv"});B9e=Xp(uF(),1),Ff=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},fhe=class{constructor(){this.store=new Map}clear(){return Ff(this,void 0,void 0,function*(){this.store.clear()})}open(){return Ff(this,void 0,void 0,function*(){})}close(){return Ff(this,void 0,void 0,function*(){})}delete(r){return Ff(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return Ff(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return Ff(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return Ff(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return Ff(this,void 0,void 0,function*(){this.store.set(r,e)})}},hhe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};mhe=["http:","https:"],O2=class extends Error{constructor(r){super(r),this.name="PublicUrlValidationError"}};yhe=5,ghe=new Set([301,302,303,307,308]);pE=class{},EF={};o5(EF,{bitGet:()=>khe,bitLen:()=>Dhe,bitMask:()=>u5,bitSet:()=>Ahe,bytesToHex:()=>Yp,bytesToNumberBE:()=>Hp,bytesToNumberLE:()=>oh,concatBytes:()=>Zp,createHmacDrbg:()=>DF,ensureBytes:()=>Zn,equalBytes:()=>She,hexToBytes:()=>qg,hexToNumber:()=>l5,isBytes:()=>rl,numberToBytesBE:()=>nl,numberToBytesLE:()=>zg,numberToHexUnpadded:()=>TF,numberToVarBytesBE:()=>Ehe,utf8ToBytes:()=>The,validateObject:()=>em});SF=BigInt(0),mE=BigInt(1),Phe=BigInt(2);_he=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));cu={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};Ahe=(r,e,t)=>r|(t?mE:SF)<<BigInt(e),u5=r=>(Phe<<BigInt(r-1))-mE,k6=r=>new Uint8Array(r),Jz=r=>Uint8Array.from(r);Ihe={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"||rl(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)};A6=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;I6=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Vd=(r,e)=>r<<32-e|r>>>e,Ohe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ohe)throw new Error("Non little-endian hardware is not supported");CF=class{clone(){return this._cloneInto()}},j9e={}.toString;OF=class extends CF{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=I6(this.buffer)}update(r){rE(this);let{view:e,buffer:t,blockLen:n}=this;r=f5(r);let i=r.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){let a=I6(r);for(;n<=i-s;s+=n)this.process(a,s);continue}t.set(r.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){rE(this),$he(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>n-s&&(this.process(t,0),s=0);for(let c=s;c<n;c++)e[c]=0;Bhe(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=I6(r),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=a/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)o.setUint32(4*c,l[c],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:s,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=s,n%e&&r.buffer.set(t),r}},jhe=(r,e,t)=>r&e^~r&t,Nhe=(r,e,t)=>r&e^r&t^e&t,Mhe=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]),Gf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Wf=new Uint32Array(64),Uhe=class extends OF{constructor(){super(64,32,8,!1),this.A=Gf[0]|0,this.B=Gf[1]|0,this.C=Gf[2]|0,this.D=Gf[3]|0,this.E=Gf[4]|0,this.F=Gf[5]|0,this.G=Gf[6]|0,this.H=Gf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:s,G:o,H:a}=this;return[r,e,t,n,i,s,o,a]}set(r,e,t,n,i,s,o,a){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=s|0,this.G=o|0,this.H=a|0}process(r,e){for(let c=0;c<16;c++,e+=4)Wf[c]=r.getUint32(e,!1);for(let c=16;c<64;c++){let u=Wf[c-15],f=Wf[c-2],h=Vd(u,7)^Vd(u,18)^u>>>3,p=Vd(f,17)^Vd(f,19)^f>>>10;Wf[c]=p+Wf[c-7]+h+Wf[c-16]|0}let{A:t,B:n,C:i,D:s,E:o,F:a,G:d,H:l}=this;for(let c=0;c<64;c++){let u=Vd(o,6)^Vd(o,11)^Vd(o,25),f=l+u+jhe(o,a,d)+Mhe[c]+Wf[c]|0,h=(Vd(t,2)^Vd(t,13)^Vd(t,22))+Nhe(t,n,i)|0;l=d,d=a,a=o,o=s+f|0,s=i,i=n,n=t,t=f+h|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,d=d+this.G|0,l=l+this.H|0,this.set(t,n,i,s,o,a,d,l)}roundClean(){Wf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},BF=$F(()=>new Uhe),xi=BigInt(0),xn=BigInt(1),qp=BigInt(2),Khe=BigInt(3),L6=BigInt(4),Zz=BigInt(5),Qz=BigInt(8),N9e=BigInt(9),Lhe=BigInt(16);Fhe=(r,e)=>(en(r,e)&xn)===xn,Ghe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Zhe=BigInt(0),R6=BigInt(1);({bytesToNumberBE:Xhe,hexToBytes:epe}=EF),Gp={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=Gp;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:Xhe(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Gp,t=typeof r=="string"?epe(r):r;if(!rl(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:s}=Gp._parseInt(t.subarray(2)),{d:o,l:a}=Gp._parseInt(s);if(a.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 c=l.toString(16);return c.length&1?`0${c}`:c},n=e(t(r.s)),i=e(t(r.r)),s=n.length/2,o=i.length/2,a=t(s),d=t(o);return`30${t(o+s+4)}02${d}${i}02${a}${n}`}},pu=BigInt(0),Ja=BigInt(1),M9e=BigInt(2),Xz=BigInt(3),U9e=BigInt(4);LF=class extends CF{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,Che(r);let t=f5(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 s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=r.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(r){return rE(this),this.iHash.update(r),this}digestInto(r){rE(this),kF(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:s,outputLen:o}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=s,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()}},qF=(r,e,t)=>new LF(r,e).update(t).digest();qF.create=(r,e)=>new LF(r,e);FF=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),e7=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ope=BigInt(1),z6=BigInt(2),t7=(r,e)=>(r+e/z6)/e;F6=p5(FF,void 0,void 0,{sqrt:spe}),aa=zF({a:BigInt(0),b:BigInt(7),Fp:F6,n:e7,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=e7,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ope*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=t7(s*r,e),d=t7(-n*r,e),l=en(r-a*t-d*i,e),c=en(-a*n-d*s,e),u=l>o,f=c>o;if(u&&(l=e-l),f&&(c=e-c),l>o||c>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:c}}}},BF),K9e=BigInt(0),L9e=aa.ProjectivePoint;B2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,C6=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Jd=(r,e)=>r<<32-e|r>>>e,q9e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;lpe=class{clone(){return this._cloneInto()}},z9e={}.toString;ppe=(r,e,t)=>r&e^~r&t,mpe=(r,e,t)=>r&e^r&t^e&t,ype=class extends lpe{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=C6(this.buffer)}update(r){r7(this);let{view:e,buffer:t,blockLen:n}=this;r=WF(r);let i=r.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){let a=C6(r);for(;n<=i-s;s+=n)this.process(a,s);continue}t.set(r.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){r7(this),cpe(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>n-s&&(this.process(t,0),s=0);for(let c=s;c<n;c++)e[c]=0;hpe(t,n-8,BigInt(this.length*8),i),this.process(t,0);let o=C6(r),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=a/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)o.setUint32(4*c,l[c],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:s,pos:o}=this;return r.length=n,r.pos=o,r.finished=i,r.destroyed=s,n%e&&r.buffer.set(t),r}},gpe=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]),Hf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vf=new Uint32Array(64),wpe=class extends ype{constructor(){super(64,32,8,!1),this.A=Hf[0]|0,this.B=Hf[1]|0,this.C=Hf[2]|0,this.D=Hf[3]|0,this.E=Hf[4]|0,this.F=Hf[5]|0,this.G=Hf[6]|0,this.H=Hf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:s,G:o,H:a}=this;return[r,e,t,n,i,s,o,a]}set(r,e,t,n,i,s,o,a){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=s|0,this.G=o|0,this.H=a|0}process(r,e){for(let c=0;c<16;c++,e+=4)Vf[c]=r.getUint32(e,!1);for(let c=16;c<64;c++){let u=Vf[c-15],f=Vf[c-2],h=Jd(u,7)^Jd(u,18)^u>>>3,p=Jd(f,17)^Jd(f,19)^f>>>10;Vf[c]=p+Vf[c-7]+h+Vf[c-16]|0}let{A:t,B:n,C:i,D:s,E:o,F:a,G:d,H:l}=this;for(let c=0;c<64;c++){let u=Jd(o,6)^Jd(o,11)^Jd(o,25),f=l+u+ppe(o,a,d)+gpe[c]+Vf[c]|0,h=(Jd(t,2)^Jd(t,13)^Jd(t,22))+mpe(t,n,i)|0;l=d,d=a,a=o,o=s+f|0,s=i,i=n,n=t,t=f+h|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,d=d+this.G|0,l=l+this.H|0,this.set(t,n,i,s,o,a,d,l)}roundClean(){Vf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Kb=upe(()=>new wpe);bpe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},HF=class{static digest(r){return bpe(this,arguments,void 0,function*({data:e}){return Kb(e)})}},xpe=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},n7="urn:jwk:";no=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},_pe=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},ao=class Zd{static adjustSignatureToLowS(e){return no(this,arguments,void 0,function*({signature:t}){let n=aa.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return no(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Zd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Zd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static compressPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){return aa.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return no(this,arguments,void 0,function*({key:t}){let n=yield Zd.privateKeyToBytes({privateKey:t}),i=yield Zd.getCurvePoint({keyBytes:n}),s={kty:"EC",crv:"secp256k1",x:ot.uint8Array(i.x).toBase64Url(),y:ot.uint8Array(i.y).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertDerToCompactSignature(e){return no(this,arguments,void 0,function*({derSignature:t}){return aa.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){return aa.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return no(this,void 0,void 0,function*(){let e=aa.utils.randomPrivateKey(),t=yield Zd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return no(this,arguments,void 0,function*({key:t}){var n;if(!(Vp(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,s=_pe(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return no(this,arguments,void 0,function*({privateKey:t}){if(!Vp(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return no(this,arguments,void 0,function*({publicKey:t}){if(!(y5(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ot.base64Url(t.x).toUint8Array(),s=ot.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...s])})}static sharedSecret(e){return no(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 Zd.privateKeyToBytes({privateKey:t}),s=yield Zd.publicKeyToBytes({publicKey:n});return aa.getSharedSecret(i,s,!0).slice(1)})}static sign(e){return no(this,arguments,void 0,function*({data:t,key:n}){let i=yield Zd.privateKeyToBytes({privateKey:n}),s=Kb(t);return aa.sign(s,i).toCompactRawBytes()})}static validatePrivateKey(e){return no(this,arguments,void 0,function*({privateKeyBytes:t}){return aa.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return no(this,arguments,void 0,function*({publicKeyBytes:t}){try{aa.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return no(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield Zd.publicKeyToBytes({publicKey:t}),o=Kb(i);return aa.verify(n,o,s,{lowS:!1})})}static getCurvePoint(e){return no(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=aa.getPublicKey(t));let n=aa.ProjectivePoint.fromHex(t),i=nl(n.x,32),s=nl(n.y,32);return{x:i,y:s}})}},VF=p5(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Epe=VF.create(BigInt("-3")),Spe=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Tpe=zF({a:Epe,b:Spe,Fp:VF,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},BF),Fa=Tpe,io=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Dpe=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},Ao=class Qd{static adjustSignatureToLowS(e){return io(this,arguments,void 0,function*({signature:t}){let n=Fa.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return io(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Qd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Qd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:ot.uint8Array(n.x).toBase64Url(),y:ot.uint8Array(n.y).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static compressPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){return Fa.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return io(this,arguments,void 0,function*({key:t}){let n=yield Qd.privateKeyToBytes({privateKey:t}),i=yield Qd.getCurvePoint({keyBytes:n}),s={kty:"EC",crv:"P-256",x:ot.uint8Array(i.x).toBase64Url(),y:ot.uint8Array(i.y).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertDerToCompactSignature(e){return io(this,arguments,void 0,function*({derSignature:t}){return Fa.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){return Fa.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return io(this,void 0,void 0,function*(){let e=Fa.utils.randomPrivateKey(),t=yield Qd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return io(this,arguments,void 0,function*({key:t}){var n;if(!(Vp(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,s=Dpe(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return io(this,arguments,void 0,function*({privateKey:t}){if(!Vp(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return io(this,arguments,void 0,function*({publicKey:t}){if(!(y5(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ot.base64Url(t.x).toUint8Array(),s=ot.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...s])})}static sharedSecret(e){return io(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 Qd.privateKeyToBytes({privateKey:t}),s=yield Qd.publicKeyToBytes({publicKey:n});return Fa.getSharedSecret(i,s,!0).slice(1)})}static sign(e){return io(this,arguments,void 0,function*({data:t,key:n}){let i=yield Qd.privateKeyToBytes({privateKey:n}),s=Kb(t);return Fa.sign(s,i).toCompactRawBytes()})}static validatePrivateKey(e){return io(this,arguments,void 0,function*({privateKeyBytes:t}){return Fa.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return io(this,arguments,void 0,function*({publicKeyBytes:t}){try{Fa.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return io(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield Qd.publicKeyToBytes({publicKey:t}),o=Kb(i);return Fa.verify(n,o,s,{lowS:!1})})}static getCurvePoint(e){return io(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Fa.getPublicKey(t));let n=Fa.ProjectivePoint.fromHex(t),i=nl(n.x,32),s=nl(n.y,32);return{x:i,y:s}})}},du=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},i7=class extends pE{bytesToPrivateKey(r){return du(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ao.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ao.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return du(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield ao.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ao.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return du(this,arguments,void 0,function*({key:e}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ao.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield Ao.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return du(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield ao.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield Ao.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return du(this,arguments,void 0,function*({key:e}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield ao.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield Ao.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return du(this,arguments,void 0,function*({key:e,data:t}){if(!Vp(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield ao.sign({key:e,data:t});case"P-256":return yield Ao.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return du(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!y5(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield ao.verify({key:e,signature:t,data:n});case"P-256":return yield Ao.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return du(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield ao.privateKeyToBytes({privateKey:e});case"P-256":return yield Ao.privateKeyToBytes({privateKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return du(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield ao.publicKeyToBytes({publicKey:e});case"P-256":return yield Ao.publicKeyToBytes({publicKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},T2=BigInt(4294967295),G6=BigInt(32);Ape=(r,e)=>BigInt(r>>>0)<<G6|BigInt(e>>>0),Ipe=(r,e,t)=>r>>>t,Rpe=(r,e,t)=>r<<32-t|e>>>t,Cpe=(r,e,t)=>r>>>t|e<<32-t,$pe=(r,e,t)=>r<<32-t|e>>>t,Ope=(r,e,t)=>r<<64-t|e>>>t-32,Bpe=(r,e,t)=>r>>>t-32|e<<64-t,jpe=(r,e)=>e,Npe=(r,e)=>r,Mpe=(r,e,t)=>r<<t|e>>>32-t,Upe=(r,e,t)=>e<<t|r>>>32-t,Kpe=(r,e,t)=>e<<t-32|r>>>64-t,Lpe=(r,e,t)=>r<<t-32|e>>>64-t;zpe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Fpe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gpe=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Wpe=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Hpe=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Vpe=(r,e,t,n,i,s)=>e+t+n+i+s+(r/2**32|0)|0,Jpe={fromBig:JF,split:kpe,toBig:Ape,shrSH:Ipe,shrSL:Rpe,rotrSH:Cpe,rotrSL:$pe,rotrBH:Ope,rotrBL:Bpe,rotr32H:jpe,rotr32L:Npe,rotlSH:Mpe,rotlSL:Upe,rotlBH:Kpe,rotlBL:Lpe,add:qpe,add3L:zpe,add3H:Fpe,add4L:Gpe,add4H:Wpe,add5H:Vpe,add5L:Hpe},Kt=Jpe,[Ype,Zpe]=Kt.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))),Jf=new Uint32Array(80),Yf=new Uint32Array(80),Qpe=class extends OF{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:s,Dh:o,Dl:a,Eh:d,El:l,Fh:c,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[r,e,t,n,i,s,o,a,d,l,c,u,f,h,p,m]}set(r,e,t,n,i,s,o,a,d,l,c,u,f,h,p,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=s|0,this.Dh=o|0,this.Dl=a|0,this.Eh=d|0,this.El=l|0,this.Fh=c|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)Jf[w]=r.getUint32(e),Yf[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let b=Jf[w-15]|0,T=Yf[w-15]|0,D=Kt.rotrSH(b,T,1)^Kt.rotrSH(b,T,8)^Kt.shrSH(b,T,7),I=Kt.rotrSL(b,T,1)^Kt.rotrSL(b,T,8)^Kt.shrSL(b,T,7),M=Jf[w-2]|0,C=Yf[w-2]|0,z=Kt.rotrSH(M,C,19)^Kt.rotrBH(M,C,61)^Kt.shrSH(M,C,6),L=Kt.rotrSL(M,C,19)^Kt.rotrBL(M,C,61)^Kt.shrSL(M,C,6),B=Kt.add4L(I,L,Yf[w-7],Yf[w-16]),H=Kt.add4H(B,D,z,Jf[w-7],Jf[w-16]);Jf[w]=H|0,Yf[w]=B|0}let{Ah:t,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:d,Dl:l,Eh:c,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let b=Kt.rotrSH(c,u,14)^Kt.rotrSH(c,u,18)^Kt.rotrBH(c,u,41),T=Kt.rotrSL(c,u,14)^Kt.rotrSL(c,u,18)^Kt.rotrBL(c,u,41),D=c&f^~c&p,I=u&h^~u&m,M=Kt.add5L(v,T,I,Zpe[w],Yf[w]),C=Kt.add5H(M,y,b,D,Ype[w],Jf[w]),z=M|0,L=Kt.rotrSH(t,n,28)^Kt.rotrBH(t,n,34)^Kt.rotrBH(t,n,39),B=Kt.rotrSL(t,n,28)^Kt.rotrBL(t,n,34)^Kt.rotrBL(t,n,39),H=t&i^t&o^i&o,ee=n&s^n&a^s&a;y=p|0,v=m|0,p=f|0,m=h|0,f=c|0,h=u|0,{h:c,l:u}=Kt.add(d|0,l|0,C|0,z|0),d=o|0,l=a|0,o=i|0,a=s|0,i=t|0,s=n|0;let R=Kt.add3L(z,B,ee);t=Kt.add3H(R,C,L,H),n=R|0}({h:t,l:n}=Kt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:s}=Kt.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:o,l:a}=Kt.add(this.Ch|0,this.Cl|0,o|0,a|0),{h:d,l}=Kt.add(this.Dh|0,this.Dl|0,d|0,l|0),{h:c,l:u}=Kt.add(this.Eh|0,this.El|0,c|0,u|0),{h:f,l:h}=Kt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Kt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:v}=Kt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,s,o,a,d,l,c,u,f,h,p,m,y,v)}roundClean(){Jf.fill(0),Yf.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)}},YF=$F(()=>new Qpe),zc=BigInt(0),oa=BigInt(1),D2=BigInt(2),Xpe=BigInt(8),eme={zip215:!0};yb=BigInt(0),$6=BigInt(1);Lb=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),o7=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),F9e=BigInt(0),ime=BigInt(1),W6=BigInt(2),ome=BigInt(5),s7=BigInt(10),sme=BigInt(20),ame=BigInt(40),a7=BigInt(80);Xa=p5(Lb,void 0,!0),qb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Xa,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:YF,randomBytes:h5,adjustScalarBytes:QF,uvRatio:cme},Kp=w5(qb);G9e=w5({...qb,domain:XF}),W9e=w5({...qb,domain:XF,prehash:YF}),Pb=nme({P:Lb,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=Lb,{pow_p_5_8:t,b2:n}=ZF(r);return en(Dn(t,BigInt(3),e)*n,e)},adjustScalarBytes:QF,randomBytes:h5});ume=(Xa.ORDER+BigInt(3))/BigInt(8),H9e=Xa.pow(W6,ume),V9e=Xa.sqrt(Xa.neg(Xa.ONE)),J9e=(Xa.ORDER-BigInt(5))/BigInt(8),Y9e=BigInt(486662),Z9e=Jhe(Xa,Xa.neg(BigInt(486664))),Q9e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),X9e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eze=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),tze=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),rze=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ga=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},fme=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},co=class th{static bytesToPrivateKey(e){return Ga(this,arguments,void 0,function*({privateKeyBytes:t}){let n=Kp.getPublicKey(t),i={crv:"Ed25519",d:ot.uint8Array(t).toBase64Url(),kty:"OKP",x:ot.uint8Array(n).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return Ga(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:ot.uint8Array(t).toBase64Url()};return n.kid=yield Tr({jwk:n}),n})}static computePublicKey(e){return Ga(this,arguments,void 0,function*({key:t}){let n=yield th.privateKeyToBytes({privateKey:t}),i=Kp.getPublicKey(n),s={kty:"OKP",crv:"Ed25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static convertPrivateKeyToX25519(e){return Ga(this,arguments,void 0,function*({privateKey:t}){let n=yield th.privateKeyToBytes({privateKey:t}),i=lme(n),s=Pb.getPublicKey(i),o={kty:"OKP",crv:"X25519",d:ot.uint8Array(i).toBase64Url(),x:ot.uint8Array(s).toBase64Url()};return o.kid=yield Tr({jwk:o}),o})}static convertPublicKeyToX25519(e){return Ga(this,arguments,void 0,function*({publicKey:t}){let n=yield th.publicKeyToBytes({publicKey:t});if(!(yield th.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=dme(n),s={kty:"OKP",crv:"X25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static generateKey(){return Ga(this,void 0,void 0,function*(){let e=Kp.utils.randomPrivateKey(),t=yield th.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return Ga(this,arguments,void 0,function*({key:t}){var n;if(!(gu(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,s=fme(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return Ga(this,arguments,void 0,function*({privateKey:t}){if(!gu(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ga(this,arguments,void 0,function*({publicKey:t}){if(!g5(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ot.base64Url(t.x).toUint8Array()})}static sign(e){return Ga(this,arguments,void 0,function*({key:t,data:n}){let i=yield th.privateKeyToBytes({privateKey:t});return Kp.sign(n,i)})}static validatePublicKey(e){return Ga(this,arguments,void 0,function*({publicKeyBytes:t}){try{Kp.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ga(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=yield th.publicKeyToBytes({publicKey:t});return Kp.verify(n,i,s)})}},lu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},hme=class extends pE{bytesToPrivateKey(r){return lu(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield co.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return lu(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield co.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return lu(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield co.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return lu(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield co.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return lu(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield co.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return lu(this,arguments,void 0,function*({key:e,data:t}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield co.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return lu(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!g5(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield co.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return lu(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield co.privateKeyToBytes({privateKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return lu(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield co.publicKeyToBytes({publicKey:e});default:throw new Qa(ks.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},pme=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},mme=class extends pE{digest(r){return pme(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield HF.digest({data:t})}})}},Zf=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},yme=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},Rg=class _b{static bytesToPrivateKey(e){return Zf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=Pb.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:ot.uint8Array(t).toBase64Url(),x:ot.uint8Array(n).toBase64Url()};return i.kid=yield Tr({jwk:i}),i})}static bytesToPublicKey(e){return Zf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:ot.uint8Array(t).toBase64Url()};return n.kid=yield Tr({jwk:n}),n})}static computePublicKey(e){return Zf(this,arguments,void 0,function*({key:t}){let n=yield _b.privateKeyToBytes({privateKey:t}),i=Pb.getPublicKey(n),s={kty:"OKP",crv:"X25519",x:ot.uint8Array(i).toBase64Url()};return s.kid=yield Tr({jwk:s}),s})}static generateKey(){return Zf(this,void 0,void 0,function*(){let e=Pb.utils.randomPrivateKey(),t=yield _b.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield Tr({jwk:t}),t})}static getPublicKey(e){return Zf(this,arguments,void 0,function*({key:t}){var n;if(!(gu(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,s=yme(t,["d"]);return(n=s.kid)!==null&&n!==void 0||(s.kid=yield Tr({jwk:s})),s})}static privateKeyToBytes(e){return Zf(this,arguments,void 0,function*({privateKey:t}){if(!gu(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return ot.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Zf(this,arguments,void 0,function*({publicKey:t}){if(!g5(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return ot.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return Zf(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 _b.privateKeyToBytes({privateKey:t}),s=yield _b.publicKeyToBytes({publicKey:n});return Pb.getSharedSecret(i,s)})}},gb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},gme=class extends pE{bytesToPrivateKey(r){return gb(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Rg.bytesToPrivateKey({privateKeyBytes:t});default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return gb(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Rg.computePublicKey({key:e});default:throw new Qa(ks.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return gb(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Rg.generateKey();default:throw new Qa(ks.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return gb(this,arguments,void 0,function*({key:e}){if(!gu(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Rg.getPublicKey({key:e});default:throw new Qa(ks.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return gb(this,arguments,void 0,function*({privateKey:e}){return Rg.privateKeyToBytes({privateKey:e})})}},uu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},O6={Ed25519:{implementation:hme,names:["Ed25519"]},secp256k1:{implementation:i7,names:["ES256K","secp256k1"]},secp256r1:{implementation:i7,names:["ES256","secp256r1"]},"SHA-256":{implementation:mme,names:["SHA-256"]},X25519:{implementation:gme,names:["X25519"]}},Wc=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new fhe}digest(r){return uu(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return uu(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return uu(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=`${n7}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return uu(this,arguments,void 0,function*({key:e}){let t=yield Tr({jwk:e});return`${n7}${t}`})}getPublicKey(r){return uu(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 uu(this,arguments,void 0,function*({key:e}){var t;if(!Ppe(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 Tr({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return uu(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 uu(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=O6[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 O6){let i=O6[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 uu(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})}},wme=class eG{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 fpe(e)}static randomUuid(){return B2.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),n=Math.ceil(Math.log2(t)/8),i=Math.pow(2,n*8),s=i-i%t,o;do{o=0;let a=eG.randomBytes(n);for(let d of a)o=o*256+d}while(o>=s);return(o%t).toString().padStart(e,"0")}},vme=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];_e=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}};_e.uint=new _e(0,"uint",!0);_e.negint=new _e(1,"negint",!0);_e.bytes=new _e(2,"bytes",!0);_e.string=new _e(3,"string",!0);_e.array=new _e(4,"array",!1);_e.map=new _e(5,"map",!1);_e.tag=new _e(6,"tag",!1);_e.float=new _e(7,"float",!0);_e.false=new _e(7,"false",!0);_e.true=new _e(7,"true",!0);_e.null=new _e(7,"null",!0);_e.undefined=new _e(7,"undefined",!0);_e.break=new _e(7,"break",!0);nt=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}`}},Vb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Pme=new TextEncoder;_me=24,Eme=200,Sme=Vb?r=>r.length>=_me?globalThis.Buffer.from(r):c7(r):r=>r.length>=Eme?Pme.encode(r):c7(r),fu=r=>Uint8Array.from(r),Tme=Vb?(r,e,t)=>nE(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Dme=Vb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),tG(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},kme=Vb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);Ame=256,nG=class{constructor(r=Ame){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=kme(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=Tme(t,0,this.cursor)}else e=Dme(this.chunks,this.cursor);return r&&this.reset(),e}},Ime=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:",iG="CBOR encode error:",Jb=[];Jb[23]=1;Jb[24]=2;Jb[25]=3;Jb[26]=5;Jb[27]=9;lo=[24,256,65536,4294967296,BigInt("18446744073709551616")];om.encodedSize=function(r){return tc.encodedSize(r.value)};tc.encodedSize=function(r){return r<lo[0]?1:r<lo[1]?2:r<lo[2]?3:r<lo[3]?5:9};om.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};v5=BigInt(-1),oG=BigInt(1);b5.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*v5-oG:e*-1-1;return t<lo[0]?1:t<lo[1]?2:t<lo[2]?3:t<lo[3]?5:9};b5.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};yE.encodedSize=function(r){let e=iE(r);return tc.encodedSize(e.length)+e.length};yE.compareTokens=function(r,e){return Fme(iE(r),iE(e))};d7=new TextDecoder,Gme=32;Qme=yE;x5.compareTokens=om.compareTokens;x5.encodedSize=function(r){return tc.encodedSize(r.value)};P5.compareTokens=om.compareTokens;P5.encodedSize=function(r){return tc.encodedSize(r.value)};_5.compareTokens=om.compareTokens;_5.encodedSize=function(r){return tc.encodedSize(r.value)};sG=20,aG=21,cG=22,dG=23;S5.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){uG(t);let n=T5(Fc,1);if(t===n||Number.isNaN(t))return 3;if(fG(t),n=D5(Fc,1),t===n)return 5}return 9};lG=new ArrayBuffer(9),Ha=new DataView(lG,1),Fc=new Uint8Array(lG,0);S5.compareTokens=om.compareTokens;Be=[];for(let r=0;r<=23;r++)Be[r]=mr;Be[24]=Rme;Be[25]=Cme;Be[26]=$me;Be[27]=Ome;Be[28]=mr;Be[29]=mr;Be[30]=mr;Be[31]=mr;for(let r=32;r<=55;r++)Be[r]=mr;Be[56]=Bme;Be[57]=jme;Be[58]=Nme;Be[59]=Mme;Be[60]=mr;Be[61]=mr;Be[62]=mr;Be[63]=mr;for(let r=64;r<=87;r++)Be[r]=Ume;Be[88]=Kme;Be[89]=Lme;Be[90]=qme;Be[91]=zme;Be[92]=mr;Be[93]=mr;Be[94]=mr;Be[95]=gE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Be[r]=Hme;Be[120]=Vme;Be[121]=Jme;Be[122]=Yme;Be[123]=Zme;Be[124]=mr;Be[125]=mr;Be[126]=mr;Be[127]=gE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Be[r]=Xme;Be[152]=eye;Be[153]=tye;Be[154]=rye;Be[155]=nye;Be[156]=mr;Be[157]=mr;Be[158]=mr;Be[159]=iye;for(let r=160;r<=183;r++)Be[r]=oye;Be[184]=sye;Be[185]=aye;Be[186]=cye;Be[187]=dye;Be[188]=mr;Be[189]=mr;Be[190]=mr;Be[191]=lye;for(let r=192;r<=215;r++)Be[r]=uye;Be[216]=fye;Be[217]=hye;Be[218]=pye;Be[219]=mye;Be[220]=mr;Be[221]=mr;Be[222]=mr;Be[223]=mr;for(let r=224;r<=243;r++)Be[r]=gE("simple values are not supported");Be[244]=mr;Be[245]=mr;Be[246]=mr;Be[247]=yye;Be[248]=gE("simple values are not supported");Be[249]=wye;Be[250]=vye;Be[251]=bye;Be[252]=mr;Be[253]=mr;Be[254]=mr;Be[255]=gye;vu=[];for(let r=0;r<24;r++)vu[r]=new nt(_e.uint,r,1);for(let r=-1;r>=-24;r--)vu[31-r]=new nt(_e.negint,r,1);vu[64]=new nt(_e.bytes,new Uint8Array(0),1);vu[96]=new nt(_e.string,"",1);vu[128]=new nt(_e.array,0,1);vu[160]=new nt(_e.map,0,1);vu[244]=new nt(_e.false,!1,1);vu[245]=new nt(_e.true,!0,1);vu[246]=new nt(_e.null,null,1);_ye=Object.freeze({float64:!0,mapSorter:kye,quickEncodeToken:Pye});Sye=Eye(),Tye=new nG,l7=class pG{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(`${iG} object contains circular references`);return new pG(t,e)}},Qf={null:new nt(_e.null,null),undefined:new nt(_e.undefined,void 0),true:new nt(_e.true,!0),false:new nt(_e.false,!1),emptyArray:new nt(_e.array,0),emptyMap:new nt(_e.map,0)},ah={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new nt(_e.float,r):r>=0?new nt(_e.uint,r):new nt(_e.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new nt(_e.uint,r):new nt(_e.negint,r)},Uint8Array(r,e,t,n){return new nt(_e.bytes,r)},string(r,e,t,n){return new nt(_e.string,r)},boolean(r,e,t,n){return r?Qf.true:Qf.false},null(r,e,t,n){return Qf.null},undefined(r,e,t,n){return Qf.undefined},ArrayBuffer(r,e,t,n){return new nt(_e.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new nt(_e.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Qf.emptyArray,new nt(_e.break)]:Qf.emptyArray;n=l7.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=j2(o,t,n);return t.addBreakTokens?[new nt(_e.array,r.length),i,new nt(_e.break)]:[new nt(_e.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length,a;if(o){a=new Array(o),n=l7.createCheck(n,r);let d=!i&&t.ignoreUndefinedProperties,l=0;for(let c of s){let u=i?r.get(c):r[c];d&&u===void 0||(a[l++]=[j2(c,t,n),j2(u,t,n)])}l<o&&(a.length=l)}return a?.length?(Dye(a,t),t.addBreakTokens?[new nt(_e.map,a.length),a,new nt(_e.break)]:[new nt(_e.map,a.length),a]):t.addBreakTokens===!0?[Qf.emptyMap,new nt(_e.break)]:Qf.emptyMap}};ah.Map=ah.Object;ah.Buffer=ah.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ah[`${r}Array`]=ah.DataView;nze=_e.uint.majorEncoded,ize=_e.negint.majorEncoded,oze=_e.bytes.majorEncoded,sze=_e.string.majorEncoded,aze=_e.array.majorEncoded,cze=_e.float.majorEncoded|sG,dze=_e.float.majorEncoded|aG,lze=_e.float.majorEncoded|cG,uze=_e.float.majorEncoded|dG,fze=BigInt(-1),hze=BigInt(1);pze=Symbol.for("DONE"),mze=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(f7||(f7={}));(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"})(Io||(Io={}));(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"})(Za||(Za={}));(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"})(h7||(h7={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(p7||(p7={}));yze={"P-256":Io.P256,"P-384":Io.P384,"P-521":Io.P521,X25519:Io.X25519,Ed25519:Io.Ed25519,Ed448:Io.Ed448,secp256k1:Io.Secp256k1},gze={[Io.P256]:"P-256",[Io.P384]:"P-384",[Io.P521]:"P-521",[Io.X25519]:"X25519",[Io.Ed25519]:"Ed25519",[Io.Ed448]:"Ed448",[Io.Secp256k1]:"secp256k1"},wze={EdDSA:Za.EdDSA,ES256:Za.ES256,ES384:Za.ES384,ES512:Za.ES512,ES256K:Za.ES256K},vze={[Za.EdDSA]:"EdDSA",[Za.ES256]:"ES256",[Za.ES384]:"ES384",[Za.ES512]:"ES512",[Za.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(m7||(m7={}));(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"})(y7||(y7={}));(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"})(g7||(g7={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(w7||(w7={}));k5={};o5(k5,{extractDidFragment:()=>rs,getServices:()=>Iye,getVerificationMethodByKey:()=>Rye,getVerificationMethodTypes:()=>yG,getVerificationMethods:()=>wE,getVerificationRelationshipsById:()=>gG,isDidService:()=>wG,isDidVerificationMethod:()=>oE,isDwnDidService:()=>Cye,isPortableDid:()=>Zg,keyBytesToMultibaseId:()=>vG,multibaseIdToKeyBytes:()=>bG});Ro=class xG{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}),s=await this.keyManager.exportKey({keyUri:i});t.push({...s})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(o=>rs(o.id)===(rs(e?.methodId)??rs(this.document.assertionMethod?.[0])));if(!t?.publicKeyJwk)throw new rt("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}),s=this.keyManager;return{algorithm:wme.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:o}){return await s.sign({data:o,keyUri:n})},async verify({data:o,signature:a}){return await s.verify({data:o,key:i,signature:a})}}}static async import({portableDid:e,keyManager:t=new Wc}){let n=wE({didDocument:e.document});if(n.length===0)throw new rt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let s=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:s}).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 s=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:s})}return new xG({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},Qb=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()")}},PG=(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))(PG||{}),A5=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(A5||{}),_G=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(_G||{}),v7="0123456789abcdef",EG=[],b7=[];for(let r=0;r<256;r++)EG[r]=v7[r>>4&15]+v7[r&15],r<16&&(r<10?b7[48+r]=r:b7[87+r]=r);$ye=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=EG[r[n++]];return t},Oye=(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,s=t;for(;s--;)i-=r[s].length,n.set(r[s],i);return n},x7="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bye=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(wb=0;wb<x7.length;wb++)Bye[x7.charCodeAt(wb)]=wb;jye=new TextDecoder,SG=(r,e)=>e?new TextDecoder(e).decode(r):jye.decode(r),Nye=new TextEncoder,wu=r=>Nye.encode(r),P7=typeof window<"u"?window:self,_7=P7.crypto||P7.msCrypto||{},bze=_7.subtle||_7.webkitSubtle;br.bytes=-1;br._floatConversionDetected=!1;br._encode=function(r,e){if(e!=null)switch(TG(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}};vE=new Uint8Array([101]),DG=new Uint8Array([100]),kG=new Uint8Array([108]);br.buffer=function(r,e){r.push(wu(e.length+":"),e)};br.string=function(r,e){r.push(wu(wu(e).byteLength+":"+e))};br.number=function(r,e){if(Number.isInteger(e))return r.push(wu("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,s=n*t+i;r.push(wu("i"+s+"e")),s!==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 "'+s+'"'),console.trace())};br.dict=function(r,e){r.push(DG);let t=0,n,i=Object.keys(e).sort(),s=i.length;for(;t<s;t++)n=i[t],e[n]!=null&&(br.string(r,n),br._encode(r,e[n]));r.push(vE)};br.dictMap=function(r,e){r.push(DG);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(vE)};br.list=function(r,e){let t=0,n=e.length;for(r.push(kG);t<n;t++)e[t]!=null&&br._encode(r,e[t]);r.push(vE)};br.listSet=function(r,e){r.push(kG);for(let t of e)t!=null&&br._encode(r,t);r.push(vE)};Mye=br,Uye=105,Kye=58,Lye=100,qye=108,I5=101;vt.bytes=0;vt.position=0;vt.data=null;vt.encoding=null;vt.next=function(){switch(vt.data[vt.position]){case Lye:return vt.dictionary();case qye:return vt.list();case Uye:return vt.integer();default:return vt.buffer()}};vt.find=function(r){let e=vt.position,t=vt.data.length,n=vt.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)+"]")};vt.dictionary=function(){vt.position++;let r={};for(;vt.data[vt.position]!==I5;){let e=vt.buffer(),t=SG(e);t.includes("\uFFFD")&&(t=$ye(e)),r[t]=vt.next()}return vt.position++,r};vt.list=function(){vt.position++;let r=[];for(;vt.data[vt.position]!==I5;)r.push(vt.next());return vt.position++,r};vt.integer=function(){let r=vt.find(I5),e=AG(vt.data,vt.position+1,r);return vt.position+=r+1-vt.position,e};vt.buffer=function(){let r=vt.find(Kye),e=AG(vt.data,vt.position,r),t=++r+e;return vt.position=t,vt.encoding?SG(vt.data.slice(r,t)):vt.data.slice(r,t)};zye=vt;IG=bE,Jye=IG,RG={encode:Mye,decode:zye,byteLength:IG,encodingLength:Jye},Yye=/^(\d{1,3}\.){3,3}\d{1,3}$/,Zye=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,tl={name:"v4",size:4,isFormat:r=>Yye.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let s=0;s<n;){let o=r.charCodeAt(s++);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]}`}},sh={name:"v6",size:16,isFormat:r=>r.length>0&&Zye.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,s=0,o=0,a=!0,d=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let c=r.charCodeAt(l);c===58?(a?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(d===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=s>>8),t<n-1&&(e[t+1]=s&255),t+=2),s=0,o=0),a=!0,d=!1):c===46?(t<n&&(e[t]=o),t++,o=0,s=0,a=!1,d=!0):(a=!1,c>=97?c-=87:c>=65?c-=55:(c-=48,o=o*10+c),s=(s<<4)+c)}if(a===!1)d===!0?(t<n&&(e[t]=o),t++):(t<n&&(e[t]=s>>8),t<n-1&&(e[t+1]=s&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}/,"::")}};Fb.bytes=0;e1.bytes=0;Qp=r=>r instanceof Uint8Array;Eb={},jG=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),s=i.toUpperCase(),o=r<<4|n,a=`${e}${i}`;jG[o]=a,Eb[a]=o,Eb[`${t}${i}`]=o,Eb[`${e}${s}`]=o,Eb[`${t}${s}`]=o}}sge=Math.pow(2,24),age=Math.pow(2,16),cge=Math.pow(2,8),mu=(r,e)=>r[e]*sge+r[e+1]*age+r[e+2]*cge+r[e+3],Lt=(r,e)=>r[e]<<8|r[e+1],yu=(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),st=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);lge=0,T7=32768,H6=32768,uge=~H6,NG=32768,fge=~NG;Ve=Hr({encode(r,e,t){e||(e=new Uint8Array(Ve.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let s=i.split(".");for(let o=0;o<s.length;o++){let a=C5(e,s[o],t+1);e[t]=a,t+=a+1}}return e[t++]=0,Ve.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,s=0,o=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let a=r[e++];if(s+=o?0:1,a===0)break;if(a&192)if((a&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let d=Lt(r,e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,s+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+a>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=a+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(e1(r,e,e+a)),e+=a,s+=o?0:a}}return Ve.decode.bytes=s,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:ch(r.replace(/^\.|\.$/gm,""))+2}}),bi=Hr({encode(r,e,t){e||(e=new Uint8Array(bi.encodingLength(r))),t||(t=0);let n=C5(e,r,t+1);return e[t]=n,bi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=e1(r,e+1,e+1+t);return bi.decode.bytes=t+1,n},encodingLength(r){return ch(r)+1}}),Cg=Hr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(Cg.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?T7:lge;return st(e,r.id||0,t),st(e,n|i,t+2),st(e,r.questions.length,t+4),st(e,r.answers.length,t+6),st(e,r.authorities.length,t+8),st(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=Lt(r,e+2);return{id:Lt(r,e),type:t&T7?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:rge(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:tge(t&15),questions:new Array(Lt(r,e+4)),answers:new Array(Lt(r,e+6)),authorities:new Array(Lt(r,e+8)),additionals:new Array(Lt(r,e+10))}},encodingLength(){return 12}}),N2=Hr({encode(r,e,t){e||(e=new Uint8Array(N2.encodingLength(r))),t||(t=0);let n=r.length;return st(e,n,t),la(r,e,t+2,0,n),N2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n=r.slice(e+2,e+2+t);return N2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),M2=Hr({encode(r,e,t){return e||(e=new Uint8Array(M2.encodingLength(r))),t||(t=0),Ve.encode(r,e,t+2),st(e,Ve.encode.bytes,t),M2.encode.bytes=Ve.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n=Ve.decode(r,e+2);return M2.decode.bytes=t+2,n},encodingLength(r){return Ve.encodingLength(r)+2}}),U2=Hr({encode(r,e,t){e||(e=new Uint8Array(U2.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.mname,e,t),t+=Ve.encode.bytes,Ve.encode(r.rname,e,t),t+=Ve.encode.bytes,yu(e,r.serial||0,t),t+=4,yu(e,r.refresh||0,t),t+=4,yu(e,r.retry||0,t),t+=4,yu(e,r.expire||0,t),t+=4,yu(e,r.minimum||0,t),t+=4,st(e,t-n-2,n),U2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=Ve.decode(r,e),e+=Ve.decode.bytes,n.rname=Ve.decode(r,e),e+=Ve.decode.bytes,n.serial=mu(r,e),e+=4,n.refresh=mu(r,e),e+=4,n.retry=mu(r,e),e+=4,n.expire=mu(r,e),e+=4,n.minimum=mu(r,e),e+=4,U2.decode.bytes=e-t,n},encodingLength(r){return 22+Ve.encodingLength(r.mname)+Ve.encodingLength(r.rname)}}),K2=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]=R5(r[i])),!Qp(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(K2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,la(i,e,t,0,i.length),t+=i.length}),st(e,t-n-2,n),K2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Lt(r,e);e+=2;let i=[];for(;n>0;){let s=r[e++];if(--n,n<s)throw new Error("Buffer overflow");i.push(r.slice(e,e+s)),e+=s,n-=s}return K2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=ch(t)+1:e+=t.length+1}),e}}),L2=Hr({encode(r,e,t){e||(e=new Uint8Array(L2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=R5(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return la(r,e,t,0,i),t+=i,st(e,t-n-2,n),L2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Lt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,L2.decode.bytes=e-t,i},encodingLength(r){return r?(Qp(r)?r.length:ch(r))+2:2}}),q2=Hr({encode(r,e,t){e||(e=new Uint8Array(q2.encodingLength(r))),t||(t=0);let n=t;return t+=2,bi.encode(r.cpu,e,t),t+=bi.encode.bytes,bi.encode(r.os,e,t),t+=bi.encode.bytes,st(e,t-n-2,n),q2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=bi.decode(r,e),e+=bi.decode.bytes,n.os=bi.decode(r,e),e+=bi.decode.bytes,q2.decode.bytes=e-t,n},encodingLength(r){return bi.encodingLength(r.cpu)+bi.encodingLength(r.os)+2}}),Ug=Hr({encode(r,e,t){return e||(e=new Uint8Array(Ug.encodingLength(r))),t||(t=0),Ve.encode(r,e,t+2),st(e,Ve.encode.bytes,t),Ug.encode.bytes=Ve.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Ve.decode(r,e+2);return Ug.decode.bytes=Ve.decode.bytes+2,t},encodingLength(r){return Ve.encodingLength(r)+2}}),z2=Hr({encode(r,e,t){e||(e=new Uint8Array(z2.encodingLength(r))),t||(t=0),st(e,r.priority||0,t+2),st(e,r.weight||0,t+4),st(e,r.port||0,t+6),Ve.encode(r.target,e,t+8);let n=Ve.encode.bytes+6;return st(e,n,t),z2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Lt(r,e),n={};return n.priority=Lt(r,e+2),n.weight=Lt(r,e+4),n.port=Lt(r,e+6),n.target=Ve.decode(r,e+8),z2.decode.bytes=t+2,n},encodingLength(r){return 8+Ve.encodingLength(r.target)}}),nh=Hr({encode(r,e,t){let n=nh.encodingLength(r);return e||(e=new Uint8Array(nh.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=nh.ISSUER_CRITICAL),st(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,bi.encode(r.tag,e,t),t+=bi.encode.bytes,C5(e,r.value,t),t+=ch(r.value),nh.encode.bytes=n,e},decode(r,e){e||(e=0);let t=Lt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=bi.decode(r,e),e+=bi.decode.bytes,i.value=e1(r,e,n+t),i.issuerCritical=!!(i.flags&nh.ISSUER_CRITICAL),nh.decode.bytes=t+2,i},encodingLength(r){return bi.encodingLength(r.tag)+bi.encodingLength(r.value)+2}});nh.ISSUER_CRITICAL=128;F2=Hr({encode(r,e,t){e||(e=new Uint8Array(F2.encodingLength(r))),t||(t=0);let n=t;return t+=2,st(e,r.preference||0,t),t+=2,Ve.encode(r.exchange,e,t),t+=Ve.encode.bytes,st(e,t-n-2,n),F2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=Lt(r,e),e+=2,n.exchange=Ve.decode(r,e),e+=Ve.decode.bytes,F2.decode.bytes=e-t,n},encodingLength(r){return 4+Ve.encodingLength(r.exchange)}}),MG=Hr({encode(r,e,t){return e||(e=new Uint8Array(MG.encodingLength(r))),t||(t=0),st(e,4,t),t+=2,tl.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,tl.decode(r,e)},bytes:6}),G2=Hr({encode(r,e,t){return e||(e=new Uint8Array(G2.encodingLength(r))),t||(t=0),st(e,16,t),t+=2,sh.encode(r,e,t),G2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=sh.decode(r,e);return G2.decode.bytes=18,t},bytes:18}),D7=r=>new Uint8Array(r),hu=Hr({encode(r,e,t){e||(e=new Uint8Array(hu.encodingLength(r))),t||(t=0);let n=t,i=E7(r.code);if(st(e,i,t),t+=2,r.data)st(e,r.data.length,t),t+=2,la(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let s=r.sourcePrefixLength||0,o=r.family||Qye(r.ip,D7),a=Xye(r.ip,D7),d=Math.ceil(s/8);st(e,d+4,t),t+=2,st(e,o,t),t+=2,e[t++]=s,e[t++]=r.scopePrefixLength||0,la(a,e,t,0,d),t+=d}break;case 11:r.timeout?(st(e,2,t),t+=2,st(e,r.timeout,t),t+=2):(st(e,0,t),t+=2);break;case 12:{let s=r.length||0;st(e,s,t),t+=2,e.fill(0,t,t+s),t+=s}break;case 14:{let s=r.tags.length*2;st(e,s,t),t+=2;for(let o of r.tags)st(e,o,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return hu.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=Lt(r,e),t.type=nge(t.code),e+=2;let n=Lt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=Lt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);la(r,i,0,e,e+n-4),t.ip=ege(i)}break;case 11:n>0&&(t.timeout=Lt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(Lt(r,e)),e+=2}return hu.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(E7(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}`)}}),ih=Hr({encode(r,e,t){e||(e=new Uint8Array(ih.encodingLength(r))),t||(t=0);let n=t,i=Ng(r,hu);return st(e,i,t),t=Ib(r,hu,e,t+2),ih.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=Lt(r,e);e+=2;let s=0;for(;i>0;)n[s++]=hu.decode(r,e),e+=hu.decode.bytes,i-=hu.decode.bytes;return ih.decode.bytes=e-t,n},encodingLength(r){return 2+Ng(r||[],hu)}}),el=Hr({encode(r,e,t){e||(e=new Uint8Array(el.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!Qp(i))throw new Error("Key must be a Buffer");return t+=2,st(e,r.flags,t),t+=2,e[t]=el.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,la(i,e,t,0,i.length),t+=i.length,el.encode.bytes=t-n,st(e,el.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);if(e+=2,n.flags=Lt(r,e),e+=2,r[e]!==el.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,el.decode.bytes=e-t,n},encodingLength(r){return 6+ch(r.key)}});el.PROTOCOL_DNSSEC=3;el.ZONE_KEY=128;el.SECURE_ENTRYPOINT=32768;Sb=Hr({encode(r,e,t){e||(e=new Uint8Array(Sb.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!Qp(i))throw new Error("Signature must be a Buffer");return t+=2,st(e,zb(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,yu(e,r.originalTTL,t),t+=4,yu(e,r.expiration,t),t+=4,yu(e,r.inception,t),t+=4,st(e,r.keyTag,t),t+=2,Ve.encode(r.signersName,e,t),t+=Ve.encode.bytes,la(i,e,t,0,i.length),t+=i.length,Sb.encode.bytes=t-n,st(e,Sb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.typeCovered=xE(Lt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=mu(r,e),e+=4,n.expiration=mu(r,e),e+=4,n.inception=mu(r,e),e+=4,n.keyTag=Lt(r,e),e+=2,n.signersName=Ve.decode(r,e),e+=Ve.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,Sb.decode.bytes=e-t,n},encodingLength(r){return 20+Ve.encodingLength(r.signersName)+ch(r.signature)}}),Tb=Hr({encode(r,e,t){e||(e=new Uint8Array(Tb.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.mbox||".",e,t),t+=Ve.encode.bytes,Ve.encode(r.txt||".",e,t),t+=Ve.encode.bytes,Tb.encode.bytes=t-n,st(e,Tb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=Ve.decode(r,e)||".",e+=Ve.decode.bytes,n.txt=Ve.decode(r,e)||".",e+=Ve.decode.bytes,Tb.decode.bytes=e-t,n},encodingLength(r){return 2+Ve.encodingLength(r.mbox||".")+Ve.encodingLength(r.txt||".")}}),da=Hr({encode(r,e,t){e||(e=new Uint8Array(da.encodingLength(r))),t||(t=0);let n=t,i=[];for(let s=0;s<r.length;s++){let o=zb(r[s]);i[o>>8]===void 0&&(i[o>>8]=[]),i[o>>8][o>>3&31]|=1<<7-(o&7)}for(let s=0;s<i.length;s++)if(i[s]!==void 0){let o=R5(i[s]);e[t]=s,t+=1,e[t]=o.length,t+=1,la(o,e,t,0,o.length),t+=o.length}return da.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let s=r[e];e+=1;let o=r[e];e+=1;for(let a=0;a<o;a++){let d=r[e+a];for(let l=0;l<8;l++)if(d&1<<7-l){let c=xE(s<<8|a<<3|l);i.push(c)}}e+=o}return da.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=zb(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}}),Db=Hr({encode(r,e,t){e||(e=new Uint8Array(Db.encodingLength(r))),t||(t=0);let n=t;return t+=2,Ve.encode(r.nextDomain,e,t),t+=Ve.encode.bytes,da.encode(r.rrtypes,e,t),t+=da.encode.bytes,Db.encode.bytes=t-n,st(e,Db.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.nextDomain=Ve.decode(r,e),e+=Ve.decode.bytes,n.rrtypes=da.decode(r,e,i-(e-t)),e+=da.decode.bytes,Db.decode.bytes=e-t,n},encodingLength(r){return 2+Ve.encodingLength(r.nextDomain)+da.encodingLength(r.rrtypes)}}),kb=Hr({encode(r,e,t){e||(e=new Uint8Array(kb.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!Qp(i))throw new Error("salt must be a Buffer");let s=r.nextDomain;if(!Qp(s))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,st(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,la(i,e,t,0,i.length),t+=i.length,e[t]=s.length,t+=1,la(s,e,t,0,s.length),t+=s.length,da.encode(r.rrtypes,e,t),t+=da.encode.bytes,kb.encode.bytes=t-n,st(e,kb.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=Lt(r,e),e+=2;let s=r[e];e+=1,n.salt=r.slice(e,e+s),e+=s;let o=r[e];return e+=1,n.nextDomain=r.slice(e,e+o),e+=o,n.rrtypes=da.decode(r,e,i-(e-t)),e+=da.decode.bytes,kb.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+da.encodingLength(r.rrtypes)}}),Ab=Hr({encode(r,e,t){e||(e=new Uint8Array(Ab.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!Qp(i))throw new Error("Digest must be a Buffer");return t+=2,st(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,la(i,e,t,0,i.length),t+=i.length,Ab.encode.bytes=t-n,st(e,Ab.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Lt(r,e);return e+=2,n.keyTag=Lt(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,Ab.decode.bytes=e-t,n},encodingLength(r){return 6+ch(r.digest)}}),jg=Hr({encode(r,e,t){e||(e=new Uint8Array(jg.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=S7(r.fingerprint),s=V6(r.hash);if(i!==s)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${s}`);return oge(e,r.fingerprint,t,t+=i),jg.encode.bytes=t-n,st(e,jg.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=V6(n.hash);return n.fingerprint=ige(r,e,e+i),e+=i,jg.decode.bytes=e-t,n},encodingLength(r){return 4+S7(r.fingerprint)}});jg.getFingerprintLengthForHashType=V6;Va=Hr({encode(r,e,t){e||(e=new Uint8Array(Va.encodingLength(r))),t||(t=0);let n=t;if(Ve.encode(r.name,e,t),t+=Ve.encode.bytes,st(e,zb(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");st(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,st(e,r.flags||0,t+6),t+=8,ih.encode(r.options||[],e,t),t+=ih.encode.bytes}else{let i=OG(r.class===void 0?"IN":r.class);r.flush&&(i|=H6),st(e,i,t+2),yu(e,r.ttl||0,t+4),t+=8;let s=B6(r.type);s.encode(r.data,e,t),t+=s.encode.bytes}return Va.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=Ve.decode(r,e),e+=Ve.decode.bytes,t.type=xE(Lt(r,e)),t.type==="OPT")t.udpPayloadSize=Lt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=Lt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=ih.decode(r,e+8),e+=8+ih.decode.bytes;else{let i=Lt(r,e+2);t.ttl=mu(r,e+4),t.class=$G(i&uge),t.flush=!!(i&H6);let s=B6(t.type);t.data=s.decode(r,e+8),e+=8+s.decode.bytes}return Va.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return Ve.encodingLength(r.name)+8+B6(r.type).encodingLength(e)}}),Kg=Hr({encode(r,e,t){e||(e=new Uint8Array(Kg.encodingLength(r))),t||(t=0);let n=t;return Ve.encode(r.name,e,t),t+=Ve.encode.bytes,st(e,zb(r.type),t),t+=2,st(e,OG(r.class===void 0?"IN":r.class),t),t+=2,Kg.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=Ve.decode(r,e),e+=Ve.decode.bytes,n.type=xE(Lt(r,e)),e+=2,n.class=$G(Lt(r,e)),e+=2,n.class&NG&&(n.class&=fge),Kg.decode.bytes=e-t,n},encodingLength(r){return Ve.encodingLength(r.name)+4}}),hge=1024,uo={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(pge(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),Cg.encode(r,e,t),t+=Cg.encode.bytes,t=Ib(r.questions,Kg,e,t),t=Ib(r.answers,Va,e,t),t=Ib(r.authorities,Va,e,t),t=Ib(r.additionals,Va,e,t),uo.encode.bytes=t-i,n&&dE.bytes!==e.length?e.slice(0,dE.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=Cg.decode(r,e);return e+=Cg.decode.bytes,e=k2(n.questions,Kg,r,e),e=k2(n.answers,Va,r,e),e=k2(n.authorities,Va,r,e),e=k2(n.additionals,Va,r,e),uo.decode.bytes=e-t,n},encodingLength:function(r){return Cg.encodingLength(r)+Ng(r.questions||[],Kg)+Ng(r.answers||[],Va)+Ng(r.authorities||[],Va)+Ng(r.additionals||[],Va)}};uo.encode.bytes=0;uo.decode.bytes=0;aE={encode:function(r,e,t){return e=uo.encode(sE(r,"query"),e,t),aE.encode.bytes=uo.encode.bytes,e},decode:function(r,e){let t=uo.decode(r,e);return aE.decode.bytes=uo.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return uo.encodingLength(sE(r,"query"))}};aE.encode.bytes=0;aE.decode.bytes=0;cE={encode:function(r,e,t){return e=uo.encode(sE(r,"response"),e,t),cE.encode.bytes=uo.encode.bytes,e},decode:function(r,e){let t=uo.decode(r,e);return cE.decode.bytes=uo.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return uo.encodingLength(sE(r,"response"))}};cE.encode.bytes=0;cE.decode.bytes=0;dE=uo.encode,J6=uo.decode,pge=uo.encodingLength;UG.bytes=0;KG.bytes=0;zG="dht";bge=0,Xf=7200,W2=";",ts=",",WG={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},HG={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};_ge="https://enbox-did-dht.fly.dev";JG=class Y6 extends Qb{static async create({keyManager:e=new Wc,options:t={}}={}){if(t.verificationMethods?.some(c=>!(c.algorithm in WG)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(c=>"id"in c).map(c=>c.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(c=>!c.id||!c.type||!c.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),s=await e.getPublicKey({keyUri:i}),o=await Mg.identityKeyToIdentifier({identityKey:s}),a={id:o,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},d=[...t.verificationMethods??[]];d?.some(c=>c.id?.split("#").pop()==="0")||d.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let c of d){let u=c.id?.split("#").pop()==="0"?i:await e.generateKey({algorithm:c.algorithm}),f=await e.getPublicKey({keyUri:u}),h=c.id??f.kid??await Tr({jwk:f});h=`${o}#${rs(h)}`,a.verificationMethod??=[],a.verificationMethod.push({id:h,type:"JsonWebKey",controller:c.controller??o,publicKeyJwk:f});for(let p of c.purposes??[])a[p]??=[],a[p].push(h)}t.services?.forEach(c=>{a.service??=[],c.id=`${o}#${c.id.split("#").pop()}`,a.service.push(c)});let l=new Ro({uri:o,document:a,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let c=await Y6.publish({did:l,gatewayUri:t.gatewayUri,allowPrivateGatewayUri:t.allowPrivateGatewayUri});l.metadata=c.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Wc}){if(Qn.parse(e.uri)?.method!==Y6.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new rt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(s=>rs(s.id)===(rs(t)??rs(e.assertionMethod?.[0])));if(!i?.publicKeyJwk)throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t,allowPrivateGatewayUri:n}){let i=A7(t,n);return I7.put({did:e,...i})}static async resolve(e,t={}){let{gatewayUri:n,allowPrivateGatewayUri:i}=A7(t.gatewayUri,t.allowPrivateGatewayUri);try{await Mg.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:o}=await I7.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:i});return{...fo,didDocument:s,didDocumentMetadata:o}}catch(s){if(!(s instanceof rt))throw new Error(s);return{...fo,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};JG.methodName="dht";fa=JG,I7=class Cb{static async get({didUri:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=Mg.identifierToIdentityKeyBytes({didUri:e}),s=await Cb.pkarrGet({gatewayUri:t,publicKeyBytes:i,allowPrivateGatewayUri:n}),o=await Mg.parseBep44GetMessage({bep44Message:s}),a=await Cb.fromDnsPacket({didUri:e,dnsPacket:o});return a.didDocumentMetadata.versionId=s.seq.toString(),a}static async put({did:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=await Cb.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),s=await Mg.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Mg.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),o=await Cb.pkarrPut({gatewayUri:t,bep44Message:s,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return mge(e)}static async pkarrPut(e){return yge(e)}static async fromDnsPacket(e){return xge(e)}static async toDnsPacket(e){return Pge(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Mg=class{static async createBep44PutMessage(r){return gge(r)}static async identifierToIdentityKey(r){return FG(r)}static identifierToIdentityKeyBytes(r){return $5(r)}static async identityKeyToIdentifier(r){return vge(r)}static keyConverter(r){return O5(r)}static async parseBep44GetMessage(r){return wge(r)}static parseTxtDataToObject(r){return Rb(r)}static parseTxtDataToString(r){return Gb(r)}static async validatePreviousDidProof(r){return GG(r)}static chunkDataIfNeeded(r){return VG(r)}},Jn={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"},Yn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},xze=new Uint8Array(0),Tge=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")},Dge=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")}},kge=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 YG(this,r)}},Age=class{constructor(r){this.decoders=r}or(r){return YG(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`)}},YG=(r,e)=>new Age({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Ige=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new Dge(r,e,t),this.decoder=new kge(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rge=({name:r,prefix:e,encode:t,decode:n})=>new Ige(r,e,t,n),Cge=(r,e,t,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,d=0,l=0;for(let c=0;c<s;++c){let u=i[r[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&d>>a)}if(a>=t||255&d<<8-a)throw new SyntaxError("Unexpected end of data");return o},$ge=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let d=0;d<r.length;++d)for(a=a<<8|r[d],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},PE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rge({prefix:e,name:r,encode(i){return $ge(i,n,t)},decode(i){return Cge(i,n,t,r)}}),Pze=PE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_ze=PE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),R7=PE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Eze=PE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Fg=class H2{static encode(e){return R7.baseEncode(e)}static decodeAsBytes(e,t){if(!H2.isBase64UrlString(e))throw new Yn(Jn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return R7.baseDecode(e)}static decodeAsString(e,t){let n=H2.decodeAsBytes(e,t);return H2.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)}},Oge=Xp(xfe(),1);(function(r){r.Public="public",r.Private="private"})(Z6||(Z6={}));Xd=Z6,sa=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Xd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Yn(Jn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Yn(Jn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Yn(Jn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Xd.Private&&(r.d===void 0||r.d.length!==43))throw new Yn(Jn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Yn(Jn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!Fg.isBase64UrlString(r))throw new Yn(Jn.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 Yn(Jn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},B5=class{};B5.hashAlgorithmInMultihashCode=18;B5.maxCanonicalizedDeltaSizeInBytes=1e3;Gc=B5,Bge=Xp(Pfe(),1),Wb=class Q6{static canonicalizeAsBytes(e){let t=Q6.removeAllUndefinedProperties(e),n=Bge.default(t);return Fg.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?Q6.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},jge=ZG,C7=128,Nge=127,Mge=~Nge,Uge=Math.pow(2,31);Kge=X6,Lge=128,$7=127;qge=Math.pow(2,7),zge=Math.pow(2,14),Fge=Math.pow(2,21),Gge=Math.pow(2,28),Wge=Math.pow(2,35),Hge=Math.pow(2,42),Vge=Math.pow(2,49),Jge=Math.pow(2,56),Yge=Math.pow(2,63),Zge=function(r){return r<qge?1:r<zge?2:r<Fge?3:r<Gge?4:r<Wge?5:r<Hge?6:r<Vge?7:r<Jge?8:r<Yge?9:10},Qge={encode:jge,decode:Kge,encodingLength:Zge},Xge=Qge,lE=Xge,O7=(r,e=0)=>[lE.decode(r,e),lE.decode.bytes],B7=(r,e,t=0)=>(lE.encode(r,e,t),e),j7=r=>lE.encodingLength(r),N7=(r,e)=>{let t=e.byteLength,n=j7(r),i=n+j7(t),s=new Uint8Array(i+t);return B7(r,s,0),B7(t,s,n),s.set(e,i),new QG(r,t,e,s)},ewe=r=>{let e=Tge(r),[t,n]=O7(e),[i,s]=O7(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new QG(t,i,o,e)},QG=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},XG=({name:r,code:e,encode:t})=>new twe(r,e,t),twe=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?N7(this.code,e):e.then(t=>N7(this.code,t))}else throw Error("Unknown type, must be binary type")}},eW=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),M7=XG({name:"sha2-256",code:18,encode:eW("SHA-256")}),Sze=XG({name:"sha2-512",code:19,encode:eW("SHA-512")}),vb=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},ca=class $b{static hash(e,t){return vb(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield M7.digest(e)).bytes;break;default:throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return vb(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield M7.encode(e);break;default:throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=Wb.canonicalizeAsBytes(e);return yield $b.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=Wb.canonicalizeAsBytes(e),i=yield $b.hashAsNonMultihashBytes(n,t);return yield $b.hashThenEncode(i,t)})}static hashThenEncode(e,t){return vb(this,void 0,void 0,function*(){let n=yield $b.hash(e,t);return Fg.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=Fg.decodeAsBytes(e,t);try{n=ewe(i)}catch{throw new Yn(Jn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let s=Gc.hashAlgorithmInMultihashCode;if(s!==n.code)throw new Yn(Jn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${s} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(e5||(e5={}));A2=e5;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(t5||(t5={}));Ig=t5,I2=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},tW=class Wa{static createCreateRequest(e){return I2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,s=e.document.services;sa.validateEs256kOperationKey(t,Xd.Public),sa.validateEs256kOperationKey(n,Xd.Public),Wa.validateDidDocumentKeys(i),Wa.validateServices(s);let o=Gc.hashAlgorithmInMultihashCode,a=[{action:Ig.Replace,document:e.document}],d={updateCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(n,o),patches:a};Wa.validateDeltaSize(d);let l={deltaHash:yield ca.canonicalizeThenHashThenEncode(d,o),recoveryCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(t,o)};return{type:A2.Create,suffixData:l,delta:d}})}static createDeactivateRequest(e){return I2(this,void 0,void 0,function*(){Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.recoveryPublicKey,Xd.Public);let t=Gc.hashAlgorithmInMultihashCode,n=yield ca.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},s=yield e.signer.sign({alg:"ES256K"},i);return{type:A2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:s}})}static createRecoverRequest(e){return I2(this,void 0,void 0,function*(){Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.recoveryPublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextRecoveryPublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextUpdatePublicKey,Xd.Public),Wa.validateDidDocumentKeys(e.document.publicKeys),Wa.validateServices(e.document.services);let t=Gc.hashAlgorithmInMultihashCode,n=yield ca.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:Ig.Replace,document:e.document}],s=yield ca.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),o={patches:i,updateCommitment:s},a=yield ca.canonicalizeThenHashThenEncode(o,t),d={recoveryCommitment:yield ca.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:a},l=yield e.signer.sign({alg:"ES256K"},d);return{type:A2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:l}})}static createUpdateRequest(e){return I2(this,void 0,void 0,function*(){if(Wa.validateDidSuffix(e.didSuffix),sa.validateEs256kOperationKey(e.updatePublicKey,Xd.Public),sa.validateEs256kOperationKey(e.nextUpdatePublicKey,Xd.Public),Wa.validateServices(e.servicesToAdd),Wa.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)sa.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)sa.validateId(p);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Ig.AddServices,services:n};t.push(p)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let p={action:Ig.RemoveServices,ids:i};t.push(p)}let s=e.publicKeysToAdd;if(s!==void 0&&s.length>0){let p={action:Ig.AddPublicKeys,publicKeys:s};t.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Ig.RemovePublicKeys,ids:o};t.push(p)}let a=Gc.hashAlgorithmInMultihashCode,d=yield ca.canonicalizeThenHashThenEncode(e.updatePublicKey,a),l=yield ca.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,a),c={patches:t,updateCommitment:l},u=yield ca.canonicalizeThenHashThenEncode(c,a),f={updateKey:e.updatePublicKey,deltaHash:u},h=yield e.signer.sign({alg:"ES256K"},f);return{type:A2.Update,didSuffix:e.didSuffix,revealValue:d,delta:c,signedData:h}})}static validateDidSuffix(e){ca.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 Yn(Jn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(sa.validateId(n.id),t.has(n.id))throw new Yn(Jn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),sa.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Wa.validateService(n),t.has(n.id))throw new Yn(Jn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){sa.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 Yn(Jn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Yn(Jn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Oge.parse(e.serviceEndpoint).error!==void 0)throw new Yn(Jn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=Wb.canonicalizeAsBytes(e);if(t.length>Gc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Gc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Yn(Jn.DeltaExceedsMaximumSize,n)}}},U7=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},rwe=class rW{static createLongFormDid(e){return U7(this,void 0,void 0,function*(){let t=yield tW.createCreateRequest(e),n=yield rW.computeDidUniqueSuffix(t.suffixData),i;Gc.network===void 0||Gc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Gc.network}:${n}`;let s={suffixData:t.suffixData,delta:t.delta},o=Wb.canonicalizeAsBytes(s),a=Fg.encode(o);return`${i}:${a}`})}static computeDidUniqueSuffix(e){return U7(this,void 0,void 0,function*(){let t=Wb.canonicalizeAsBytes(e),n=yield ca.hash(t,Gc.hashAlgorithmInMultihashCode);return Fg.encode(n)})}},so=2n**255n-19n,V2=2n**252n+27742317777372353535851937790883648493n,r5=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,n5=0x6666666666666666666666666666666666666666666666666666666666666658n,R2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:so,n:V2,h:8,Gx:r5,Gy:n5},Ds=(r="")=>{throw new Error(r)},nW=r=>typeof r=="string",j5=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ds("Uint8Array expected"):r,Gg=r=>new Uint8Array(r),nwe=(r,e)=>j5(nW(r)?M5(r):Gg(r),e),dt=(r,e=so)=>{let t=r%e;return t>=0n?t:e+t},K7=r=>r instanceof Wg?r:Ds("Point expected"),Wg=class $g{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new $g(e.x,e.y,1n,dt(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=R2;e=nwe(e,32);let i=e.slice();i[31]=e[31]&-129;let s=owe(i);s===0n||(t&&!(0n<s&&s<so)&&Ds("bad y coord 1"),!t&&!(0n<s&&s<2n**256n)&&Ds("bad y coord 2"));let o=dt(s*s),a=dt(o-1n),d=dt(n*o+1n),{isValid:l,value:c}=awe(a,d);l||Ds("bad y coordinate 3");let u=(c&1n)===1n;return(e[31]&128)!==0!==u&&(c=dt(-c)),new $g(c,s,1n,dt(c*s))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:s,ey:o,ez:a}=K7(e),d=dt(t*a),l=dt(s*i),c=dt(n*a),u=dt(o*i);return d===l&&c===u}is0(){return this.equals(J2)}negate(){return new $g(dt(-this.ex),this.ey,this.ez,dt(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=R2,s=dt(e*e),o=dt(t*t),a=dt(2n*dt(n*n)),d=dt(i*s),l=e+t,c=dt(dt(l*l)-s-o),u=d+o,f=u-a,h=d-o,p=dt(c*f),m=dt(u*h),y=dt(c*h),v=dt(f*u);return new $g(p,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:s}=this,{ex:o,ey:a,ez:d,et:l}=K7(e),{a:c,d:u}=R2,f=dt(t*o),h=dt(n*a),p=dt(s*u*l),m=dt(i*d),y=dt((t+n)*(o+a)-f-h),v=dt(m-p),w=dt(m+p),b=dt(h-c*f),T=dt(y*v),D=dt(w*b),I=dt(y*b),M=dt(v*w);return new $g(T,D,M,I)}mul(e,t=!0){if(e===0n)return t===!0?Ds("cannot multiply by 0"):J2;if(typeof e=="bigint"&&0n<e&&e<V2||Ds("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(uE))return lwe(e).p;let n=J2,i=uE;for(let s=this;e>0n;s=s.double(),e>>=1n)e&1n?n=n.add(s):t&&(i=i.add(s));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(R2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(V2/2n,!1).double();return V2%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=oW(n);return dt(n*i)!==1n&&Ds("invalid inverse"),{x:dt(e*i),y:dt(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=iwe(t);return n[31]|=e&1n?128:0,n}toHex(){return N5(this.toRawBytes())}};Wg.BASE=new Wg(r5,n5,1n,dt(r5*n5));Wg.ZERO=new Wg(0n,1n,1n,0n);({BASE:uE,ZERO:J2}=Wg),iW=(r,e)=>r.toString(16).padStart(e,"0"),N5=r=>Array.from(r).map(e=>iW(e,2)).join(""),M5=r=>{let e=r.length;(!nW(r)||e%2)&&Ds("hex invalid 1");let t=Gg(e/2);for(let n=0;n<t.length;n++){let i=n*2,s=r.slice(i,i+2),o=Number.parseInt(s,16);(Number.isNaN(o)||o<0)&&Ds("hex invalid 2"),t[n]=o}return t},iwe=r=>M5(iW(r,32*2)).reverse(),owe=r=>BigInt("0x"+N5(Gg(j5(r)).reverse())),q7=(...r)=>{let e=Gg(r.reduce((n,i)=>n+j5(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},oW=(r,e=so)=>{(r===0n||e<=0n)&&Ds("no inverse n="+r+" mod="+e);let t=dt(r,e),n=e,i=0n,s=1n,o=1n,a=0n;for(;t!==0n;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}return n===1n?dt(i,e):Ds("no inverse")},Yd=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=so;return t},swe=r=>{let e=r*r%so*r%so,t=Yd(e,2n)*e%so,n=Yd(t,1n)*r%so,i=Yd(n,5n)*n%so,s=Yd(i,10n)*i%so,o=Yd(s,20n)*s%so,a=Yd(o,40n)*o%so,d=Yd(a,80n)*a%so,l=Yd(d,80n)*a%so,c=Yd(l,10n)*i%so;return{pow_p_5_8:Yd(c,2n)*r%so,b2:e}},z7=19681161376707505956807079304988542015446066515923890162744021073123829784752n,awe=(r,e)=>{let t=dt(e*e*e),n=dt(t*t*e),i=swe(r*n).pow_p_5_8,s=dt(r*t*i),o=dt(e*s*s),a=s,d=dt(s*z7),l=o===r,c=o===dt(-r),u=o===dt(-r*z7);return l&&(s=a),(c||u)&&(s=d),(dt(s)&1n)===1n&&(s=dt(-s)),{isValid:l||c,value:s}},F7=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,cwe={bytesToHex:N5,hexToBytes:M5,concatBytes:q7,mod:dt,invert:oW,randomBytes:r=>{let e=F7();return e||Ds("crypto.getRandomValues must be defined"),e.getRandomValues(Gg(r))},sha512Async:async(...r)=>{let e=F7();e||Ds("crypto.subtle or etc.sha512Async must be defined");let t=q7(...r);return Gg(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(cwe,{sha512Sync:{configurable:!1,get(){return j6},set(r){j6||(j6=r)}}});zp=8,dwe=()=>{let r=[],e=256/zp+1,t=uE,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let s=1;s<2**(zp-1);s++)n=n.add(t),r.push(n);t=n.double()}return r},lwe=r=>{let e=L7||(L7=dwe()),t=(c,u)=>{let f=u.negate();return c?f:u},n=J2,i=uE,s=1+256/zp,o=2**(zp-1),a=BigInt(2**zp-1),d=2**zp,l=BigInt(zp);for(let c=0;c<s;c++){let u=c*o,f=Number(r&a);r>>=l,f>o&&(f-=d,r+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(t(m,e[h])):n=n.add(t(y,e[p]))}return{p:n,f:i}},U5=2n**256n,Jp=U5-0x1000003d1n,K5=U5-0x14551231950b75fc4402da1732fc9bebfn,sW=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,aW=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,cW={p:Jp,n:K5,a:0n,b:7n,Gx:sW,Gy:aW},Lg=32,G7=r=>tt(tt(r*r)*r+cW.b),Bi=(r="")=>{throw new Error(r)},_E=r=>typeof r=="bigint",dW=r=>typeof r=="string",N6=r=>_E(r)&&0n<r&&r<Jp,lW=r=>_E(r)&&0n<r&&r<K5,uW=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Bi("Uint8Array expected"):r,Hb=r=>new Uint8Array(r),L5=(r,e)=>uW(dW(r)?EE(r):Hb(r),e),tt=(r,e=Jp)=>{let t=r%e;return t>=0n?t:e+t},W7=r=>r instanceof Hg?r:Bi("Point expected"),Hg=class Og{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Og(e.x,e.y,1n)}static fromHex(e){e=L5(e);let t,n=e[0],i=e.subarray(1),s=V7(i,0,Lg),o=e.length;if(o===33&&[2,3].includes(n)){N6(s)||Bi("Point hex invalid: x not FE");let a=uwe(G7(s)),d=(a&1n)===1n;(n&1)===1!==d&&(a=tt(-a)),t=new Og(s,a,1n)}return o===65&&n===4&&(t=new Og(s,V7(i,Lg,2*Lg),1n)),t?t.ok():Bi("Point is not on curve")}static fromPrivateKey(e){return Nb.mul(fwe(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:s,py:o,pz:a}=W7(e),d=tt(t*a),l=tt(s*i),c=tt(n*a),u=tt(o*i);return d===l&&c===u}negate(){return new Og(this.px,tt(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:s,py:o,pz:a}=W7(e),{a:d,b:l}=cW,c=0n,u=0n,f=0n,h=tt(l*3n),p=tt(t*s),m=tt(n*o),y=tt(i*a),v=tt(t+n),w=tt(s+o);v=tt(v*w),w=tt(p+m),v=tt(v-w),w=tt(t+i);let b=tt(s+a);return w=tt(w*b),b=tt(p+y),w=tt(w-b),b=tt(n+i),c=tt(o+a),b=tt(b*c),c=tt(m+y),b=tt(b-c),f=tt(d*w),c=tt(h*y),f=tt(c+f),c=tt(m-f),f=tt(m+f),u=tt(c*f),m=tt(p+p),m=tt(m+p),y=tt(d*y),w=tt(h*w),m=tt(m+y),y=tt(p-y),y=tt(d*y),w=tt(w+y),p=tt(m*w),u=tt(u+p),p=tt(b*w),c=tt(v*c),c=tt(c-p),p=tt(v*m),f=tt(b*f),f=tt(f+p),new Og(c,u,f)}mul(e,t=!0){if(!t&&e===0n)return Y2;if(lW(e)||Bi("invalid scalar"),this.equals(Nb))return ywe(e).p;let n=Y2,i=Nb;for(let s=this;e>0n;s=s.double(),e>>=1n)e&1n?n=n.add(s):t&&(i=i.add(s));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(Y2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=hW(n);return tt(n*i)!==1n&&Bi("invalid inverse"),{x:tt(e*i),y:tt(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!N6(e)||!N6(t))&&Bi("Point invalid: x or y"),tt(t*t)===G7(e)?this:Bi("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")+J7(t)+(e?"":J7(n))}toRawBytes(e=!0){return EE(this.toHex(e))}};Hg.BASE=new Hg(sW,aW,1n);Hg.ZERO=new Hg(0n,1n,0n);({BASE:Nb,ZERO:Y2}=Hg),fW=(r,e)=>r.toString(16).padStart(e,"0"),q5=r=>Array.from(r).map(e=>fW(e,2)).join(""),EE=r=>{let e=r.length;(!dW(r)||e%2)&&Bi("hex invalid 1");let t=Hb(e/2);for(let n=0;n<t.length;n++){let i=n*2,s=r.slice(i,i+2),o=Number.parseInt(s,16);(Number.isNaN(o)||o<0)&&Bi("hex invalid 2"),t[n]=o}return t},SE=r=>BigInt("0x"+(q5(r)||"0")),V7=(r,e,t)=>SE(r.slice(e,t)),z5=r=>_E(r)&&r>=0n&&r<U5?EE(fW(r,2*Lg)):Bi("bigint expected"),J7=r=>q5(z5(r)),Y7=(...r)=>{let e=Hb(r.reduce((n,i)=>n+uW(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},hW=(r,e=Jp)=>{(r===0n||e<=0n)&&Bi("no inverse n="+r+" mod="+e);let t=tt(r,e),n=e,i=0n,s=1n,o=1n,a=0n;for(;t!==0n;){let d=n/t,l=n%t,c=i-o*d,u=s-a*d;n=t,t=l,i=o,s=a,o=c,a=u}return n===1n?tt(i,e):Bi("no inverse")},uwe=r=>{let e=1n;for(let t=r,n=(Jp+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%Jp),t=t*t%Jp;return tt(e*e)===r?e:Bi("sqrt invalid")},fwe=r=>(_E(r)||(r=SE(L5(r,Lg))),lW(r)?r:Bi("private key out of range")),Z7=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;pwe={hexToBytes:EE,bytesToHex:q5,concatBytes:Y7,bytesToNumberBE:SE,numberToBytesBE:z5,mod:tt,invert:hW,hmacSha256Async:async(r,...e)=>{let t=Z7();if(!t)return Bi("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Hb(await n.sign("HMAC",i,Y7(...e)))},hmacSha256Sync:Z2,hashToPrivateKey:hwe,randomBytes:r=>{let e=Z7();return e||Bi("crypto.getRandomValues must be defined"),e.getRandomValues(Hb(r))}};Object.defineProperties(pwe,{hmacSha256Sync:{configurable:!1,get(){return Z2},set(r){Z2||(Z2=r)}}});Fp=8,mwe=()=>{let r=[],e=256/Fp+1,t=Nb,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let s=1;s<2**(Fp-1);s++)n=n.add(t),r.push(n);t=n.double()}return r},ywe=r=>{let e=H7||(H7=mwe()),t=(c,u)=>{let f=u.negate();return c?f:u},n=Y2,i=Nb,s=1+256/Fp,o=2**(Fp-1),a=BigInt(2**Fp-1),d=2**Fp,l=BigInt(Fp);for(let c=0;c<s;c++){let u=c*o,f=Number(r&a);r>>=l,f>o&&(f-=d,r+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(t(m,e[h])):n=n.add(t(y,e[p]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(Q7||(Q7={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(X7||(X7={}));bb=class Lp{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 s=await Lp.createIonDocument({services:n,verificationMethods:i}),o=Lp.normalizeJwk(e),a=Lp.normalizeJwk(t);return await rwe.createLongFormDid({document:s,recoveryKey:o,updateKey:a})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await tW.createCreateRequest({document:e,recoveryKey:Lp.normalizeJwk(t),updateKey:Lp.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let s of t){let o=s.id??s.publicKeyJwk.kid??await Tr({jwk:s.publicKeyJwk});o=`${o.split("#").pop()}`;let a={id:o,publicKeyJwk:Lp.normalizeJwk(s.publicKeyJwk),purposes:s.purposes,type:"JsonWebKey2020"};n.push(a)}let i=e.map(s=>({...s,id:`${s.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}},gwe=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(gwe||{}),wwe={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},eF="https://ion.tbd.engineering",vwe=class Ob extends Qb{static async create({keyManager:e=new Wc,options:t={}}={}){if(t.verificationMethods?.some(p=>!(p.algorithm in wwe)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(p=>"id"in p).map(p=>p.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(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},s=[];for(let p of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});s.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),a=await e.getPublicKey({keyUri:o}),d=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:d}),c=await bb.computeLongFormDidUri({recoveryKey:a,updateKey:l,services:t.services??[],verificationMethods:s}),{didDocument:u,didResolutionMetadata:f}=await Ob.resolve(c,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ro({uri:c,document:u,metadata:{published:!1,canonicalId:c.split(":",3).join(":"),recoveryKey:a,updateKey:l},keyManager:e});if(t.publish??!0){let p=await Ob.publish({did:h,gatewayUri:t.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:t}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(s=>s.id===(t??e.assertionMethod?.[0]));if(!i?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==Ob.methodName)throw new rt("methodNotSupported","Method not supported");return await Ro.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=eF}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:gG({didDocument:e.document,methodId:o.id})}))??[],i=await bb.createIonDocument({services:e.document.service??[],verificationMethods:n}),s=await bb.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=bb.appendPathToUrl({baseUrl:t,path:"/operations"}),a=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a.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=Qn.parse(e);if(!n)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Ob.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??eF;try{let s=bb.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),o=await fetch(s,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new rt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:a,didDocumentMetadata:d}=await o.json();return{...fo,...a&&{didDocument:a},didDocumentMetadata:{published:d?.method?.published,...d}}}catch(s){if(!(s instanceof rt))throw new Error(s);return{...fo,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};vwe.methodName="ion";pW=class Bb extends Qb{static async create({keyManager:e=new Wc,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}),s=await e.getPublicKey({keyUri:i}),o=ot.object(s).toBase64Url(),a=`did:${Bb.methodName}:${o}`,d=(await Bb.resolve(a)).didDocument;return new Ro({uri:a,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Qn.parse(e.id);if(t&&t.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==Bb.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Qn.parse(e),i;try{i=n?ot.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Bb.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let s={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${s.id}#0`;switch(s.verificationMethod=[{id:o,type:"JsonWebKey",controller:s.id,publicKeyJwk:i}],s.authentication=[o],s.assertionMethod=[o],s.capabilityInvocation=[o],s.capabilityDelegation=[o],s.keyAgreement=[o],i.use){case"sig":{delete s.keyAgreement;break}case"enc":{delete s.authentication,delete s.assertionMethod,delete s.capabilityInvocation,delete s.capabilityDelegation;break}}return{...fo,didDocument:s}}};pW.methodName="jwk";ns=pW,bwe={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Q2=class Bg{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=Bg.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:ec.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":Ao.compressPublicKey,secp256k1:ao.compressPublicKey}[e];if(!t)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:co,"P-256":Ao,secp256k1:ao}[e];if(!t)throw new rt("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?ec.getNameFromCode({code:e}):t;let n=t,i=Bg.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 bwe))throw new rt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Bg.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Bg.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Bg.jwkToMulticodec({jwk:e});return vG({keyBytes:t,multicodecName:n})}};Q2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},Q2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},Q2.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:""}};C2=Q2,xwe=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(xwe||{}),tF={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},mW=class rh extends Qb{static async create({keyManager:e=new Wc,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}),s=await e.getPublicKey({keyUri:i}),o=await C2.publicKeyToMultibaseId({publicKey:s}),a=`did:${rh.methodName}:${o}`,d=(await rh.resolve(a,t)).didDocument;return new Ro({uri:a,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Qn.parse(e.id);if(t&&t.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(s=>s.id===n);if(!i?.publicKeyJwk)throw new rt("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 Wc}){if(Qn.parse(e.uri)?.method!==rh.methodName)throw new rt("methodNotSupported","Method not supported");let n=await Ro.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await rh.createDocument({didUri:e,options:t});return{...fo,didDocument:n}}catch(n){if(!(n instanceof rt))throw new Error(n);return{...fo,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:s="JsonWebKey2020"}=t,o={id:""},a=Qn.parse(e);if(!a)throw new rt("invalidDid",`Invalid DID URI: ${e}`);let d=a.id;if(a.method!==rh.methodName)throw new rt("methodNotSupported",`Method not supported: ${a.method}`);if(!rh.validateIdentifier(a))throw new rt("invalidDid",`Invalid DID URI: ${e}`);let l=await rh.createSignatureMethod({didUri:e,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:s}});o.id=a.uri,o.verificationMethod=[l],o.authentication=[l.id],o.assertionMethod=[l.id],o.capabilityInvocation=[l.id],o.capabilityDelegation=[l.id];let c=[n];return yG({didDocument:o}).forEach(u=>{let f=tF[u];c.push(f)}),o["@context"]=c,o}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:s}=n,o={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:d,multicodecName:l}=bG({multibaseKeyId:t}),c=a.byteLength,u=C2.MULTICODEC_PUBLIC_KEY_LENGTH[d];if(c!==u)throw new rt("invalidPublicKeyLength",`Expected ${c} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await ao.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":f=await co.validatePublicKey({publicKeyBytes:a});break}if(!f)throw new rt("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${t}`;try{new URL(o.id)}catch{throw new rt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(s in tF))throw new rt("unsupportedPublicKeyType",`Unsupported format: ${s}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new rt("invalidPublicKeyType",`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=s,o.controller=e,s==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=t),s==="JsonWebKey2020"){let{crv:h}=await C2.multicodecToJwk({code:d});o.publicKeyJwk=await C2.keyConverter(h).bytesToPublicKey({publicKeyBytes:a})}return o}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&M6(n)==="String"&&n.startsWith("z")}};mW.methodName="key";sm=mW,Pwe=3e4,yW=class X2 extends Qb{static async create({keyManager:e=new Wc,options:t}){if(!t.domain)throw new rt("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:${X2.methodName}:${n}`;if(!Qn.parse(i))throw new rt("invalidDid",`The constructed DID URI is invalid: ${i}`);let s=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let a=0;a<s.length;a++){let d=s[a],l=await e.generateKey({algorithm:d.algorithm}),c=await e.getPublicKey({keyUri:l}),u=d.id?.split("#").pop()??`key-${a}`,f=`${i}#${u}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:d.controller??i,publicKeyJwk:c});for(let h of d.purposes??[])o[h]??=[],o[h].push(f)}return t.services&&(o.service=t.services.map(a=>({...a,id:`${i}#${a.id.split("#").pop()}`}))),new Ro({uri:i,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Qn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=rs(t)??rs(e.assertionMethod?.[0]),s=i?e.verificationMethod?.find(o=>rs(o.id)===i):e.verificationMethod?.[0];if(!s?.publicKeyJwk)throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:t=new Wc}){if(Qn.parse(e.uri)?.method!==X2.methodName)throw new rt("methodNotSupported","Method not supported");return await Ro.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Qn.parse(e);if(!n)return{...fo,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==X2.methodName)return{...fo,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let s=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let o=await xF(s,{signal:AbortSignal.timeout(Pwe)},{description:"did:web document URL"});if(!o.ok)throw new Error("HTTP error status code returned");let a=await o.json();return{...fo,didDocument:a}}catch{return{...fo,didResolutionMetadata:{error:"notFound"}}}}};yW.methodName="web";TE=yW,_we=Xp(uF(),1),Ewe=Xp(fF(),1),DE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new _we.Level(e),this.ttl=(0,Ewe.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()}},Swe=Xp(fF(),1),t1=class{constructor({ttl:r="15m"}={}){this.cache=new Efe.default({ttl:(0,Swe.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(){}},Twe={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()}},dh=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=r||Twe;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=Qn.parse(r);if(!t)return{...fo,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...fo,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};if(e!==void 0)return n.resolve(t.uri,e);let i=await this.cache.get(t.uri);if(i)return i;let s=this._inFlight.get(t.uri);if(s)return s;let o=(async()=>{let a=await n.resolve(t.uri,e);if(!a.didResolutionMetadata.error)try{await this.cache.set(t.uri,a)}catch{}return a})();this._inFlight.set(t.uri,o);try{return await o}finally{this._inFlight.delete(t.uri)}}async dereference(r,e){let t=Qn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:s}=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:s};let{service:o=[],verificationMethod:a=[]}=n,d=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let c of a)if(d.has(c.id)){l=c;break}for(let c of o)if(d.has(c.id)){l=c;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var Qg,gW=G(()=>{"use strict";g();PR();xR();vr();na();bL();PL();EL();ia();vz();bz();$z();Oz();Bz();jz();Nz();Mz();w2();D6();is();lr();Qg=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 Ag({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new g2(e.resumableTaskStore,this.storageController),this._coreProtocols=new dg,this._coreProtocols.register(new Qe);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={[xe.Messages+me.Read]:new E_(t),[xe.Messages+me.Subscribe]:new D_(t),[xe.Messages+me.Sync]:new A_(t),[xe.Protocols+me.Configure]:new h2(t),[xe.Protocols+me.Query]:new m2(t),[xe.Records+me.Count]:new y2(t),[xe.Records+me.Delete]:new v2(t),[xe.Records+me.Query]:new b2(t),[xe.Records+me.Read]:new x2(t),[xe.Records+me.Subscribe]:new _2(t),[xe.Records+me.Write]:new E2(t)}}static async create(e){e.didResolver||(e.didResolver=new dh({didResolvers:[fa,ns,sm,TE],cache:new t1}),e.ownsResolver=!0),e.tenantGate??=new lg;let t=new r(e);return await t.open(),t}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.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();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.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:s,subscriptionHandler:o}=n,a=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[a].handle({tenant:e,message:t,dataStream:s,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 gt(i,400)}}}});function Dwe(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Xn(r,e){return e?Promise.race([r,Dwe(e)]):r}var kE=G(()=>{"use strict";g()});import{Level as kwe}from"level";async function os(r,e){return new kwe(r,{...e,keyEncoding:"utf8"})}var rc,lh=G(()=>{"use strict";g();kE();rc=class r{config;db;constructor(e,t){this.config={createLevelDatabase:os,...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 Xn(this.createLevelDatabase(),t?.signal);try{return await Xn(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 Xn(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 Xn(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 Xn(this.createLevelDatabase(),n?.signal),Xn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Xn(this.createLevelDatabase(),t?.signal),Xn(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 Xn(this.createLevelDatabase(),t?.signal),Xn(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 Xn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Xn(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 uh,AE=G(()=>{"use strict";g();v0();lh();uh=class r{config;db;constructor(e,t){this.config={createLevelDatabase:os,...e},this.db=t??new rc({...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),er.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:er.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 Awe(r){return r[Symbol.asyncIterator]!=null}function Iwe(r){if(Awe(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 wW,vW=G(()=>{g();wW=Iwe});var bW,Rwe,xW,Cwe,PW,_W=G(()=>{g();Eh();Vm();bW=0,Rwe="identity",xW=cc,Cwe=r=>Ih(bW,xW(r)),PW={code:bW,name:Rwe,encode:xW,digest:Cwe}});var EW,$we,SW,TW=G(()=>{g();xy();EW=Rn(_a(),1);Ol();$we=async(r,e,t,n,i,s,o,a)=>{let d=await o.get(r,a),l=ck(d),c=l,u=t;for(;n.length>0;){let f=n[0];if(f in c){n.shift(),u=`${u}/${f}`;let h=er.asCID(c[f]);if(h!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:d,depth:s,size:BigInt(d.length),content:async function*(){yield l}},next:{cid:h,name:f,path:u,toResolve:n}};c=c[f]}else throw(0,EW.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:d,depth:s,size:BigInt(d.length),content:async function*(){yield l}}}},SW=$we});function Owe(r,e,t,n){let i=BigInt(r.length),s=BigInt(e+i);return t>=s||n<e?new Uint8Array(0):(n>=e&&n<s&&(r=r.subarray(0,Number(n-e))),t>=e&&t<s&&(r=r.subarray(Number(t-e))),r)}var am,IE=G(()=>{g();am=Owe});var r1,Bwe,Xg,RE=G(()=>{g();r1=Rn(_a(),1),Bwe=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),s=BigInt(t);if(s!==n&&(s=i+s),s>n&&(s=n),i<0n)throw(0,r1.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,r1.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(s<0n)throw(0,r1.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,r1.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:s}},Xg=Bwe});var DW,jwe,Nwe,kW,AW=G(()=>{g();DW=Rn(_a(),1);Vm();jl();IE();RE();jwe=r=>{async function*e(t={}){let{start:n,end:i}=Xg(r.length,t.offset,t.length),s=am(r,0n,n,i);t.onProgress?.(new Bn("unixfs:exporter:progress:identity",{bytesRead:BigInt(s.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield s}return e},Nwe=async(r,e,t,n,i,s,o,a)=>{if(n.length>0)throw(0,DW.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let d=nx(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:jwe(d.digest),depth:s,size:BigInt(d.digest.length),node:d.digest}}},kW=Nwe});var IW,Mwe,Uwe,RW,CW=G(()=>{g();IW=Rn(_a(),1);jl();IE();RE();Mwe=r=>{async function*e(t={}){let{start:n,end:i}=Xg(r.length,t.offset,t.length),s=am(r,0n,n,i);t.onProgress?.(new Bn("unixfs:exporter:progress:raw",{bytesRead:BigInt(s.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield s}return e},Uwe=async(r,e,t,n,i,s,o,a)=>{if(n.length>0)throw(0,IW.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let d=await o.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:Mwe(d),depth:s,size:BigInt(d.length),node:d}}},RW=Uwe});var Kwe,Lwe,$W,qwe,OW,BW,jW=G(()=>{g();Ea();cA();dA();Kwe=async function(r){return(await oP.encode(r)).slice(0,8).reverse()},Lwe=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 pd({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},$W=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),qwe=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},OW=async(r,e,t,n,i)=>{if(n==null){let c=cP({hashFn:Kwe});n={rootBucket:c,hamtDepth:1,lastBucket:c}}await Lwe(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),o=$W(s.pos),a=qwe(s);a.length>n.hamtDepth&&(n.lastBucket=a[n.hamtDepth],o=$W(n.lastBucket._posAtParent));let d=r.Links.find(c=>{if(c.Name==null)return!1;let u=c.Name.substring(0,2),f=c.Name.substring(2);return!(u!==o||f!==""&&f!==e)});if(d==null)return;if(d.Name!=null&&d.Name.substring(2)===e)return d.Hash;n.hamtDepth++;let l=await t.get(d.Hash,i);return r=Bl(l),OW(r,e,t,n,i)},BW=OW});function zwe(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 CE,F5=G(()=>{g();CE=zwe});function Fwe(r){return r[Symbol.asyncIterator]!=null}function Gwe(r,e){let t=0;if(Fwe(r))return async function*(){for await(let d of r)await e(d,t++)&&(yield d)}();let n=CE(r),{value:i,done:s}=n.next();if(s===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){await o&&(yield i);for(let d of n)await e(d,t++)&&(yield d)}();let a=e;return function*(){o===!0&&(yield i);for(let d of n)a(d,t++)&&(yield d)}()}var NW,MW=G(()=>{g();F5();NW=Gwe});function Wwe(r){return r[Symbol.asyncIterator]!=null}function Hwe(r,e){let t=0;if(Wwe(r))return async function*(){for await(let d of r)yield e(d,t++)}();let n=CE(r),{value:i,done:s}=n.next();if(s===!0)return function*(){}();let o=e(i,t++);if(typeof o.then=="function")return async function*(){yield await o;for(let d of n)yield e(d,t++)}();let a=e;return function*(){yield o;for(let d of n)yield a(d,t++)}()}var ew,$E=G(()=>{g();F5();ew=Hwe});function As(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var OE=G(()=>{g()});async function*cm(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,s=[],o=As(),a=As(),d=!1,l,c=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(o=As(),await o.promise),c)break;let m={done:!1};s.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new BE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new BE("task-complete"))})}d=!0,i.dispatchEvent(new BE("task-complete"))}catch(p){l=p,i.dispatchEvent(new BE("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*f(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw c=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw c=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(u()||(a=As(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(d&&s.length===0)break}}var BE,jE=G(()=>{g();OE();BE=globalThis.CustomEvent??Event});var NE,tw,UW=G(()=>{g();NE=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}},tw=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new NE(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 NE(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 ME(r={}){return Vwe(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 Vwe(r,e){e=e??{};let t=e.onEnd,n=new tw,i,s,o,a=As(),d=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,v)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){v(b)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=As()})}},l=y=>s!=null?s(y):(n.push(y),i),c=y=>(n=new tw,s!=null?s({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?c(y):l({done:!0})),h=()=>(n=new tw,f(),{done:!0}),p=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:d,return:h,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,b;v!=null&&(w=new Promise((T,D)=>{b=()=>{D(new G5)},v.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&v!=null&&v?.removeEventListener("abort",b)}}},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 G5,W5=G(()=>{g();OE();UW();G5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function Jwe(r){return r.reason}async function KW(r,e,t){if(e==null)return r;let n=t?.translateError??Jwe;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((s,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var LW=G(()=>{g()});function qW(){return new H5}var H5,zW=G(()=>{g();OE();LW();H5=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=As(),this.haveNext=As()}[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=As(),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=As(),await KW(this.readNext.promise,t?.signal,t)}}});function Ywe(r){return r[Symbol.asyncIterator]!=null}async function Zwe(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*Qwe(r){let e=new AbortController,t=qW();Zwe(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Xwe(r){for(let e of r)yield*e}function e0e(...r){let e=[];for(let t of r)Ywe(t)||e.push(t);return e.length===r.length?Xwe(e):Qwe(r)}var FW,GW=G(()=>{g();zW();FW=e0e});function rw(r,...e){if(r==null)throw new Error("Empty pipeline");if(V5(r)){let n=r;r=()=>n.source}else if(HW(r)||WW(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&V5(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++)V5(t[n])&&(t[n]=r0e(t[n]));return t0e(...t)}var t0e,WW,HW,V5,r0e,UE=G(()=>{g();W5();GW();t0e=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},WW=r=>r?.[Symbol.asyncIterator]!=null,HW=r=>r?.[Symbol.iterator]!=null,V5=r=>r==null?!1:r.sink!=null&&r.source!=null,r0e=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=ME({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(WW(s))i=async function*(){yield*s,n.end()};else if(HW(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return FW(n,i())}return r.source}});var n0e,VW,JW=G(()=>{g();MW();$E();jE();UE();jl();n0e=(r,e,t,n,i,s,o)=>{async function*a(d={}){let l=d.offset??0,c=d.length??e.Links.length,u=e.Links.slice(l,c);d.onProgress?.(new Bn("unixfs:exporter:walk:directory",{cid:r})),yield*rw(u,f=>ew(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await i(h.Hash,p,m,[],s+1,o,d)).entry}),f=>cm(f,{ordered:!0}),f=>NW(f,h=>h!=null))}return a},VW=n0e});var ZW=Te(($Ge,J5)=>{"use strict";g();var i0e=Object.prototype.hasOwnProperty,ss="~";function n1(){}Object.create&&(n1.prototype=Object.create(null),new n1().__proto__||(ss=!1));function o0e(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function YW(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new o0e(t,n||r,i),o=ss?ss+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function KE(r,e){--r._eventsCount===0?r._events=new n1:delete r._events[e]}function Co(){this._events=new n1,this._eventsCount=0}Co.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)i0e.call(t,n)&&e.push(ss?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Co.prototype.listeners=function(e){var t=ss?ss+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Co.prototype.listenerCount=function(e){var t=ss?ss+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Co.prototype.emit=function(e,t,n,i,s,o){var a=ss?ss+e:e;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,c,u;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,n),!0;case 4:return d.fn.call(d.context,t,n,i),!0;case 5:return d.fn.call(d.context,t,n,i,s),!0;case 6:return d.fn.call(d.context,t,n,i,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var f=d.length,h;for(u=0;u<f;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,n);break;case 4:d[u].fn.call(d[u].context,t,n,i);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0};Co.prototype.on=function(e,t,n){return YW(this,e,t,n,!1)};Co.prototype.once=function(e,t,n){return YW(this,e,t,n,!0)};Co.prototype.removeListener=function(e,t,n,i){var s=ss?ss+e:e;if(!this._events[s])return this;if(!t)return KE(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&KE(this,s);else{for(var a=0,d=[],l=o.length;a<l;a++)(o[a].fn!==t||i&&!o[a].once||n&&o[a].context!==n)&&d.push(o[a]);d.length?this._events[s]=d.length===1?d[0]:d:KE(this,s)}return this};Co.prototype.removeAllListeners=function(e){var t;return e?(t=ss?ss+e:e,this._events[t]&&KE(this,t)):(this._events=new n1,this._eventsCount=0),this};Co.prototype.off=Co.prototype.removeListener;Co.prototype.addListener=Co.prototype.on;Co.prefixed=ss;Co.EventEmitter=Co;typeof J5<"u"&&(J5.exports=Co)});var Y5,QW=G(()=>{g();Y5=Rn(ZW(),1)});function Q5(r,e,t,n){let i,s=new Promise((o,a)=>{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:d}=n;d.aborted&&a(eH(d)),d.addEventListener("abort",()=>{a(eH(d))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(c){a(c)}return}let d=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new i1(d);typeof r.cancel=="function"&&r.cancel(),a(l)},e),(async()=>{try{o(await r)}catch(d){a(d)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}var i1,Z5,XW,eH,tH=G(()=>{g();i1=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Z5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},XW=r=>globalThis.DOMException===void 0?new Z5(r):new DOMException(r),eH=r=>{let e=r.reason===void 0?XW("This operation was aborted."):r.reason;return e instanceof Error?e:XW(e)}});function X5(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var rH=G(()=>{g()});var dm,bu,e$,nH,iH=G(()=>{g();rH();dm=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)},e$=class{constructor(){bu.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&dm(this,bu,"f")[this.size-1].priority>=t.priority){dm(this,bu,"f").push(n);return}let i=X5(dm(this,bu,"f"),n,(s,o)=>o.priority-s.priority);dm(this,bu,"f").splice(i,0,n)}dequeue(){let e=dm(this,bu,"f").shift();return e?.run}filter(e){return dm(this,bu,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return dm(this,bu,"f").length}};bu=new WeakMap;nH=e$});var An,Je,ei,s1,a1,hh,WE,c1,LE,Hc,o1,ha,qE,pa,d1,fh,zE,oH,sH,dH,aH,cH,FE,t$,r$,HE,lH,GE,VE,n$,uH,fH=G(()=>{g();QW();tH();iH();An=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},Je=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)},VE=class extends Error{},n$=class extends Y5.default{constructor(e){var t,n,i,s;if(super(),ei.add(this),s1.set(this,void 0),a1.set(this,void 0),hh.set(this,0),WE.set(this,void 0),c1.set(this,void 0),LE.set(this,0),Hc.set(this,void 0),o1.set(this,void 0),ha.set(this,void 0),qE.set(this,void 0),pa.set(this,0),d1.set(this,void 0),fh.set(this,void 0),zE.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:nH,...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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);An(this,s1,e.carryoverConcurrencyCount,"f"),An(this,a1,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),An(this,WE,e.intervalCap,"f"),An(this,c1,e.interval,"f"),An(this,ha,new e.queueClass,"f"),An(this,qE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,An(this,zE,e.throwOnTimeout===!0,"f"),An(this,fh,e.autoStart===!1,"f")}get concurrency(){return Je(this,d1,"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})`);An(this,d1,e,"f"),Je(this,ei,"m",HE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Je(this,zE,"f"),...t},new Promise((n,i)=>{Je(this,ha,"f").enqueue(async()=>{var s,o,a;An(this,pa,(o=Je(this,pa,"f"),o++,o),"f"),An(this,hh,(a=Je(this,hh,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new VE("The task was aborted.");let d=e({signal:t.signal});t.timeout&&(d=Q5(Promise.resolve(d),t.timeout)),t.signal&&(d=Promise.race([d,Je(this,ei,"m",lH).call(this,t.signal)]));let l=await d;n(l),this.emit("completed",l)}catch(d){if(d instanceof i1&&!t.throwOnTimeout){n();return}i(d),this.emit("error",d)}finally{Je(this,ei,"m",dH).call(this)}},t),this.emit("add"),Je(this,ei,"m",FE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Je(this,fh,"f")?(An(this,fh,!1,"f"),Je(this,ei,"m",HE).call(this),this):this}pause(){An(this,fh,!0,"f")}clear(){An(this,ha,new(Je(this,qE,"f")),"f")}async onEmpty(){Je(this,ha,"f").size!==0&&await Je(this,ei,"m",GE).call(this,"empty")}async onSizeLessThan(e){Je(this,ha,"f").size<e||await Je(this,ei,"m",GE).call(this,"next",()=>Je(this,ha,"f").size<e)}async onIdle(){Je(this,pa,"f")===0&&Je(this,ha,"f").size===0||await Je(this,ei,"m",GE).call(this,"idle")}get size(){return Je(this,ha,"f").size}sizeBy(e){return Je(this,ha,"f").filter(e).length}get pending(){return Je(this,pa,"f")}get isPaused(){return Je(this,fh,"f")}};s1=new WeakMap,a1=new WeakMap,hh=new WeakMap,WE=new WeakMap,c1=new WeakMap,LE=new WeakMap,Hc=new WeakMap,o1=new WeakMap,ha=new WeakMap,qE=new WeakMap,pa=new WeakMap,d1=new WeakMap,fh=new WeakMap,zE=new WeakMap,ei=new WeakSet,oH=function(){return Je(this,a1,"f")||Je(this,hh,"f")<Je(this,WE,"f")},sH=function(){return Je(this,pa,"f")<Je(this,d1,"f")},dH=function(){var e;An(this,pa,(e=Je(this,pa,"f"),e--,e),"f"),Je(this,ei,"m",FE).call(this),this.emit("next")},aH=function(){Je(this,ei,"m",r$).call(this),Je(this,ei,"m",t$).call(this),An(this,o1,void 0,"f")},cH=function(){let e=Date.now();if(Je(this,Hc,"f")===void 0){let t=Je(this,LE,"f")-e;if(t<0)An(this,hh,Je(this,s1,"f")?Je(this,pa,"f"):0,"f");else return Je(this,o1,"f")===void 0&&An(this,o1,setTimeout(()=>{Je(this,ei,"m",aH).call(this)},t),"f"),!0}return!1},FE=function(){if(Je(this,ha,"f").size===0)return Je(this,Hc,"f")&&clearInterval(Je(this,Hc,"f")),An(this,Hc,void 0,"f"),this.emit("empty"),Je(this,pa,"f")===0&&this.emit("idle"),!1;if(!Je(this,fh,"f")){let e=!Je(this,ei,"a",cH);if(Je(this,ei,"a",oH)&&Je(this,ei,"a",sH)){let t=Je(this,ha,"f").dequeue();return t?(this.emit("active"),t(),e&&Je(this,ei,"m",t$).call(this),!0):!1}}return!1},t$=function(){Je(this,a1,"f")||Je(this,Hc,"f")!==void 0||(An(this,Hc,setInterval(()=>{Je(this,ei,"m",r$).call(this)},Je(this,c1,"f")),"f"),An(this,LE,Date.now()+Je(this,c1,"f"),"f"))},r$=function(){Je(this,hh,"f")===0&&Je(this,pa,"f")===0&&Je(this,Hc,"f")&&(clearInterval(Je(this,Hc,"f")),An(this,Hc,void 0,"f")),An(this,hh,Je(this,s1,"f")?Je(this,pa,"f"):0,"f"),Je(this,ei,"m",HE).call(this)},HE=function(){for(;Je(this,ei,"m",FE).call(this););},lH=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new VE("The task was aborted."))},{once:!0})})},GE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};uH=n$});async function hH(r,e,t,n,i,s,o){if(e instanceof Uint8Array){let l=am(e,n,i,s);t.push(l);return}if(e.Data==null)throw(0,lm.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=Ti.unmarshal(e.Data)}catch(l){throw(0,lm.default)(l,"ERR_NOT_UNIXFS")}if(a.data!=null){let l=a.data,c=am(l,n,i,s);t.push(c),n+=BigInt(c.byteLength)}let d=[];if(e.Links.length!==a.blockSizes.length)throw(0,lm.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let c=e.Links[l],u=n,f=u+a.blockSizes[l];if((i>=u&&i<f||s>=u&&s<=f||i<u&&s>f)&&d.push({link:c,blockStart:n}),n=f,n>s)break}await rw(d,l=>ew(l,c=>async()=>{let u=await r.get(c.link.Hash,o);return{...c,block:u}}),l=>cm(l,{ordered:!0}),async l=>{for await(let{link:c,block:u,blockStart:f}of l){let h;switch(c.Hash.code){case E0:h=Bl(u);break;case of:h=u;break;default:t.end((0,lm.default)(new Error(`Unsupported codec: ${c.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new uH({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{o.onProgress?.(new Bn("unixfs:exporter:walk:file",{cid:c.Hash})),await hH(r,h,t,f,i,s,o)}),await p.onIdle()}}),n>=s&&t.end()}var lm,s0e,i$,pH=G(()=>{g();Ea();lm=Rn(_a(),1);nf();$E();jE();UE();W5();C0();fH();jl();IE();RE();s0e=(r,e,t,n,i,s,o)=>{async function*a(d={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:c,end:u}=Xg(l,d.offset,d.length);if(u===0n)return;let f=0n,h=u-c,p=ME();d.onProgress?.(new Bn("unixfs:exporter:walk:file",{cid:r})),hH(o,e,p,0n,c,u,d).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),(0,lm.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===h&&p.end(),d.onProgress?.(new Bn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw(0,lm.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},i$=s0e});async function*mH(r,e,t,n,i,s){let o=r.Links,a=rw(o,d=>ew(d,l=>async()=>{let c=l.Name!=null?l.Name.substring(2):null;if(c!=null&&c!==""){let u=await t(l.Hash,c,`${e}/${c}`,[],n+1,i,s);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,s);return r=Bl(u),s.onProgress?.(new Bn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:mH(r,e,t,n,i,s)}}}),d=>cm(d,{ordered:!0}));for await(let{entries:d}of a)yield*d}var a0e,yH,gH=G(()=>{g();Ea();$E();jE();UE();jl();a0e=(r,e,t,n,i,s,o)=>{function a(d={}){return d.onProgress?.(new Bn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),mH(e,n,i,s,o,d)}return a};yH=a0e});var l1,c0e,d0e,l0e,wH,vH=G(()=>{g();Ea();l1=Rn(_a(),1);nf();jW();JW();pH();gH();c0e=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,d0e={raw:i$,file:i$,directory:VW,"hamt-sharded-directory":yH,metadata:(r,e,t,n,i,s,o)=>()=>[],symlink:(r,e,t,n,i,s,o)=>()=>[]},l0e=async(r,e,t,n,i,s,o,a)=>{let d=await o.get(r,a),l=Bl(d),c,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,l1.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{c=Ti.unmarshal(l.Data)}catch(h){throw(0,l1.default)(h,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let h;if(c?.type==="hamt-sharded-directory"?h=await BW(l,n[0],o):h=c0e(l,n[0]),h==null)throw(0,l1.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${t}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=d0e[c.type](r,l,c,t,i,s,o);if(f==null)throw(0,l1.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return c.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:c,depth:s,node:l,size:c.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:c,depth:s,node:l,size:c.fileSize()},next:u}},wH=l0e});var bH,u0e,xH,PH,_H=G(()=>{g();xy();Ea();bH=Rn(_a(),1);C0();_W();TW();AW();CW();vH();u0e={[E0]:wH,[of]:RW,[Xu]:SW,[PW.code]:kW},xH=async(r,e,t,n,i,s,o)=>{let a=u0e[r.code];if(a==null)throw(0,bH.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,xH,i,s,o)},PH=xH});async function*p0e(r,e,t={}){let{cid:n,toResolve:i}=h0e(r),s=n.toString(),o=s,a=i.length;for(;;){let d=await PH(n,s,o,i,a,e,t);if(d.entry==null&&d.next==null)throw(0,JE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(d.entry!=null&&(yield d.entry),d.next==null)return;i=d.next.toResolve,n=d.next.cid,s=d.next.name,o=d.next.path}}async function EH(r,e,t={}){let n=await wW(p0e(r,e,t));if(n==null)throw(0,JE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var JE,f0e,h0e,SH=G(()=>{g();JE=Rn(_a(),1);vW();Ol();_H();f0e=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),h0e=r=>{if(r instanceof Uint8Array)return{cid:er.decode(r),toResolve:[]};let e=er.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=f0e(r);return{cid:er.parse(t[0]),toResolve:t.slice(1)}}throw(0,JE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var o$,YE,um,TH=G(()=>{"use strict";g();AE();lh();ef();SH();fA();o$=new TextEncoder,YE=new TextDecoder,um=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:os,...e},this.blockstore=new uh({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 s=await this.getRefsPartition(e,t),o=await s.get(n);if(o){await i.cancel();let{dataSize:u}=JSON.parse(YE.decode(o));return{dataSize:u}}let a=await this.getRefcountsPartition(),d=await a.get(n),l=d?JSON.parse(YE.decode(d)):{count:0,dataSize:0},c;if(l.count>0)await i.cancel(),c=l.dataSize;else{let u=await this.getBlocksPartition(n),f=B0([{content:Et.asAsyncIterable(i)}],u,{cidVersion:1}),h;for await(h of f);c=Number(h.unixfs?.fileSize()??h.size)}return await s.put(n,o$.encode(JSON.stringify({dataSize:c}))),await a.put(n,o$.encode(JSON.stringify({count:l.count+1,dataSize:c}))),{dataSize:c}}async get(e,t,n){let s=await(await this.getRefsPartition(e,t)).get(n);if(!s)return;let{dataSize:o}=JSON.parse(YE.decode(s)),a=await this.getBlocksPartition(n);if(!await a.has(n))return;let c=(await EH(n,a)).content(),u=new ReadableStream({async pull(f){let h=await c.next();h.done?f.close():f.enqueue(h.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(),a=await o.get(n);if(!a)return;let d=JSON.parse(YE.decode(a)),l=d.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,o$.encode(JSON.stringify({count:l,dataSize:d.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 DH(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function kH(r,e,t,n,i){let s=[];for(let l of t.properties){let c=e[l];if(c===void 0||Array.isArray(c))return;s.push(n(c))}let o=e[t.sortProperty];if(o===void 0||Array.isArray(o))return;let a=s.join(ZE),d=n(o);return a+ZE+d+i+r}function AH(r,e,t){let n=[];for(let i of e.properties){let s=r[i];if(s===void 0||typeof s=="object")return;n.push(t(s))}return n.join(ZE)+ZE}function IH(r,e,t,n,i,s){let o=kH(t.messageCid,t.indexes,n,i,s);if(o!==void 0)return CH(r,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(t)})}function RH(r,e,t,n,i,s,o){let a=kH(t,n,i,s,o);if(a!==void 0)return CH(r,e,`__compound:${i.name}__`,{type:"del",key:a})}async function CH(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function s$(r,e,t){let n,i=0;for(let s of t){if(s.sortProperty!==e.sortProperty)continue;let o=!0;for(let a of s.properties){let d=r[a];if(d===void 0||typeof d=="object"){o=!1;break}}o&&s.properties.length>i&&(n=s,i=s.properties.length)}return n}async function $H(r,e,t,n,i,s,o,a,d){let{sortDirection:l=It.Ascending,cursor:c,limit:u}=n,f=AH(t,i,s);if(f===void 0)return a(e,[t],n,d);let h=await DH(r,e,i),p={};if(c===void 0)l===It.Ascending?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);else{let b=s(c.value),T=f+b+o+c.messageCid;l===It.Ascending?(p.gt=T,p.lt=f+"\xFF"):(p.lt=T,p.gt=f,p.reverse=!0)}let m=new Set(i.properties),y={},v=!1;for(let b in t)m.has(b)||(y[b]=t[b],v=!0);let w=[];for await(let[b,T]of h.iterator(p,d)){if(u!==void 0&&w.length===u)break;let D=JSON.parse(T);v&&!tr.matchFilter(D.indexes,y)||w.push(D)}return w}async function OH(r,e,t,n,i,s,o){let a=AH(t,n,i);if(a===void 0)return(await s(e,[t],{sortProperty:n.sortProperty},o)).length;let d=await DH(r,e,n),l=new Set(n.properties),c=!1,u={};for(let p in t)l.has(p)||(u[p]=t[p],c=!0);let f={gt:a,lt:a+"\xFF"},h=0;if(c)for await(let[p,m]of d.iterator(f,o)){let y=JSON.parse(m);tr.matchFilter(y.indexes,u)&&h++}else for await(let[p,m]of d.iterator(f,o))h++;return h}var ZE,BH=G(()=>{"use strict";g();$c();Ed();ZE=""});var jH,fm,a$=G(()=>{"use strict";g();He();pA();Ed();BH();lh();xt();$c();jH="index",fm=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:os,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new rc({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(Ml(n))throw new ne(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let s={messageCid:t,indexes:n},o=[];for(let c in n){let u=n[c];if(Array.isArray(u))for(let f of u){let h=this.createPutIndexedItemOperation(e,s,c,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,s,c,u);o.push(f)}}for(let c of this._compoundIndexes){let u=IH(this.db,e,s,c,r.encodeValue,r.delimiter);u!==void 0&&o.push(u)}let a=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});o.push(a);let d=await Promise.all(o);await(await this.db.partition(e)).batch(d,i)}async delete(e,t,n){let i=[],s=await this.getIndexes(e,t);if(s===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(o);for(let l in s){let c=s[l];if(Array.isArray(c))for(let u of c){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,c);i.push(u)}}for(let l of this._compoundIndexes){let c=RH(this.db,e,t,s,l,r.encodeValue,r.delimiter);c!==void 0&&i.push(c)}let a=await Promise.all(i);await(await this.db.partition(e)).batch(a,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:s}=t,o=r.keySegmentJoin(r.encodeValue(i),s);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let s=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:s})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),s=r.getIndexPartitionName(t);return i.createPartitionOperation(s,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(jH,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(jH)}async query(e,t,n,i){if(t.length===1&&!Ml(t[0])){let s=s$(t[0],n,this._compoundIndexes);if(s!==void 0)return $H(this.db,e,t[0],n,s,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&&!Ml(t[0])){let o=s$(t[0],{...n},this._compoundIndexes);if(o!==void 0)return OH(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:s,limit:o}=n,a=s?this.createStartingKeyFromCursor(s):"",d=[];for await(let l of this.getIndexIterator(e,a,n,i)){if(o!==void 0&&o===d.length)break;let{indexes:c}=l;tr.matchAnyFilter(c,t)&&d.push(l)}return d}async*getIndexIterator(e,t,n,i){let{sortProperty:s,sortDirection:o=It.Ascending,cursor:a}=n,d={gt:t};o===It.Descending&&(d.reverse=!0,a!==void 0&&(d.lt=t,delete d.gt));let l=await this.getIndexPartition(e,s);for await(let[c,u]of l.iterator(d,i)){let{indexes:f,messageCid:h}=JSON.parse(u);yield{indexes:f,messageCid:h}}}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,s=i[t];if(s===void 0)throw new ne(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof s=="boolean"||Array.isArray(s))throw new ne(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof s} was given.`);return{messageCid:n,value:s}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:s,sortDirection:o=It.Ascending,cursor:a,limit:d}=n,l=a?this.createStartingKeyFromCursor(a):void 0,c=new Map;t.length===0&&(t=[{}]);try{for(let p of t)await this.executeSingleFilterQuery(e,p,s,c,i)}catch(p){if(p.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...c.values()].sort((p,m)=>this.sortItems(p,m,s,o)),f=l===void 0?0:this.findCursorStartingIndex(u,o,s,l);if(f<0)return[];let h=d===void 0?void 0:f+d;return u.slice(f,h)}async executeSingleFilterQuery(e,t,n,i,s){let o=d=>{for(let l of d)if(!(i.has(l.messageCid)||!tr.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ne(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(Ml(t)){let d=await this.getAllItems(e,n);o(d);return}let a=$P.reduceFilter(t);for(let d in a){let l=a[d];if(tr.isEqualFilter(l)){let c=await this.filterExactMatches(e,d,l,s);o(c)}else if(tr.isOneOfFilter(l))for(let c of new Set(l)){let u=await this.filterExactMatches(e,d,c,s);o(u)}else if(tr.isRangeFilter(l)){let c=await this.filterRangeMatches(e,d,l,s);o(c)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[s,o]of n.iterator())i.push(JSON.parse(o));return i}async filterExactMatches(e,t,n,i){let s=r.keySegmentJoin(r.encodeValue(n)),o={gt:s},a=await this.getIndexPartition(e,t),d=[];for await(let[l,c]of a.iterator(o,i)){if(!l.startsWith(s))break;d.push(JSON.parse(c))}return d}async filterRangeMatches(e,t,n,i){let s={};for(let d in n){let l=d,c=r.encodeValue(n[l]);l==="lte"?s[l]=c+"\xFF":s[l]=c}s.gt===void 0&&s.gte===void 0&&(s.reverse=!0);let o=[],a=await this.getIndexPartition(e,t);for await(let[d,l]of a.iterator(s,i))"gt"in n&&this.extractIndexValueFromKey(d)===r.encodeValue(n.gt)||o.push(JSON.parse(l));return o}sortItems(e,t,n,i){let s=e.indexes[n],o=t.indexes[n],a=r.encodeValue(s)+e.messageCid,d=r.encodeValue(o)+t.messageCid;return i===It.Ascending?j0(a,d):j0(d,a)}findCursorStartingIndex(e,t,n,i){let s=d=>{let{messageCid:l,indexes:c}=d,u=c[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===It.Ascending?f>i:f<i},o=0,a=e.length;for(;o<a;){let d=o+a>>>1;s(e[d])?a=d:o=d+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,s=e<0?n:"",o=e<0?t:0;return s+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 QE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*m0e(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],s=er.asCID(n);s?yield[i.join("/"),s]:typeof n=="object"&&(yield*c$(n,i))}else{let t=er.asCID(e);t?yield[r.join("/"),t]:yield*c$(e,r)}}function*c$(r,e){if(r==null||r instanceof Uint8Array)return;let t=er.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let s=[...e,n];yield*m0e(s,i)}}function*y0e(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!er.asCID(n)&&(yield*d$(n,i))}else yield*d$(e,r)}function*d$(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"&&!er.asCID(n)&&(yield*y0e(i,n))}}function g0e(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 s=er.asCID(t);if(s)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}async function NH({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),s=er.create(1,e.code,i);return new XE({value:r,bytes:n,cid:s})}async function MH({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),s=er.create(1,e.code,i);return new XE({value:n,bytes:r,cid:s})}var XE,UH=G(()=>{g();v0();pk();XE=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:QE(),bytes:QE(),value:QE(),asBlock:QE()})}links(){return c$(this.value,[])}tree(){return d$(this.value,[])}get(e="/"){return g0e(this.value,e.split("/").filter(Boolean))}}});var v0e,hm,KH=G(()=>{"use strict";g();UH();xy();AE();Nl();Ol();lh();kE();a$();vr();Bu();Ed();v0e=[{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"}],hm=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:os,...e},this.blockstore=new uh({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new fm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??v0e})}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 Xn(this.blockstore.partition(e),n?.signal),s=er.parse(t),o=await i.get(s,n);return o?(await Xn(MH({bytes:o,codec:$l,hasher:Kn}),n?.signal)).value:void 0}async query(e,t,n,i,s){s?.signal?.throwIfAborted();let o=r.buildQueryOptions(n,i),a=await this.index.query(e,t,o,s),d;i?.limit!==void 0&&i.limit<a.length&&(a.splice(-1),d=fm.createCursorFromLastArrayItem(a,o.sortProperty));let l=[];for(let c=0;c<a.length;c++){let{messageCid:u}=a[c],f=await this.get(e,u,s);f&&l.push(f)}return{messages:l,cursor:d}}async count(e,t,n,i){i?.signal?.throwIfAborted();let s=r.buildQueryOptions(n);return this.index.count(e,t,s,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:s,datePublished:o,messageTimestamp:a}=e,d=It.Ascending,l="messageTimestamp";return s!==void 0?l="dateCreated":o!==void 0?l="datePublished":a!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(d=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:d,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Xn(this.blockstore.partition(e),n?.signal),s=er.parse(t);await i.delete(s,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let s=await Xn(this.blockstore.partition(e),i?.signal),o=await Xn(NH({value:t,codec:$l,hasher:Kn}),i?.signal),a=pr.parseCid(await ye.getCid(t));await s.put(a,o.bytes,i);let d=a.toString();await this.index.put(e,d,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var pm,LH=G(()=>{"use strict";g();Nl();lh();pm=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:os,...e},this.db=new rc({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 pr.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 s=JSON.parse(i);if(Date.now()>=s.timeout&&(s.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,s.retryCount++,await this.db.put(s.id,JSON.stringify(s)),t.push(s)),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 qH(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 zH=G(()=>{g()});var FH,mm,GH=G(()=>{"use strict";g();zH();$c();xt();FH="events",mm=class r{emitter=qH();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),s=>s.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){let d=this.tenantLogs.get(e);if(d!==void 0&&d.size>0){let l=d.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}else i="epoch_mismatch";let s=await this.getReplayBounds(e),o={requested:t,oldestAvailable:s?.oldest??t,latestAvailable:s?.latest??t,reason:i},a=new ne(re.EventLogProgressGap,`progress token gap: ${i}`);throw a.gapInfo=o,a}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 ne(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let a=this.tenantLogs.get(e);if(a===void 0&&(a=new Map,this.tenantLogs.set(e,a)),a.set(o,{event:t,indexes:n,messageCid:i}),a.size>this.maxEventsPerTenant){let l=a.size-this.maxEventsPerTenant,c=0;for(let u of a.keys()){if(c>=l)break;a.delete(u),c++}}let d=`${e}_${FH}`;return this.emitter.emit(d,{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:s}=t;n!==void 0&&await this.validateCursor(e,n);let o=n===void 0?void 0:r.parsePosition(n.position),a=this.tenantLogs.get(e);if(a===void 0||a.size===0)return{events:[],cursor:n};let d=[],l=i??Number.MAX_SAFE_INTEGER;for(let[c,u]of a)if(!(o!==void 0&&c<=o)&&!(s!==void 0&&s.length>0&&!tr.matchAnyFilter(u.indexes,s))&&(d.push({seq:c,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),d.length>=l))break;if(d.length>0){let c=d[d.length-1],u=await this.buildToken(e,c.seq,c.messageCid);return{events:d,cursor:u}}return{events:d,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ne?t:new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let s=`${e}_${FH}`,{cursor:o,filters:a}=i??{},d=async c=>this.buildToken(e,c.seq,c.messageCid);if(o!==void 0){await this.validateCursor(e,o);let c=r.parsePosition(o.position),u=[],f=!1,h=v=>{a!==void 0&&a.length>0&&!tr.matchAnyFilter(v.indexes,a)||(f?d(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(s,h);let p=await this.read(e,{cursor:o,filters:a}),m=p.cursor??o,y=p.cursor===void 0?c:r.parsePosition(p.cursor.position);for(let v of p.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(s,h)}}}let l=c=>{a!==void 0&&a.length>0&&!tr.matchAnyFilter(c.indexes,a)||d(c).then(u=>{n({type:"event",cursor:u,event:c.event})})};return this.emitter.on(s,l),{id:t,close:async()=>{this.emitter.off(s,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],s=n[n.length-1],o=t.get(i),a=t.get(s),d=await this.buildToken(e,i,o.messageCid),l=await this.buildToken(e,s,a.messageCid);return{oldest:d,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,s]of n)(s.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var nw,l$=G(()=>{"use strict";g();Rf();nw=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=dn(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=dn(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=dn(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return If(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",dn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:dn(e.leftHash),rightHash:dn(e.rightHash)}:{type:"leaf",keyHash:dn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:If(e.leftHash),rightHash:If(e.rightHash)}:{type:"leaf",keyHash:If(e.keyHash),valueCid:e.valueCid}}}});var iw,u$=G(()=>{"use strict";g();Rf();iw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await tu()}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 Af(e),n=await fg(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let s=await this.getRoot(),o=await this.insertAtNode(s,t,n,i,0);return await this.store.setRoot(o),o}async delete(e){let t=await Af(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 Af(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Af(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(cn(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?.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let s=i;e[n]?t=s.rightHash:t=s.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(cn(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 s=i;e[n]?t=s.rightHash:t=s.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(cn(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],s=[];return await this.diffAtNode(t,n,0,this,e,i,s),{onlyLocal:i,onlyRemote:s}}async insertAtNode(e,t,n,i,s){if(s>=_o||cn(e,this.defaultHashes[s]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return cn(o.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,i,n,s);let a=o,d=xs(t,s),l,c;d?(l=a.leftHash,c=await this.insertAtNode(a.rightHash,t,n,i,s+1)):(l=await this.insertAtNode(a.leftHash,t,n,i,s+1),c=a.rightHash);let u=await ru(l,c);if(!cn(u,e)){let f={type:"internal",leftHash:l,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,s){let o=s;for(;o<_o&&xs(e.keyHash,o)===xs(n.keyHash,o);)o++;if(o>=_o)return i;let a=xs(e.keyHash,o),d,l;a?(d=i,l=t):(d=t,l=i);let c=await ru(d,l);await this.store.putNode(c,{type:"internal",leftHash:d,rightHash:l});for(let u=o-1;u>=s;u--){let f=xs(e.keyHash,u),h=this.defaultHashes[u+1],p,m;f?(p=h,m=c):(p=c,m=h),c=await ru(p,m),await this.store.putNode(c,{type:"internal",leftHash:p,rightHash:m})}return c}async deleteAtNode(e,t,n){if(n>=_o)return this.defaultHashes[_o];if(cn(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 cn(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let s=i,o=xs(t,n),a,d;if(o?(a=s.leftHash,d=await this.deleteAtNode(s.rightHash,t,n+1)):(a=await this.deleteAtNode(s.leftHash,t,n+1),d=s.rightHash),cn(a,this.defaultHashes[n+1])&&cn(d,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=cn(a,this.defaultHashes[n+1]),c=cn(d,this.defaultHashes[n+1]);if(l||c){let f=l?d:a;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let u=await ru(a,d);if(!cn(u,e)){let f={type:"internal",leftHash:a,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=_o||cn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return cn(i.keyHash,t);let s=i;return xs(t,n)?this.existsAtNode(s.rightHash,t,n+1):this.existsAtNode(s.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=_o)return{siblings:[],leafNode:void 0,depth:n};if(cn(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 s=i,o=xs(t,n),a,d;o?(a=s.rightHash,d=s.leftHash):(a=s.leftHash,d=s.rightHash);let l=await this.generateProof(a,t,n+1);return l.siblings.unshift(d),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(xs(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await fg(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(xs(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=_o||cn(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,s=await this.collectLeaves(i.leftHash,t+1),o=await this.collectLeaves(i.rightHash,t+1);return[...s,...o]}async diffAtNode(e,t,n,i,s,o,a){if(cn(e,t)||n>=_o)return;let d=cn(e,this.defaultHashes[n]),l=cn(t,this.defaultHashes[n]);if(d&&!l){let f=await s.collectLeaves(t,n);a.push(...f);return}if(!d&&l){let f=await i.collectLeaves(e,n);o.push(...f);return}let c=await i.store.getNode(e),u=await s.store.getNode(t);if(c?.type==="leaf"&&u?.type==="leaf"){cn(c.keyHash,u.keyHash)?c.valueCid!==u.valueCid&&(o.push(c.valueCid),a.push(u.valueCid)):(o.push(c.valueCid),a.push(u.valueCid));return}if(c?.type==="leaf"){let f=await s.collectLeaves(t,n),h=c.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&a.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),h=u.valueCid;new Set(f).has(h)||a.push(h);for(let m of f)m!==h&&o.push(m);return}if(c?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(c.leftHash,u.leftHash,n+1,i,s,o,a),await this.diffAtNode(c.rightHash,u.rightHash,n+1,i,s,o,a);return}if(c===void 0){let f=await s.collectLeaves(t,n);a.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);o.push(...f)}}}});var ym,WH=G(()=>{"use strict";g();Rf();l$();u$();lh();ym=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:os,...e}}async open(){this.db=new rc({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await tu()}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 s=n.protocol;s!==void 0&&await(await this.getProtocolTree(e,s)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let s=await this.getStoredIndexes(e,i);if(await n.delete(i),s!==void 0){let o=s.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 nw(n),s=new iw(i);return await s.initialize(),s}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),s={protocol:n.protocol};await i.put(t,JSON.stringify(s))}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 eS,HH=G(()=>{"use strict";g();Rf();eS=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(dn(e))}async putNode(e,t){this.nodes.set(dn(e),t)}async deleteNode(e){this.nodes.delete(dn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var b0e,tS,VH=G(()=>{"use strict";g();xy();Ol();ef();is();yT();Cn();sd();__();T_();ia();Px();f2();p2();ni();b_();hb();x_();P2();Zo();He();ix();Bu();Yo();gn();nv();lr();jy();b0e={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},tS=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}`,s=e?.keyPair??await dc.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let d=await kt.generateKey();o={publicJwk:await kt.getPublicKey({key:d}),privateJwk:d}}return{did:t,keyId:i,keyPair:s,encryptionKeyPair:o,signer:new Al({privateJwk:s.privateJwk,algorithm:s.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await Ka.create({definition:b0e,signer:lt.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 a="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[a]={schema:"test-object",dataFormats:["text/plain"]},n.structure[a]={}}let i=lt.createSigner(t),s={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await Ka.create(s);return{author:t,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=lt.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Mt(i);let s=await La.create(i);return{author:t,message:s.message,protocolsQuery:s}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??At.createOffsetTimestamp({seconds:10}),s=e?.scope??{interface:xe.Messages,method:me.Read},o=lt.createSigner(t),a=n.did,d={signer:o,grantedTo:a,dateExpires:i,scope:s,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await Qe.createGrant(d);return{dataStream:Et.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=lt.createSigner(t),i=lt.createSigners(e?.attesters??[]),s=e?.dataCid,o=e?.dataSize,a,d;s===void 0&&o===void 0&&(a=e?.data??r.randomBytes(32),d=Et.fromBytes(a));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:a,dataCid:s,dataSize:o,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},c=await _t.create(l),u=c.message;return{author:t,message:u,dataCid:s,dataSize:o,dataBytes:a,dataStream:d,recordsWrite:c}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:s,protocolPath:o,protocolParentContextId:a,protocolContextDerivingRootKeyId:d,protocolContextDerivedPublicKeyJwk:l}=e,c=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:h}=await Ai.aeadEncrypt(pi.A256GCM,u,c,t),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:s.protocol,protocolPath:o,parentContextId:a,schema:s.types[m].schema,dataFormat:s.types[m].dataFormats?.[0],data:f}),b={initializationVector:c,key:u,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let T=s.structure;for(let C of p)T=T[C];let D=T.$encryption?.publicKeyJwk,M={publicKeyId:T.$encryption?.rootKeyId,publicKey:D,derivationScheme:St.ProtocolPath};b.keyEncryptionInputs.push(M)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let T;if(a===void 0){let D={rootKeyId:n.keyId,derivationScheme:St.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},I=await _t.getEntryId(n.did,y.descriptor),M=ke.constructKeyDerivationPathUsingProtocolContextScheme(I),C=await zi.derivePublicKey(D,M);T={publicKeyId:n.keyId,publicKey:C,derivationScheme:St.ProtocolContext}}else{if(d===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");T={publicKeyId:d,publicKey:l,derivationScheme:St.ProtocolContext}}b.keyEncryptionInputs.push(T)}return await w.encryptSymmetricEncryptionKey(b),await w.sign({signer:lt.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:b}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=At.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),s=e.datePublished??(i?n:void 0),o=e.data??r.randomBytes(32),a=Et.fromBytes(o),d={recordsWriteMessage:e.existingWrite.message,data:o,published:i,datePublished:s,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:lt.createSigner(e.author)},l=await _t.createFrom(d);return{message:l.message,recordsWrite:l,dataBytes:o,dataStream:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Mt(s);let a=(await $a.create(s)).message;return{author:t,message:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Mt(s);let a=(await za.create(s)).message;return{author:t,message:a}}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=lt.createSigner(t));let s={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};Mt(s);let a=(await Md.create(s)).message;return{author:t,message:a}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await qa.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:lt.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=lt.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Mt(i);let s=await Kd.create(i),o=s.message;return{author:t,messagesSubscribe:s,message:o}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:lt.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},s=await Ud.create(i);return{author:t,messagesRead:s,message:s.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Cw.generateKeyPair(),t=await Cw.sign(r.randomBytes(32),e.privateJwk);return Ie.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 Kn.digest(e);return(await er.createV1(Xu,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:s,minute:o,second:a,millisecond:d,microsecond:l}=e||{};return At.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:s||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:a||this.randomInt(0,59),millisecond:d||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 sm.create(),t=await sm.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),s={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},o=await kt.generateKey(),d={publicJwk:await kt.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:s,encryptionKeyPair:d,signer:new Al({privateJwk:s.privateJwk,algorithm:s.privateJwk.alg,keyId:n})}}}});var rS,JH=G(()=>{"use strict";g();He();rS=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 yd(t)}}}});var YH={};ir(YH,{AllowAllTenantGate:()=>lg,BlockstoreLevel:()=>uh,Cid:()=>pr,ContentEncryptionAlgorithm:()=>pi,CoreProtocolRegistry:()=>dg,DataStoreLevel:()=>um,DataStream:()=>Et,DateSort:()=>Ut,Dwn:()=>Qg,DwnConstant:()=>bs,DwnError:()=>ne,DwnErrorCode:()=>re,DwnInterfaceName:()=>xe,DwnMethodName:()=>me,Encoder:()=>Ie,Encryption:()=>Ai,EventEmitterEventLog:()=>mm,HdKey:()=>zi,IndexLevel:()=>fm,Jws:()=>lt,KeyAgreementAlgorithm:()=>rv,KeyDerivationScheme:()=>St,LevelWrapper:()=>rc,Message:()=>ye,MessageStoreLevel:()=>hm,MessagesRead:()=>Ud,MessagesSubscribe:()=>Kd,MessagesSync:()=>Cf,PERMISSIONS_REVOCATION_PATH:()=>OP,PermissionConditionPublication:()=>Ny,PermissionGrant:()=>Ht,PermissionRequest:()=>Oa,PermissionsProtocol:()=>Qe,Poller:()=>rS,PrivateKeySigner:()=>Al,ProtocolRecordLimitStrategy:()=>Cu,Protocols:()=>Gd,ProtocolsConfigure:()=>Ka,ProtocolsQuery:()=>La,Records:()=>ke,RecordsCount:()=>Md,RecordsDelete:()=>qa,RecordsQuery:()=>$a,RecordsRead:()=>Hd,RecordsSubscribe:()=>za,RecordsWrite:()=>_t,ResumableTaskStoreLevel:()=>pm,SMTStoreLevel:()=>nw,SMTStoreMemory:()=>eS,SMT_DEPTH:()=>_o,Secp256k1:()=>dc,Secp256r1:()=>kl,SortDirection:()=>It,SparseMerkleTree:()=>iw,StateIndexLevel:()=>ym,TestDataGenerator:()=>tS,Time:()=>At,ZERO_HASH:()=>k_,authenticate:()=>bn,createLevelDatabase:()=>os,executeUnlessAborted:()=>Xn,getBit:()=>xs,getDefaultHashes:()=>ER,getRuleSetAtPath:()=>Wd,hashChildren:()=>ru,hashEquals:()=>cn,hashKey:()=>Af,hashLeaf:()=>fg,hashToHex:()=>dn,hexToHash:()=>If,initDefaultHashes:()=>tu,isCrossProtocolRef:()=>qf,parseCrossProtocolRef:()=>es});var fn=G(()=>{"use strict";g();kw();ra();xR();oI();PR();Nl();b_();x_();ef();jy();gW();ug();xt();lr();Cn();T_();nv();Zo();kE();sd();vr();__();SR();Tc();_R();ia();Px();Np();f2();p2();ni();hb();T6();P2();ix();vD();Ed();Yo();sI();rp();AE();TH();a$();lh();KH();LH();GH();WH();u$();l$();HH();Rf();VH();JH()});var cS=Te((aYe,oV)=>{g();var dw=1e3,lw=dw*60,uw=lw*60,Pm=uw*24,$0e=Pm*7,O0e=Pm*365.25;oV.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return B0e(r);if(t==="number"&&isFinite(r))return e.long?N0e(r):j0e(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function B0e(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*O0e;case"weeks":case"week":case"w":return t*$0e;case"days":case"day":case"d":return t*Pm;case"hours":case"hour":case"hrs":case"hr":case"h":return t*uw;case"minutes":case"minute":case"mins":case"min":case"m":return t*lw;case"seconds":case"second":case"secs":case"sec":case"s":return t*dw;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function j0e(r){var e=Math.abs(r);return e>=Pm?Math.round(r/Pm)+"d":e>=uw?Math.round(r/uw)+"h":e>=lw?Math.round(r/lw)+"m":e>=dw?Math.round(r/dw)+"s":r+"ms"}function N0e(r){var e=Math.abs(r);return e>=Pm?aS(r,e,Pm,"day"):e>=uw?aS(r,e,uw,"hour"):e>=lw?aS(r,e,lw,"minute"):e>=dw?aS(r,e,dw,"second"):r+" ms"}function aS(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();function zbe(r,e){return{definition:r}}g();g();g();fn();fn();var ve;(function(r){r.MessagesRead="MessagesRead",r.MessagesSubscribe="MessagesSubscribe",r.MessagesSync="MessagesSync",r.ProtocolsConfigure="ProtocolsConfigure",r.ProtocolsQuery="ProtocolsQuery",r.RecordsDelete="RecordsDelete",r.RecordsQuery="RecordsQuery",r.RecordsRead="RecordsRead",r.RecordsSubscribe="RecordsSubscribe",r.RecordsWrite="RecordsWrite"})(ve||(ve={}));var gm={[ve.MessagesRead]:Ud,[ve.MessagesSubscribe]:Kd,[ve.MessagesSync]:Cf,[ve.ProtocolsConfigure]:Ka,[ve.ProtocolsQuery]:La,[ve.RecordsDelete]:qa,[ve.RecordsQuery]:$a,[ve.RecordsRead]:Hd,[ve.RecordsSubscribe]:za,[ve.RecordsWrite]:_t};g();var x0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function f$(r){return x0e(this,void 0,void 0,function*(){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort((l,c)=>l.localeCompare(c))),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort((l,c)=>l.localeCompare(c))));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=yield crypto.subtle.digest("SHA-256",n),s=new Uint8Array(i),o="";for(let l of s)o+=String.fromCharCode(l);let a=btoa(o).replaceAll("+","-").replaceAll("/","_"),d=a.length;for(;d>0&&a.codePointAt(d-1)===61;)d--;return d===a.length?a:a.slice(0,d)})}var h$=100;g();var xu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},ZH=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(s){t[s]=r[s]&&function(o){return new Promise(function(a,d){o=r[s](o),i(a,d,o.done,o.value)})}}function i(s,o,a,d){Promise.resolve(d).then(function(l){s({value:l,done:a})},o)}},p$="^",ho=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${p$}${t}${p$}${n}`}getOrCreateLink(e){return xu(this,void 0,void 0,function*(){let t=yield f$(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let s=yield this.sublevel.get(n),o=JSON.parse(s);return delete o.push,o.connectivity="unknown",o}catch(s){if(s.code!=="LEVEL_NOT_FOUND")throw s}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 yield this.sublevel.put(n,JSON.stringify(i)),i})}saveLink(e){return xu(this,void 0,void 0,function*(){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),yield this.sublevel.put(t,JSON.stringify(e))})}deleteLink(e,t,n){return xu(this,void 0,void 0,function*(){let i=r.buildKey(e,t,n);yield this.sublevel.del(i)})}getLinksForTenant(e){return xu(this,void 0,void 0,function*(){var t,n,i,s;let o=`${e}${p$}`,a=[];try{for(var d=!0,l=ZH(this.sublevel.iterator()),c;c=yield l.next(),t=c.done,!t;d=!0){s=c.value,d=!1;let[u,f]=s;u.startsWith(o)&&a.push(JSON.parse(f))}}catch(u){n={error:u}}finally{try{!d&&!t&&(i=l.return)&&(yield i.call(l))}finally{if(n)throw n.error}}return a})}getAllLinks(){return xu(this,void 0,void 0,function*(){var e,t,n,i;let s=[];try{for(var o=!0,a=ZH(this.sublevel.iterator()),d;d=yield a.next(),e=d.done,!e;o=!0){i=d.value,o=!1;let[,l]=i;s.push(JSON.parse(l))}}catch(l){t={error:l}}finally{try{!o&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(t)throw t.error}}return s})}updateDelegateDid(e,t){return xu(this,void 0,void 0,function*(){let n=yield this.getLinksForTenant(e),i=[];for(let s of n)s.delegateDid!==t&&(s.delegateDid=t,yield this.saveLink(s),i.push(s));return i})}setStatus(e,t){return xu(this,void 0,void 0,function*(){e.status=t,yield 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}markNeedsReconcile(e,t){return xu(this,void 0,void 0,function*(){e.needsReconcile||(e.needsReconcile=!0,yield this.saveLink(e))})}clearNeedsReconcile(e){return xu(this,void 0,void 0,function*(){e.needsReconcile&&(e.needsReconcile=!1,yield this.saveLink(e))})}};g();var oi;(function(r){r.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",r.InitialWriteMissing="ClosureInitialWriteMissing",r.ParentChainMissing="ClosureParentChainMissing",r.ContextChainMissing="ClosureContextChainMissing",r.GrantMissing="ClosureGrantMissing",r.GrantNotYetActive="ClosureGrantNotYetActive",r.GrantExpired="ClosureGrantExpired",r.GrantRevocationMissing="ClosureGrantRevocationMissing",r.VisibilityFloorMissing="ClosureVisibilityFloorMissing",r.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",r.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",r.DependencyForbidden="ClosureDependencyForbidden",r.DepthExceeded="ClosureDepthExceeded"})(oi||(oi={}));function nS(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 QH(r,e){var t;let n=e.descriptor;if(n.interface==="Protocols"&&n.method==="Configure"){let i=n.definition?n.definition.protocol:void 0;i&&r.protocolCache.delete(i)}if(n.protocol==="https://identity.foundation/dwn/permissions"){let i=e.recordId,s=n.protocolPath;if(s==="grant"&&i&&(r.grantCache.delete(i),r.satisfiedDeps.delete(`permissionGrant:grantId:${i}`),r.missingDeps.delete(`permissionGrant:grantId:${i}`)),s==="grant/revocation"){let o=n.parentId;o&&(r.grantCache.delete(`revocation:${o}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${o}`),r.missingDeps.delete(`grantRevocation:grantId:${o}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${o}`),r.missingDeps.delete(`permissionGrant:grantId:${o}`))}}if(n.interface==="Records"){let i=e.recordId,s=n.protocol,o=n.protocolPath;if(i){let a=d=>{let l=d.indexOf(i);if(l===-1)return!1;let c=l>0?d[l-1]:":",u=l+i.length<d.length?d[l+i.length]:"|",f=c===":"||c==="|",h=u==="|"||u===void 0;return f&&(l+i.length===d.length||h)};for(let d of r.satisfiedDeps)a(d)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)a(d)&&r.missingDeps.delete(d)}if(s&&o){let a=`filter:${s}|${o}`;for(let d of r.satisfiedDeps)d.includes(a)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)d.includes(a)&&r.missingDeps.delete(d)}if(s==="https://identity.foundation/protocols/key-delivery"){let a=(t=e.descriptor)===null||t===void 0?void 0:t.tags,d=a?.protocol;if(d){let l=`messageCid:${d}|`;for(let c of r.satisfiedDeps)c.includes(l)&&r.satisfiedDeps.delete(c);for(let c of r.missingDeps)c.includes(l)&&r.missingDeps.delete(c)}}else if(s){let a=`messageCid:${s}|`;for(let d of r.satisfiedDeps)d.includes(a)&&r.satisfiedDeps.delete(d);for(let d of r.missingDeps)d.includes(a)&&r.missingDeps.delete(d)}}}g();fn();g();function XH(r,e){let[t,...n]=e.split("/"),i=r.structure[t];for(let s of n){if(!i)return;i=i[s]}return i}function wm(r,e){let t=XH(r,e);if(!t)return!1;function n(i){for(let s in i)if(!s.startsWith("$")){let o=i[s];if(o.$role===!0||n(o))return!0}return!1}return n(t)?!0:m$(void 0,e,r)}function m$(r,e,t){function n(i){var s;if(i.$actions){for(let o of i.$actions)if(o.who&&o.who!=="anyone"&&(r===void 0||o.who===r)&&o.of===e&&(!((s=o.can)===null||s===void 0)&&s.includes("read")))return!0}for(let o in i)if(!o.startsWith("$")&&n(i[o]))return!0;return!1}for(let i in t.structure)if(n(t.structure[i]))return!0;return!1}function y$({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let s=new Set,o=XH(r,e);return o&&(o.$role===!0&&t&&s.add(t),t&&t!==n&&m$("recipient",e,r)&&s.add(t),i&&i!==n&&m$("author",e,r)&&s.add(i),s.delete(n)),s}var g$=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function P0e(r){let t=r.descriptor.protocol;return t?t===Qe.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function _0e(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 s=r.contextId;if(s&&n&&s!==n){let o=s.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:o,identifierType:"recordId"})}if(n&&e.method==="Write"){let o=e.dateCreated,a=e.messageTimestamp;o&&a&&o!==a&&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 E0e(r){var e;let t=[],n=r.authorization;if(!n)return[];let i=(e=n.signature)===null||e===void 0?void 0:e.payload;if(i)try{let s=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));s.permissionGrantId&&(t.push({dependencyClass:3,label:"permissionGrant",identifier:s.permissionGrantId,identifierType:"grantId"}),t.push({dependencyClass:3,label:"grantRevocation",identifier:s.permissionGrantId,identifierType:"grantId"}))}catch{}return t}function S0e(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let s of t){if(!Object.hasOwn(n,s))return;i=n[s],n=i}return i}function T0e(r,e,t){var n,i,s;let o=r.descriptor;if(o.interface!=="Records")return[];let a=o.protocolPath;if(!a)return[];let d=[],l=S0e(e?.structure,a);if(l?.$encryption){let h=a.split("/").pop(),p=(n=e?.types)===null||n===void 0?void 0:n[h??""];if(p?.encryptionRequired===!0){d.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:o.protocol,identifierType:"protocol"});let m=r.contextId,y=!1;if(m){let w=a.split("/")[0];y=wm(e,w)}if(t&&!y||d.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"}),y&&m){let w=m.split("/")[0];d.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${o.protocol}|${w}`,identifierType:"messageCid"})}}}let c=a.split("/")[0],u=(i=e?.structure)===null||i===void 0?void 0:i[c];if(u?.$ref){let h=u.$ref.indexOf(":");if(h>0){let p=u.$ref.substring(0,h),m=e?.uses,y=m?.[p];if(y){d.push({dependencyClass:6,label:"crossProtocolConfig",identifier:y,identifierType:"protocol"});let v=a.split("/"),w=o.parentId;v.length===2&&w&&d.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${y}|${w}`,identifierType:"recordId"})}}}let f=r.authorization;if(f&&e?.uses){let h=(s=f.signature)===null||s===void 0?void 0:s.payload;if(h)try{let m=JSON.parse(Buffer.from(h,"base64url").toString("utf-8")).protocolRole;if(m?.includes(":")){let y=m.indexOf(":"),v=m.substring(0,y),w=e.uses[v];if(w){d.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:w,identifierType:"protocol"});let b=m.substring(y+1),T=ye.getAuthor(r),D=r.contextId;if(T){let I={interface:"Records",method:"Write",protocol:w,protocolPath:b,recipient:T,isLatestBaseState:!0};if(D){let C=b.split("/").length-1;if(C>0){let L=D.split("/").slice(0,C).join("/");L&&(I.contextId={gte:L,lt:L+"\uFFFF"})}}let M=I.contextId?JSON.stringify(I.contextId):"no-context";d.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${w}|${b}|${T}|${M}`,identifierType:"filter",filter:I})}}}}catch{}}return d}function w$(r,e,t,n){return g$(this,void 0,void 0,function*(){var i;if(t.kind==="full")return{complete:!0,rootMessageCid:yield ye.getCid(r),edges:[],depth:0};let s=yield ye.getCid(r),o=[],a=new Set,d=0,l=[r];for(a.add(s);l.length>0;){if(d>=n.maxDepth)return{complete:!1,rootMessageCid:s,edges:o,failure:{code:oi.DepthExceeded,edge:{dependencyClass:1,label:"depth",identifier:String(d),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:d};let c=l.length;for(let u=0;u<c;u++){let f=l.shift(),h=[...P0e(f),..._0e(f),...E0e(f)],p=yield eV(h,o,e,n,a,l,s,d);if(p)return p;let y=f.descriptor.protocol;if(y){let v=n.protocolCache.get(y),w=(i=v?.descriptor)===null||i===void 0?void 0:i.definition;if(w){let b=T0e(f,w,n.isDelegateSession),T=yield eV(b,o,e,n,a,l,s,d);if(T)return T}}if(d===0){let v=D0e(f,o,n,s,d);if(v)return v}}d++}return{complete:!0,rootMessageCid:s,edges:o,depth:d}})}function D0e(r,e,t,n,i){var s;let o=e.find(p=>p.label==="permissionGrant");if(!o)return null;let a=r.descriptor.messageTimestamp;if(!a)return null;let d=t.grantCache.get(o.identifier);if(!d)return null;let l=d.descriptor.dateCreated,c,u=d.encodedData;if(u)try{c=JSON.parse(Buffer.from(u,"base64url").toString("utf-8")).dateExpires}catch{}if(l&&a<l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantNotYetActive,edge:o,detail:`grant '${o.identifier}' is not yet active at message timestamp ${a} (dateGranted: ${l})`},depth:i};if(c&&a>=c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantExpired,edge:o,detail:`grant '${o.identifier}' expired at ${c}, message timestamp is ${a}`},depth:i};let f=`revocation:${o.identifier}`,h=t.grantCache.get(f);if(h&&h.descriptor.interface!=="Synthetic"){let p=h.descriptor.messageTimestamp;if(p&&p<=a)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:oi.GrantRevocationMissing,edge:(s=e.find(m=>m.label==="grantRevocation"))!==null&&s!==void 0?s:o,detail:`grant '${o.identifier}' was revoked at ${p}, before message timestamp ${a}`},depth:i}}return null}function eV(r,e,t,n,i,s,o,a){return g$(this,void 0,void 0,function*(){for(let d of r){e.push(d);let l=`${d.label}:${d.identifierType}:${d.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:o,edges:e,failure:{code:tV(d),edge:d,detail:`dependency '${d.label}' (${d.identifier}) is missing`},depth:a};let c=yield k0e(d,t,n);if(!c)return n.missingDeps.add(l),{complete:!1,rootMessageCid:o,edges:e,failure:{code:tV(d),edge:d,detail:`dependency '${d.label}' (${d.identifier}) not found locally`},depth:a};if(n.satisfiedDeps.add(l),!(d.identifierType==="grantId"||d.identifierType==="filter"||d.label==="contextKeyRecord")){let f=yield ye.getCid(c);i.has(f)||(i.add(f),s.push(c))}}return null})}function k0e(r,e,t){return g$(this,void 0,void 0,function*(){var n,i,s,o;switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return(n=t.protocolCache.get(r.identifier))!==null&&n!==void 0?n:null;let{messages:a}=yield e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),d=a.length>0?a[0]:null;return t.protocolCache.set(r.identifier,d),d}case"recordId":{if(r.label==="initialWrite"){let{messages:d}=yield e.query(t.tenantDid,[{entryId:r.identifier}]);if(d.length>0)return d[0];let{messages:l}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return l.length>0?l[0]:null}if(r.label==="crossProtocolParent"){let d=r.identifier.indexOf("|");if(d>0){let l=r.identifier.substring(0,d),c=r.identifier.substring(d+1),{messages:u}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:l,recordId:c,isLatestBaseState:!0}]);return u.length>0?u[0]:null}}let{messages:a}=yield e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return a.length>0?a[0]:null}case"grantId":{if(r.label==="grantRevocation"){let l=`revocation:${r.identifier}`;if(t.grantCache.has(l))return(i=t.grantCache.get(l))!==null&&i!==void 0?i:null;let{messages:c}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),u;for(let p of c){let m=p.descriptor.messageTimestamp;(!u||m<u.descriptor.messageTimestamp)&&(u=p)}let h=u??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(l,h),h}if(t.grantCache.has(r.identifier))return(s=t.grantCache.get(r.identifier))!==null&&s!==void 0?s:null;let{messages:a}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),d=a.length>0?a[0]:null;return t.grantCache.set(r.identifier,d),d}case"messageCid":{if(r.label==="contextKeyRecord"){let a=r.identifier.indexOf("|");if(a>0){let d=r.identifier.substring(0,a),l=r.identifier.substring(a+1),{messages:c}=yield e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":d,"tag.contextId":l}]);return c.length>0?c[0]:null}}return(o=yield e.get(t.tenantDid,r.identifier))!==null&&o!==void 0?o:null}case"filter":{if(!r.filter)return null;let{messages:a}=yield e.query(t.tenantDid,[r.filter]);return a.length>0?a[0]:null}default:return null}})}function tV(r){switch(r.dependencyClass){case 1:return oi.ProtocolMetadataMissing;case 2:return r.label==="initialWrite"?oi.InitialWriteMissing:r.label==="parentRecord"?oi.ParentChainMissing:r.label==="contextRoot"?oi.ContextChainMissing:oi.ParentChainMissing;case 3:return r.label==="permissionGrant"?oi.GrantMissing:oi.GrantRevocationMissing;case 4:return r.label==="squashContextRoot"?oi.VisibilityFloorMissing:oi.VisibilityFloorMissing;case 5:return oi.EncryptionDependencyMissing;case 6:return oi.CrossProtocolReferenceMissing;default:return oi.DependencyForbidden}}g();is();He();var A0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},vm=class extends DE{constructor({agent:e,db:t,location:n,ttl:i}){super({db:t,location:n,ttl:i}),this._resolving=new Map,this._agent=e}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(e){this._agent=e}get(e){return A0e(this,void 0,void 0,function*(){try{let t=yield this.cache.get(e),n=JSON.parse(t);if(!this._resolving.has(e)&&Date.now()>=n.ttlMillis){this._resolving.set(e,!0);let i=yield this.agent.did.get({didUri:e,tenant:this.agent.agentDid.uri});if(typeof i>"u")this._resolving.delete(e),this.cache.nextTick(()=>this.cache.del(e));else try{let s=yield this.agent.did.resolve(e);if(!s.didResolutionMetadata.error&&s.didDocument){let o=Object.assign(Object.assign({},i),{document:s.didDocument,metadata:s.didDocumentMetadata});try{yield this.agent.did.update({portableDid:o,tenant:this.agent.agentDid.uri,publish:!1})}catch(a){a.message&&!a.message.includes("No changes detected, update aborted")&&ki.error(`Error updating DID: ${a.message}`)}}}finally{this._resolving.delete(e)}}return n.value}catch(t){if(t.notFound)return;throw t}})}};g();var ph=class{constructor(e){this.agent=e.agent,this.did=e.did,this.delegateDid=e.delegateDid,this.recoveryPhrase=e.recoveryPhrase,this.identity=e.identity}};g();fn();g();is();fn();var bm=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function ow(r,e){return bm(this,void 0,void 0,function*(){let t=yield e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(k5.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(s=>typeof s=="string")?n:[];if(i.length>0)return i}return[]})}function Is(r){return ye.getAuthor(r)}function rV(r){let e=lt.decodePlainObjectPayload(r.authorization.signature);return e?.protocolRole}function ol(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===xe.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function I0e(r){return ye.getCid(r)}function nV(r,e){return bm(this,void 0,void 0,function*(){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:yield I0e(r),value:t}})}function iV(r,e=3e3,t=3e5,n){let i=Date.now()+t,s=null,o=!0;return new Promise((a,d)=>{n&&n.addEventListener("abort",()=>{o=!1,s!==null&&clearTimeout(s),console.log("Polling aborted by user"),a(null)});function l(){return bm(this,void 0,void 0,function*(){if(!o)return;let c=i-Date.now();if(c<=0){o=!1,console.log("Polling stopped: TTL reached"),a(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(c/1e3)}s)`);try{let u=yield r();if(u.ok){o=!1,s!==null&&clearTimeout(s),console.log("Polling stopped: Success condition met"),a(u);return}}catch(u){console.error("Error fetching data:",u),d(u)}o&&(s=setTimeout(l,e))})}l()})}function v$(r,e,t){return bm(this,void 0,void 0,function*(){if(!Number.isInteger(e)||e<1)throw new Error(`mapConcurrent: concurrency must be a positive integer, got ${e}`);if(r.length===0)return[];let n=new Array(r.length),i=0,s=()=>bm(this,void 0,void 0,function*(){for(;;){let d=i++;if(d>=r.length)return;n[d]=yield t(r[d],d)}}),o=Math.min(e,r.length),a=[];for(let d=0;d<o;d++)a.push(s());return yield Promise.all(a),n})}function iS(r,e,t){return bm(this,void 0,void 0,function*(){return v$(r,e,(n,i)=>bm(this,void 0,void 0,function*(){try{return{status:"fulfilled",value:yield t(n,i)}}catch(s){return{status:"rejected",reason:s}}}))})}var sw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},oS=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}recordsQuery(e,t){return sw(this,void 0,void 0,function*(){let n=yield $a.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}recordsRead(e,t){return sw(this,void 0,void 0,function*(){let n=yield Hd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}recordsSubscribe(e,t,n){return sw(this,void 0,void 0,function*(){let i=yield za.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,i.message,void 0,n)})}recordsCount(e,t){return sw(this,void 0,void 0,function*(){let n=yield Md.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return yield this.sendRequest(e,n.message)})}protocolsQuery(e,t){return sw(this,void 0,void 0,function*(){let n=yield La.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return yield this.sendRequest(e,n.message)})}sendRequest(e,t,n,i){return sw(this,void 0,void 0,function*(){let s=yield ow(e,this._didResolver),o=[];for(let a of s)try{if(i!==void 0){if(!(yield this._rpcClient.getServerInfo(a)).webSocketSupport){o.push({url:a,message:"WebSocket support is not enabled on the server."});continue}let c=new URL(a);c.protocol=c.protocol==="http:"?"ws:":"wss:",a=c.toString()}return yield this._rpcClient.sendDwnRequest({dwnUrl:a,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(d){o.push({url:a,message:d instanceof Error?d.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(o)}`)})}};g();var R0e=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},aw=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}export(){return R0e(this,void 0,void 0,function*(){return{portableDid:yield this.did.export(),metadata:Object.assign({},this.metadata)}})}};g();gn();var as=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},b$={"AES-GCM":{implementation:$y,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Oy,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:xd,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:AP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:RP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:Ac,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:Ac,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:pf,names:["SHA-256"],operations:["digest"]},X25519:{implementation:yf,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},ma=class{constructor(){this._algorithmInstances=new Map}bytesToPrivateKey(e){return as(this,arguments,void 0,function*({algorithm:t,privateKeyBytes:n}){let i=this.getAlgorithmName({algorithm:t});return yield this.getAlgorithm({algorithm:i}).bytesToPrivateKey({algorithm:t,privateKeyBytes:n})})}bytesToPublicKey(e){return as(this,arguments,void 0,function*({algorithm:t,publicKeyBytes:n}){let i=this.getAlgorithmName({algorithm:t});return yield this.getAlgorithm({algorithm:i}).bytesToPublicKey({algorithm:t,publicKeyBytes:n})})}decrypt(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.key});return yield this.getAlgorithm({algorithm:t}).decrypt(e)})}deriveKey(e){return as(this,void 0,void 0,function*(){var t,n;let i=this.getAlgorithmName({algorithm:e.algorithm}),s=this.getAlgorithm({algorithm:i}),o;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{o=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{o=e.algorithm.split(/[-+]/)[2];break}default:throw new ze(Ke.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+((n=(t=o.match(/\d+/))===null||t===void 0?void 0:t[0])!==null&&n!==void 0?n:-1);if(a===-1)throw new ze(Ke.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${o}`);let d=yield s.deriveKeyBytes(Object.assign(Object.assign({},e),{length:a}));return yield this.bytesToPrivateKey({algorithm:o,privateKeyBytes:d})})}deriveKeyBytes(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({algorithm:e.algorithm});return yield this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)})}digest(e){return as(this,arguments,void 0,function*({algorithm:t,data:n}){return yield this.getAlgorithm({algorithm:t}).digest({algorithm:t,data:n})})}encrypt(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.key});return yield this.getAlgorithm({algorithm:t}).encrypt(e)})}generateKey(e){return as(this,void 0,void 0,function*(){var t;let n=this.getAlgorithmName({algorithm:e.algorithm}),s=yield this.getAlgorithm({algorithm:n}).generateKey({algorithm:e.algorithm});return(t=s.kid)!==null&&t!==void 0||(s.kid=yield wt({jwk:s})),s})}getPublicKey(e){return as(this,arguments,void 0,function*({key:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}privateKeyToBytes(e){return as(this,arguments,void 0,function*({privateKey:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).privateKeyToBytes({privateKey:t})})}publicKeyToBytes(e){return as(this,arguments,void 0,function*({publicKey:t}){let n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).publicKeyToBytes({publicKey:t})})}sign(e){return as(this,arguments,void 0,function*({key:t,data:n}){let i=this.getAlgorithmName({key:t});return this.getAlgorithm({algorithm:i}).sign({data:n,key:t})})}unwrapKey(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.decryptionKey});return yield this.getAlgorithm({algorithm:t}).unwrapKey(e)})}verify(e){return as(this,arguments,void 0,function*({key:t,signature:n,data:i}){let s=this.getAlgorithmName({key:t});return this.getAlgorithm({algorithm:s}).verify({key:t,signature:n,data:i})})}wrapKey(e){return as(this,void 0,void 0,function*(){let t=this.getAlgorithmName({key:e.encryptionKey});return yield this.getAlgorithm({algorithm:t}).wrapKey(e)})}getAlgorithm({algorithm:e}){var t;let n=(t=b$[e])===null||t===void 0?void 0:t.implementation;if(!n)throw new ze(Ke.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({algorithm:e,key:t}){var n;let i=(n=t?.alg)!==null&&n!==void 0?n:e,s=t?.crv;for(let o of Object.keys(b$)){let a=b$[o].names;if(i&&a.includes(i))return o;if(s&&a.includes(s))return o}throw new ze(Ke.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${i}, crv=${s}. Please check the documentation for the list of supported algorithms.`)}};g();is();gn();g();He();is();g();var xm={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:{}}},Rs={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"}}}}},u1={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();gn();var cw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},C0e=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},ji="^",sS=class extends Pd{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}addPredefinedKeys(e){return cw(this,arguments,void 0,function*({privateKeys:t}){var n;let i={};for(let s of t){(n=s.kid)!==null&&n!==void 0||(s.kid=yield wt({jwk:s}));let o=yield this.getKeyUri({key:s});i[o]=s}this._predefinedKeys=new Map(Object.entries(i)),this._keyGenerator=this._predefinedKeys.keys()})}exportKey(e){return cw(this,arguments,void 0,function*({keyUri:t}){let n=this._predefinedKeys.get(t);if(!n)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${t}`);return n})}generateKey(e){return cw(this,void 0,void 0,function*(){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t})}getPublicKey(e){return cw(this,arguments,void 0,function*({keyUri:t}){let n=this._predefinedKeys.get(t);if(!n)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${t}`);let{d:i}=n;return C0e(n,["d"])})}sign(e){return cw(this,arguments,void 0,function*({keyUri:t,data:n}){let i=this._predefinedKeys.get(t);if(!i)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${t}`);return yield zn.sign({data:n,key:i})})}};function sl(r){return cw(this,arguments,void 0,function*({agent:e,tenant:t,didUri:n}){if(t)return t;if(e.agentDid)return e.agentDid.uri;if(!n)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return n})}g();var f1=Rn(cS(),1);He();fn();var Cs=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},mh=class{constructor(){this.name="DwnDataStore",this._cache=new Di.default({ttl:(0,f1.default)("15 minutes"),max:100}),this._index=new Di.default({ttl:(0,f1.default)("21 days"),max:1e3}),this._protocolInitializedCache=new Di.default({ttl:(0,f1.default)("1 hour"),max:1e3}),this._tenantEncryptionActive=new Di.default({ttl:(0,f1.default)("1 hour"),max:1e3}),this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}delete(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t}),o=yield this.lookupRecordId({id:t,tenantDid:s,agent:n});if(!o)return!1;let{reply:{status:a}}=yield n.dwn.processRequest({author:s,target:s,messageType:ve.RecordsDelete,messageParams:{recordId:o}});if(a.code===202)return this._index.delete(`${s}${ji}${t}`),this._cache.delete(o),!0;throw new Error(`${this.name}: Failed to delete '${t}' from store: (${a.code}) ${a.detail}`)})}get(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i,useCache:s=!1}){let o=yield sl({agent:n,tenant:i,didUri:t}),a=yield this.lookupRecordId({id:t,tenantDid:o,agent:n});if(a)return yield this.getRecord({recordId:a,tenantDid:o,agent:n,useCache:s})})}list(e){return Cs(this,arguments,void 0,function*({agent:t,tenant:n}){let i=yield sl({tenant:n,agent:t});return yield this.getAllRecords({agent:t,tenantDid:i})})}set(e){return Cs(this,arguments,void 0,function*({id:t,data:n,tenant:i,agent:s,preventDuplicates:o=!0,updateExisting:a=!1,useCache:d=!1}){let l=yield sl({agent:s,tenant:i,didUri:t});yield this.initialize({tenant:l,agent:s});let c=Object.assign({},this._recordProperties);if(a){let m=yield this.getExistingRecordEntry({id:t,tenantDid:l,agent:s});if(!m)throw new Error(`${this.name}: Update failed due to missing entry for: ${t}`);c.recordId=m.recordsWrite.recordId,c.dateCreated=m.recordsWrite.descriptor.dateCreated}else if(o&&(yield this.lookupRecordId({id:t,tenantDid:l,agent:s})))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${t}`);let u=ae.object(n).toUint8Array(),f=this.isEncryptionActive(l),{message:h,reply:{status:p}}=yield s.dwn.processRequest(Object.assign({author:l,target:l,messageType:ve.RecordsWrite,messageParams:Object.assign(Object.assign({},this._recordProperties),c),dataStream:new Blob([u],{type:"application/json"})},f?{encryption:!0}:{}));if(!(h&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${t}: ${p.detail}`);this._index.set(`${l}${ji}${t}`,h.recordId),d&&this._cache.set(h.recordId,n)})}initialize(e){return Cs(this,arguments,void 0,function*({tenant:t,agent:n}){var i,s,o;let a=yield sl({agent:n,tenant:t});if(this._protocolInitializedCache.has(a)&&(!this.encryptionRequired||this._tenantEncryptionActive.has(a)))return;let{reply:{status:d,entries:l}}=yield n.dwn.processRequest({author:a,target:a,messageType:ve.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(d.code!==200)throw new Error(`Failed to query for protocols: ${d.code} - ${d.detail}`);let c=!1;if(l?.length===0)c=(yield this.installProtocol(a,n)).encryptionActive;else if(this.encryptionRequired){let u=(i=l[0].descriptor)===null||i===void 0?void 0:i.definition,f=Object.keys((s=u?.structure)!==null&&s!==void 0?s:{})[0];c=!!(f&&(!((o=u?.structure[f])===null||o===void 0)&&o.$encryption))}this._tenantEncryptionActive.set(a,c),this._protocolInitializedCache.set(a,!0)})}get encryptionRequired(){return this._encryptionRequired===void 0&&(this._encryptionRequired=Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)),this._encryptionRequired}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}getAllRecords(e){return Cs(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")})}getRecord(e){return Cs(this,arguments,void 0,function*({recordId:t,tenantDid:n,agent:i,useCache:s}){var o;if(s){let c=this._cache.get(t);if(c)return c}let a=this.encryptionRequired||this.isEncryptionActive(n),{reply:d}=yield i.dwn.processRequest(Object.assign({author:n,target:n,messageType:ve.RecordsRead,messageParams:{filter:{recordId:t}}},a?{encryption:!0}:{}));if(!(!((o=d.entry)===null||o===void 0)&&o.data))throw new Error(`${this.name}: Failed to read data from DWN for: ${t}`);let l=yield bo.consumeToJson({readableStream:d.entry.data});return s&&this._cache.set(t,l),l})}installProtocol(e,t){return Cs(this,void 0,void 0,function*(){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let o=yield t.dwn.getEncryptionKeyDeriver(e);n=yield Gd.deriveAndInjectPublicEncryptionKeys(n,o),i=!0}let{reply:{status:s}}=yield t.dwn.processRequest({author:e,target:e,messageType:ve.ProtocolsConfigure,messageParams:{definition:n}});if(s.code!==202)throw new Error(`Failed to install protocol: ${s.code} - ${s.detail}`);return i&&(yield t.dwn.ensureKeyDeliveryProtocol(e)),{encryptionActive:i}})}lookupRecordId(e){return Cs(this,arguments,void 0,function*({id:t,tenantDid:n,agent:i}){let s=this._index.get(`${n}${ji}${t}`,{updateAgeOnGet:!0});return s||(yield this.getAllRecords({agent:i,tenantDid:n}),s=this._index.get(`${n}${ji}${t}`)),s})}getExistingRecordEntry(e){return Cs(this,arguments,void 0,function*({id:t,tenantDid:n,agent:i}){let s=yield this.lookupRecordId({id:t,tenantDid:n,agent:i});if(s){let{reply:o}=yield i.dwn.processRequest({author:n,target:n,messageType:ve.RecordsRead,messageParams:{filter:{recordId:s}}});return o.entry}})}},yh=class{constructor(){this.name="InMemoryDataStore",this.store=new Map}delete(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t});return this.store.has(`${s}${ji}${t}`)?(this.store.delete(`${s}${ji}${t}`),!0):!1})}get(e){return Cs(this,arguments,void 0,function*({id:t,agent:n,tenant:i}){let s=yield sl({agent:n,tenant:i,didUri:t});return this.store.get(`${s}${ji}${t}`)})}list(e){return Cs(this,arguments,void 0,function*({agent:t,tenant:n}){let i=yield sl({tenant:n,agent:t}),s=[];for(let[o,a]of this.store.entries())o.startsWith(`${i}${ji}`)&&s.push(a);return s})}set(e){return Cs(this,arguments,void 0,function*({id:t,data:n,tenant:i,agent:s,preventDuplicates:o,updateExisting:a}){let d=yield sl({agent:s,tenant:i,didUri:t});if(a){if(!this.store.has(`${d}${ji}${t}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${t}`)}else if(o&&this.store.has(`${d}${ji}${t}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${t}`);let l=structuredClone(n);this.store.set(`${d}${ji}${t}`,l)})}};var Pu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},h1=class extends mh{constructor(){super(...arguments),this.name="DwnDidStore",this._recordProtocolDefinition=xm,this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}delete(e){let t=Object.create(null,{delete:{get:()=>super.delete}});return Pu(this,void 0,void 0,function*(){return yield t.delete.call(this,e)})}get(e){let t=Object.create(null,{get:{get:()=>super.get}});return Pu(this,void 0,void 0,function*(){return yield t.get.call(this,e)})}list(e){let t=Object.create(null,{list:{get:()=>super.list}});return Pu(this,void 0,void 0,function*(){return yield t.list.call(this,e)})}set(e){let t=Object.create(null,{set:{get:()=>super.set}});return Pu(this,void 0,void 0,function*(){return yield t.set.call(this,e)})}getAllRecords(e){return Pu(this,arguments,void 0,function*({agent:t,tenantDid:n}){var i;this._index.clear();let{reply:s}=yield t.dwn.processRequest({author:n,target:n,messageType:ve.RecordsQuery,messageParams:{filter:Object.assign({},this._recordProperties)}}),o=[];for(let a of(i=s.entries)!==null&&i!==void 0?i:[]){if(!a.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let d=ae.base64Url(a.encodedData).toObject();if(Zg(d)){let l=`${n}${ji}${d.uri}`;this._index.set(l,a.recordId),this._cache.set(a.recordId,d),o.push(d)}}return o})}},p1=class extends yh{constructor(){super(...arguments),this.name="InMemoryDidStore"}delete(e){let t=Object.create(null,{delete:{get:()=>super.delete}});return Pu(this,void 0,void 0,function*(){return yield t.delete.call(this,e)})}get(e){let t=Object.create(null,{get:{get:()=>super.get}});return Pu(this,void 0,void 0,function*(){return yield t.get.call(this,e)})}list(e){let t=Object.create(null,{list:{get:()=>super.list}});return Pu(this,void 0,void 0,function*(){return yield t.list.call(this,e)})}set(e){let t=Object.create(null,{set:{get:()=>super.set}});return Pu(this,void 0,void 0,function*(){return yield t.set.call(this,e)})}};var _u=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},_m;(function(r){r.Create="Create",r.Resolve="Resolve"})(_m||(_m={}));function sV(r,e){return r.messageType===e}var m1=class extends dh{constructor({agent:e,didMethods:t,resolverCache:n,store:i}){if(!t)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:t,cache:n??new vm({agent:e,location:"DATA/AGENT/DID_CACHE"})}),this._didMethods=new Map,this._agent=e,this._store=i??new p1;for(let s of t)this._didMethods.set(s.methodName,s)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,"agent"in this.cache&&(this.cache.agent=e)}create(e){return _u(this,arguments,void 0,function*({method:t,tenant:n,options:i,store:s}){let a=yield this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(yield this.cache.set(a.uri,{didDocument:a.document,didResolutionMetadata:{},didDocumentMetadata:a.metadata}),s??!0){let{uri:d,document:l,metadata:c}=a,u={uri:d,document:l,metadata:c};yield this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return a})}export(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n}){let i=yield this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return yield i.export()})}get(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n}){let i=yield this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?yield Ro.import({portableDid:i,keyManager:this.agent.keyManager}):void 0})}getSigningMethod(e){return _u(this,arguments,void 0,function*({didUri:t,methodId:n}){let i=Qn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let s=this.getMethod(i.method),{didDocument:o,didResolutionMetadata:a}=yield this.resolve(t);if(!o)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(a)}`);return yield s.getSigningMethod({didDocument:o,methodId:n})})}update(e){return _u(this,arguments,void 0,function*({tenant:t,portableDid:n,publish:i=!0}){let s=yield this.get({didUri:n.uri,tenant:t??n.uri});if(!s)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(G0(n.document)===G0(s.document))throw new Error("AgentDidApi: No changes detected, update aborted");let o=yield Ro.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:a,document:d,metadata:l}=o,c={uri:a,document:d,metadata:l};if(yield this.cache.set(a,{didDocument:d,didResolutionMetadata:{},didDocumentMetadata:l}),yield this._store.set({id:a,data:c,agent:this.agent,tenant:t??a,updateExisting:!0,useCache:!0}),i){let u=Qn.parse(a);u?.method==="dht"&&(yield fa.publish({did:o}))}return o})}import(e){return _u(this,arguments,void 0,function*({portableDid:t,tenant:n}){let i=yield Ro.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:s,document:o,metadata:a}=i,d={uri:s,document:o,metadata:a};return yield this.cache.set(s,{didDocument:o,didResolutionMetadata:{},didDocumentMetadata:a}),yield this._store.set({id:d.uri,data:d,agent:this.agent,tenant:n??d.uri,preventDuplicates:!0,useCache:!0}),i})}delete(e){return _u(this,arguments,void 0,function*({didUri:t,tenant:n,deleteKey:i=!0}){let s=yield this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!s)throw new Error("AgentDidApi: Could not delete, DID not found");yield this.cache.delete(t),yield this._store.delete({id:t,agent:this.agent,tenant:n}),i&&(yield this.deleteKeys({portableDid:s}))})}deleteKeys(e){return _u(this,arguments,void 0,function*({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=yield this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});yield this.agent.keyManager.deleteKey({keyUri:i})}})}processRequest(e){return _u(this,void 0,void 0,function*(){var t;if(sV(e,_m.Create))try{let n=yield this.create(Object.assign({},e.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:(t=n.message)!==null&&t!==void 0?t:"Unknown error occurred"}}}if(sV(e,_m.Resolve)){let{didUri:n,options:i}=e.messageParams;return{result:yield this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${e.messageType}`)})}getMethod(e){let t=this._didMethods.get(e);if(t===void 0)throw new Error(`DID Method not supported: ${e}`);return t}};g();fn();He();gn();is();g();fn();He();var al=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},aV=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},Pn=class r{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Di.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return al(this,arguments,void 0,function*({connectedDid:t,delegateDid:n,delegate:i,messageType:s,protocol:o,cached:a=!1}){let d=[t,n,s,o].join("~"),l=a?this._cachedPermissions.get(d):void 0;if(l)return l;let c=yield this.fetchGrants({author:n,target:n,grantor:t,grantee:n}),u=yield r.matchGrantFromArray(t,n,{messageType:s,protocol:o},c,i);if(!u)throw new Error(`CachedPermissions: No permissions found for ${s}: ${o}`);return this._cachedPermissions.set(d,u),u})}fetchGrants(e){return al(this,arguments,void 0,function*({author:t,target:n,grantee:i,grantor:s,protocol:o,remote:a=!1,checkRevoked:d=!0}){let l=o?{protocol:o}:void 0,c={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{author:s,recipient:i,protocol:Qe.uri,protocolPath:Qe.grantPath,tags:l}}},{reply:u}=a?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(u.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${u.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:t,target:n,grantor:s,remote:a,tags:l}):new Set,h=[];for(let p of u.entries){if(f.has(p.recordId))continue;let m=Ht.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return al(this,arguments,void 0,function*({author:t,target:n,grantor:i,remote:s,tags:o}){let a={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{author:i,protocol:Qe.uri,protocolPath:Qe.revocationPath,tags:o}}},{reply:d}=s?yield this.agent.sendDwnRequest(a):yield this.agent.processDwnRequest(a);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let l=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&l.add(c.descriptor.parentId);return l})}fetchRequests(e){return al(this,arguments,void 0,function*({author:t,target:n,protocol:i,remote:s=!1}){let o=i?{protocol:i}:void 0,a={author:t,target:n,messageType:ve.RecordsQuery,messageParams:{filter:{protocol:Qe.uri,protocolPath:Qe.requestPath,tags:o}}},{reply:d}=s?yield this.agent.sendDwnRequest(a):yield this.agent.processDwnRequest(a);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let l=[];for(let c of d.entries){let u=Oa.parse(c);l.push({request:u,message:c})}return l})}isGrantRevoked(e){return al(this,arguments,void 0,function*({author:t,target:n,grantRecordId:i,remote:s=!1}){let o={author:t,target:n,messageType:ve.RecordsRead,messageParams:{filter:{parentId:i,protocol:Qe.uri,protocolPath:Qe.revocationPath}}},{reply:a}=s?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(a.status.code===404)return!1;if(a.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${a.status.detail}`)})}createGrant(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,delegated:i=!1}=e,s=aV(e,["author","store","delegated"]),o;Qe.hasProtocolScope(s.scope)&&(o={protocol:s.scope.protocol});let a={dateExpires:s.dateExpires,requestId:s.requestId,description:s.description,delegated:i,scope:s.scope};s.delegateKeyDelivery&&(a.delegateKeyDelivery=s.delegateKeyDelivery);let d=ae.object(a).toUint8Array(),l={recipient:s.grantedTo,protocol:Qe.uri,protocolPath:Qe.grantPath,dataFormat:"application/json",tags:o},{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(d).toBase64Url()});return{grant:Ht.parse(f),message:f}})}createRequest(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,delegated:i=!1}=e,s=aV(e,["author","store","delegated"]),o;Qe.hasProtocolScope(s.scope)&&(o={protocol:s.scope.protocol});let a={description:s.description,delegated:i,scope:s.scope},d=ae.object(a).toUint8Array(),l={protocol:Qe.uri,protocolPath:Qe.requestPath,dataFormat:"application/json",tags:o},{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(d).toBase64Url()});return{request:Oa.parse(f),message:f}})}createRevocation(e){return al(this,void 0,void 0,function*(){let{author:t,store:n=!1,grant:i,description:s}=e,o={description:s},a=ae.object(o).toUint8Array(),d;Qe.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:Qe.uri,protocolPath:Qe.revocationPath,dataFormat:"application/json",tags:d};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:c,message:u}=yield this.agent.processDwnRequest({store:n,author:t,target:t,messageType:ve.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([a])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},u),{encodedData:ae.uint8Array(a).toBase64Url()})}})}clear(){return al(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,t,n,i){return al(this,arguments,void 0,function*(s,o,a,d,l=!1){let c;for(let u of d){let{grant:f,message:h}=u;if(l===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:y,contextId:v}=a;if(this.matchScopeFromGrant(s,o,p,f,m,y,v)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,t,n,i,s,o,a){if(i.grantee!==t||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(d.interface==="Messages"?d.method==="Read"&&(n===ve.MessagesRead||n===ve.MessagesSync||n===ve.MessagesSubscribe):l===n)if(x$(n)){let u=d;if(u.protocol!==s)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===o||u.contextId!==void 0&&a?.startsWith(u.contextId))return!0}else{let u=d;return u.protocol===void 0?!0:u.protocol!==s?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var dS=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},P$="@enbox/dwn-server";function fw(r){return r.endsWith("/")?r.slice(0,-1):r}var Em=class{constructor(e,t=1e4,n){this._rpcClient=e,this._cacheTtlMs=t,this._discoveryFile=n,this._cacheExpiry=0}getEndpoint(){return dS(this,void 0,void 0,function*(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=yield this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)})}setCachedEndpoint(e){return dS(this,void 0,void 0,function*(){let t=fw(e),n=yield this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n})}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}_tryDiscoveryFile(){return dS(this,void 0,void 0,function*(){if(this._discoveryFile)try{let e=yield this._discoveryFile.read();return e&&(yield this._validateEndpoint(e.endpoint))?e.endpoint:void 0}catch{return}})}_validateEndpoint(e){return dS(this,void 0,void 0,function*(){try{return(yield this._rpcClient.getServerInfo(e)).server===P$}catch{return!1}})}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};var hw=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function M0e(){try{let r=XS,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{readFile(i){return hw(this,void 0,void 0,function*(){try{return yield e.readFile(i,"utf-8")}catch{return null}})},writeFile(i,s){return hw(this,void 0,void 0,function*(){yield e.mkdir(t.dirname(i),{recursive:!0}),yield e.writeFile(i,s,{encoding:"utf-8",mode:384})})},removeFile(i){return hw(this,void 0,void 0,function*(){try{yield e.unlink(i)}catch{}})},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var U0e=".enbox",K0e="dwn.json",lS=class{constructor(e,t){let n=e??M0e();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 s=XS("node:path");this._filePath=s.join(n.homedir(),U0e,K0e)}}get path(){return this._filePath}read(){return hw(this,void 0,void 0,function*(){let e=yield this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{yield this._fs.removeFile(this._filePath);return}if(!L0e(t)){yield this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){yield this._fs.removeFile(this._filePath);return}let n={endpoint:fw(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n})}write(e){return hw(this,void 0,void 0,function*(){let t={endpoint:fw(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);yield this._fs.writeFile(this._filePath,n)})}remove(){return hw(this,void 0,void 0,function*(){yield this._fs.removeFile(this._filePath)})}};function L0e(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();fn();function nc(r,e){return r.messageType===e}function _$(r,e){return e.descriptor.interface+e.descriptor.method===r}function x$(r){return r===ve.RecordsDelete||r===ve.RecordsQuery||r===ve.RecordsRead||r===ve.RecordsSubscribe||r===ve.RecordsWrite}function Sm(r){return r.interface===xe.Records}g();fn();gn();var Vc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function uS(r){return r===pi.XC20P?24:12}function Tm(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}function fS(r,e,t){return Vc(this,arguments,void 0,function*(n,i,s,o=pi.A256GCM){let{ciphertextStream:a,tag:d}=yield Ai.aeadEncryptStream(o,i,s,Et.fromBytes(n)),l=yield Et.toBytes(a),c=Et.fromBytes(l),u=yield pr.computeDagPbCidFromStream(c);return{encryptedBytes:l,dataCid:u,dataSize:l.length,authenticationTag:d}})}function ic(r,e){return Vc(this,void 0,void 0,function*(){var t;let{didDocument:n,didResolutionMetadata:i}=yield r.did.resolve(e);if(!n)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(i)}`);let s=n.keyAgreement;if(!s||s.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 o=s[0],a;if(typeof o=="string"){let c=o.includes("#")?o.split("#").pop():o;a=(t=n.verificationMethod)===null||t===void 0?void 0:t.find(u=>u.id.endsWith(`#${c}`))}else a=o;if(!a?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let d=a.publicKeyJwk;if(d.crv==="Ed25519")d=yield zn.convertPublicKeyToX25519({publicKey:d});else if(d.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${d.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let l=yield r.keyManager.getKeyUri({key:d});return{keyId:a.id,keyUri:l,publicKeyJwk:d}})}function dV(r,e,t,n,i){return Vc(this,void 0,void 0,function*(){let{keyId:s,keyUri:o}=yield ic(r,e),a=ke.constructKeyDerivationPathUsingProtocolContextScheme(t),d=yield r.keyManager.derivePublicKey({keyUri:o,derivationPath:a});return{encryptionInput:Tm(n,i,s,d,St.ProtocolContext),keyId:s,keyUri:o,contextDerivationPath:a}})}function lV(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:(s,o)=>Vc(this,void 0,void 0,function*(){return i.jweKeyUnwrap({keyUri:t,derivationPath:s,encryptedKey:o.encryptedKey,ephemeralPublicKey:o.ephemeralPublicKey})})}}function g1(r,e){return Vc(this,void 0,void 0,function*(){let{keyId:t,keyUri:n}=yield ic(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:St.ProtocolPath,derivePublicKey:s=>Vc(this,void 0,void 0,function*(){return i.derivePublicKey({keyUri:n,derivationPath:s})})}})}function E$(r,e){return Vc(this,void 0,void 0,function*(){let{keyId:t,keyUri:n}=yield ic(r,e);return lV(r,t,n,St.ProtocolPath)})}function y1(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:(e,t)=>Vc(this,void 0,void 0,function*(){let n=yield ke.derivePrivateKey(r,e),i=yield kt.bytesToPrivateKey({privateKeyBytes:n});return Ai.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)})}}function q0e(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:(e,t)=>Vc(this,void 0,void 0,function*(){var n;let i=(n=r.derivationPath)!==null&&n!==void 0?n:[];if(i.length!==e.length||!i.every((a,d)=>a===e[d]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${i.join(", ")}], record path: [${e.join(", ")}].`);let s=yield ke.derivePrivateKey(r,e),o=yield kt.bytesToPrivateKey({privateKeyBytes:s});return Ai.ecdhEsUnwrapKey(o,t.ephemeralPublicKey,t.encryptedKey)})}}function cV(r,e,t,n,i,s,o,a,d){return Vc(this,void 0,void 0,function*(){let{encryption:l}=t;if(!l?.recipients.some(b=>b.header.derivationScheme===St.ProtocolContext)||!t.contextId){if(o&&a){let b=t.descriptor.protocol,T=t.descriptor.protocolPath;if(b){let D=`ddk~${a}`,I=o.get(D);if(I){let M=I.filter(z=>z.protocol===b);if(T){let z=M.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===T);if(z)return q0e(z.derivedPrivateKey)}let C=M.find(z=>z.scope.kind==="protocol");if(C)return y1(C.derivedPrivateKey)}}}return E$(r,e)}let u=l.recipients.find(b=>b.header.derivationScheme===St.ProtocolContext),f=t.contextId.split("/")[0];if(d&&a){let b=t.descriptor.protocol;if(b){let T=`dctx~${a}~${b}~${f}`,D=d.get(T);if(D)return y1(D);try{let I=yield s({ownerDid:e,requesterDid:a,sourceProtocol:b,sourceContextId:f});if(I)return d.set(T,I),y1(I)}catch{}}throw new Error(`AgentDwnApi: Delegate '${a}' 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:h,keyUri:p}=yield ic(r,e);if(u.header.kid===h)return lV(r,h,p,St.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return y1(y);let v=t.descriptor.protocol,w=yield s({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:b}=yield Promise.resolve().then(()=>(fn(),YH)),T=n??b.getSignerDid(t.authorization.signature.signatures[0]);w=yield s({ownerDid:T,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),y1(w)})}function uV(r,e,t,n,i,s,o){return Vc(this,void 0,void 0,function*(){var a,d,l;if(!("encryption"in r)||!r.encryption)return;let c=r,u=c.granteeDid;if(nc(c,ve.RecordsRead)){let f=e;if(f.status.code===200&&(!((d=(a=f.entry)===null||a===void 0?void 0:a.recordsWrite)===null||d===void 0)&&d.encryption)&&(!((l=f.entry)===null||l===void 0)&&l.data)){let h=yield cV(t,c.author,f.entry.recordsWrite,c.target,n,i,s,u,o);try{f.entry.data=yield ke.decrypt(f.entry.recordsWrite,h,f.entry.data)}catch(p){throw new Error(`AgentDwnApi: Failed to decrypt record '${f.entry.recordsWrite.recordId}'. Original error: ${p.message}`)}}}if(nc(c,ve.RecordsQuery)){let f=e;if(f.status.code===200&&f.entries){for(let h of f.entries)if(h.encryption&&h.encodedData){let p=yield cV(t,c.author,h,c.target,n,i,s,u,o);try{let m=Ie.base64UrlToBytes(h.encodedData),y=Et.fromBytes(m),v=yield ke.decrypt(h,p,y),w=yield Et.toBytes(v);h.encodedData=Ie.bytesToBase64Url(w)}catch(m){throw new Error(`AgentDwnApi: Failed to decrypt record '${h.recordId}'. Original error: ${m.message}`)}}}}})}g();fn();var w1=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function fV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){if(i.get(e))return;let o=Rs.protocol;if(!(yield n(e,o))){let d=yield g1(r,e),l=yield Gd.deriveAndInjectPublicEncryptionKeys(Rs,d),{reply:{status:c}}=yield t({author:e,target:e,messageType:ve.ProtocolsConfigure,messageParams:{definition:l}});if(c.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${c.code} - ${c.detail}`);s.delete(`${e}~${o}`)}i.set(e,!0)})}function hV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){let{tenantDid:o,recipientDid:a,contextKeyData:d,sourceProtocol:l,sourceContextId:c,recipientKeyDeliveryPublicKey:u}=e;yield n(o);let f=Rs.protocol,h=new TextEncoder().encode(JSON.stringify(d)),p={protocol:f,protocolPath:"contextKey",dataFormat:"application/json",recipient:a,tags:{protocol:l,contextId:c}},m,y;if(u){let v=pi.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),b=crypto.getRandomValues(new Uint8Array(uS(v))),{encryptedBytes:T,dataCid:D,dataSize:I,authenticationTag:M}=yield fS(h,w,b,v),C=Object.assign(Object.assign({},Tm(w,b,u.rootKeyId,u.publicKeyJwk,St.ProtocolPath)),{authenticationTag:M});({message:m,reply:{status:y}}=yield t({author:o,target:o,messageType:ve.RecordsWrite,messageParams:Object.assign(Object.assign({},p),{dataCid:D,dataSize:I,encryptionInput:C}),dataStream:new Blob([T])}))}else({message:m,reply:{status:y}}=yield t({author:o,target:o,messageType:ve.RecordsWrite,messageParams:p,dataStream:new Blob([h],{type:"application/json"}),encryption:!0}));if(!(m&&y.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${a}: ${y.code} - ${y.detail}`);return s(i(o,m).catch(v=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${m.recordId}' to remote DWN failed: ${v.message}. Sync will deliver it later.`)})),m.recordId})}function pV(r,e,t,n,i,s){return w1(this,void 0,void 0,function*(){let o;try{o=yield s(e)}catch{return}if(o.length===0)return;let{data:a}=yield n({author:e,messageType:ve.RecordsWrite,messageCid:yield ye.getCid(t)});yield i({targetDid:e,dwnEndpointUrls:o,message:t,data:a})})}function z0e(r,e,t,n,i){return w1(this,void 0,void 0,function*(){var s,o;try{let{reply:a}=yield r({author:e,target:t,messageType:ve.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!(!((s=a.entries)===null||s===void 0)&&s.length))return;let d=a.entries[0].recordId,{reply:l}=yield r({author:e,target:t,messageType:ve.RecordsRead,messageParams:{filter:{recordId:d}},encryption:!0}),c=l;return!((o=c.entry)===null||o===void 0)&&o.data?i(yield Et.toBytes(c.entry.data)):void 0}catch{return}})}function mV(r,e,t){return w1(this,void 0,void 0,function*(){var n,i;let{ownerDid:s,requesterDid:o,sourceProtocol:a,sourceContextId:d}=e,l=Rs.protocol,c=s===o,u={protocol:l,protocolPath:"contextKey",recipient:o,tags:{protocol:a,contextId:d}},f=h=>JSON.parse(new TextDecoder().decode(h));if(c){let{reply:h}=yield t({author:o,target:s,messageType:ve.RecordsQuery,messageParams:{filter:u}});if(h.status.code!==200||!(!((n=h.entries)===null||n===void 0)&&n.length))return;let p=h.entries[0].recordId,{reply:m}=yield t({author:o,target:s,messageType:ve.RecordsRead,messageParams:{filter:{recordId:p}},encryption:!0}),y=m;return!((i=y.entry)===null||i===void 0)&&i.data?f(yield Et.toBytes(y.entry.data)):void 0}return z0e(t,o,s,u,f)})}g();fn();var S$=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})};function yV(r,e,t,n,i,s,o){return S$(this,void 0,void 0,function*(){var a;let d=`${r}~${e}`,l=i.get(d);if(l)return l;let u=yield n(s??r),f=yield gm[ve.ProtocolsQuery].create(Object.assign({filter:{protocol:e},signer:u},o?{permissionGrantId:o}:{})),h=yield t.processMessage(r,f.message);if(h.status.code!==200||!(!((a=h.entries)===null||a===void 0)&&a.length))return;let p=h.entries[0].descriptor.definition;return i.set(d,p),p})}function gV(r,e,t,n,i){return S$(this,void 0,void 0,function*(){var s;let o=`remote~${r}~${e}`,a=i.get(o);if(a)return a;let d=yield gm[ve.ProtocolsQuery].create({filter:{protocol:e}}),l=yield n({targetDid:r,dwnEndpointUrls:yield t(r),message:d.message});if(l.status.code!==200||!(!((s=l.entries)===null||s===void 0)&&s.length))throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let c=l.entries[0].descriptor.definition;return i.set(o,c),c})}function wV(r,e,t,n,i,s,o){return S$(this,void 0,void 0,function*(){var a,d;let l=yield s(n),c=yield gm[ve.RecordsQuery].create({signer:l,filter:{protocol:e,contextId:t}}),u=yield i(r),f=yield o({targetDid:r,dwnEndpointUrls:u,message:c.message});if(!(f.status.code!==200||!(!((a=f.entries)===null||a===void 0)&&a.length))){for(let h of f.entries)if(!((d=h.encryption)===null||d===void 0)&&d.recipients){let p=h.encryption.recipients.find(m=>m.header.derivationScheme===St.ProtocolContext&&m.header.derivedPublicKey);if(p?.header.derivedPublicKey)return{rootKeyId:p.header.kid,derivedPublicKey:p.header.derivedPublicKey}}}})}var xr=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(n.next(c))}catch(u){o(u)}}function d(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){c.done?s(c.value):i(c.value).then(a,d)}l((n=n.apply(r,e||[])).next())})},Dm=class r{constructor(e){this._protocolDefinitionCache=new Di.default({ttl:30*60*1e3}),this._contextKeyCache=new Di.default({ttl:30*60*1e3}),this._contextDerivedKeyCache=new Di.default({ttl:30*60*1e3}),this._delegateDecryptionKeyCache=new Di.default({ttl:24*60*60*1e3}),this._delegateContextKeyCache=new Di.default({ttl:24*60*60*1e3}),this._delegateContextKeyCacheIndex=new Map,this._delegateMultiPartyProtocols=new Map,this._localManagedDidCache=new Di.default({ttl:30*60*1e3}),this._pendingEagerSends=new Set,this._keyDeliveryProtocolInstalledCache=new Di.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 Em(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 Em(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}setCachedLocalDwnEndpoint(e){return xr(this,void 0,void 0,function*(){var t;return(t=this._localDwnDiscovery)!==null&&t!==void 0||(this._localDwnDiscovery=new Em(this.agent.rpc,1e4,r._tryCreateDiscoveryFile())),this._localDwnDiscovery.setCachedEndpoint(e)})}getDwnEndpointUrlsForTarget(e){return xr(this,void 0,void 0,function*(){if(!(yield this.shouldUseLocalDwnForTarget(e)))return ow(e,this.agent.did);let n=yield 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=yield ow(e,this.agent.did)}catch(o){if(!n)throw o}return n?[...new Set([n,...i])]:i})}getRemoteDwnEndpointUrls(e){return xr(this,void 0,void 0,function*(){return ow(e,this.agent.did)})}getLocalDwnEndpoint(){return xr(this,void 0,void 0,function*(){var e;return this._localDwnEndpoint?this._localDwnEndpoint:((e=this._localDwnDiscovery)!==null&&e!==void 0||(this._localDwnDiscovery=new Em(this.agent.rpc,1e4,r._tryCreateDiscoveryFile())),this._localDwnDiscovery.getEndpoint())})}static _tryCreateDiscoveryFile(){try{return new lS}catch{return}}shouldUseLocalDwnForTarget(e){return xr(this,void 0,void 0,function*(){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=yield 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 s=i.has(e);return s||this._localManagedDidCache.set(e,!1),s})}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 createDwn(e){return xr(this,arguments,void 0,function*({dataPath:t,dataStore:n,didResolver:i,stateIndex:s,eventLog:o,messageStore:a,tenantGate:d,resumableTaskStore:l}){return n??(n=new um({blockstoreLocation:`${t}/DWN_DATASTORE`})),i??(i=new dh({didResolvers:[fa,ns],cache:new DE({location:`${t}/DID_RESOLVERCACHE`})})),s??(s=new ym({location:`${t}/DWN_STATEINDEX`})),a??(a=new hm({blockstoreLocation:`${t}/DWN_MESSAGESTORE`,indexLocation:`${t}/DWN_MESSAGEINDEX`})),l??(l=new pm({location:`${t}/DWN_RESUMABLETASKSTORE`})),o??(o=new mm),yield Qg.create({dataStore:n,didResolver:i,stateIndex:s,eventLog:o,messageStore:a,tenantGate:d,resumableTaskStore:l})})}processRequest(e){return xr(this,void 0,void 0,function*(){let{message:t,dataStream:n}=yield this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,s;if(e.store===!1)s={status:{code:202,detail:"Accepted"}};else if(this._dwn)s=yield this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let o;if(n){let a=yield Et.toBytes(n);o=new Blob([a])}s=yield this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:o,subscriptionHandler:i})}return yield Promise.all([this.postWriteKeyDelivery(e,t,s),this.maybeDecryptReply(e,s)]),{reply:s,message:t,messageCid:yield ye.getCid(t)}})}processRawMessage(e,t,n){return xr(this,void 0,void 0,function*(){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let s=yield Et.toBytes(n.dataStream);i=new Blob([s])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})})}sendRequest(e){return xr(this,void 0,void 0,function*(){let t=yield this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,s,o;if("messageCid"in e)({message:i,data:s}=yield this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=yield this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");s=e.dataStream,o=e.subscriptionHandler}let a;o!==void 0&&!("messageCid"in e)&&(a=l=>xr(this,void 0,void 0,function*(){let c=l===void 0?e.messageParams:Object.assign(Object.assign({},e.messageParams),{cursor:l}),u=Object.assign(Object.assign({},e),{messageParams:c}),{message:f}=yield this.constructDwnMessage({request:u});return f}));let d=yield this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:s,subscriptionHandler:o,resubscribeFactory:a});return yield this.maybeDecryptReply(e,d),n??(n=yield ye.getCid(i)),{reply:d,message:i,messageCid:n}})}postWriteKeyDelivery(e,t,n){return xr(this,void 0,void 0,function*(){var i,s;if(!nc(e,ve.RecordsWrite)||!e.encryption||n.status.code!==202)return;let o=e.messageParams;if(o.protocol!==Rs.protocol)try{let a=yield this.getProtocolDefinition(e.target,o.protocol);if(!a)return;let d=t,l=lt.getSignerDid(d.authorization.signature.signatures[0]),c=l!==e.target,u=!o.parentContextId,f=o.protocolPath.split("/")[0],h=wm(a,f),p=y$({protocolDefinition:a,protocolPath:o.protocolPath,recipient:o.recipient,tenantDid:e.target,authorDid:c?l:void 0}),m=((i=d.contextId)===null||i===void 0?void 0:i.split("/")[0])||d.contextId||d.recordId,y=h&&u&&!c&&this.hasEligibleDelegatesForProtocol(o.protocol),v=h&&u&&!c;if(p.size>0||y||v){let{keyId:w,keyUri:b}=yield ic(this.agent,e.target),T=[St.ProtocolContext,m],D=yield this.agent.keyManager.derivePrivateKeyBytes({keyUri:b,derivationPath:T}),I=yield kt.bytesToPrivateKey({privateKeyBytes:D}),M={rootKeyId:w,derivationScheme:St.ProtocolContext,derivationPath:T,derivedPrivateKey:I};if(p.size>0){let C=(s=d.authorization)===null||s===void 0?void 0:s.authorKeyDeliveryPublicKey;for(let z of p)try{let L=z===l&&C?C:void 0;yield this.writeContextKeyRecord({tenantDid:e.target,recipientDid:z,contextKeyData:M,sourceProtocol:o.protocol,sourceContextId:m,recipientKeyDeliveryPublicKey:L})}catch(L){console.warn(`AgentDwnApi: Key delivery to '${z}' for context '${m}' failed: ${L.message}. The participant may not be able to decrypt records in this context.`)}}y&&this.deliverContextKeyToDelegates(o.protocol,m,M),v&&(yield this.deliverContextKeyToDelegatesViaDwn(e.target,o.protocol,m,M))}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}})}sendDwnRpcRequest(e){return xr(this,arguments,void 0,function*({targetDid:t,dwnEndpointUrls:n,message:i,data:s,subscriptionHandler:o,resubscribeFactory:a}){let d=[];if(i.descriptor.method===me.Subscribe&&o===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let l of n)try{if(o!==void 0){if(!(yield this.agent.rpc.getServerInfo(l)).webSocketSupport){d.push({url:l,message:"WebSocket support is not enabled on the server."});continue}let f=new URL(l);f.protocol=f.protocol==="http:"?"ws:":"wss:",l=f.toString()}return yield this.agent.rpc.sendDwnRequest({dwnUrl:l,targetDid:t,message:i,data:s,subscription:o?{handler:o,resubscribeFactory:a}:void 0})}catch(c){d.push({url:l,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(d)}`)})}constructDwnMessage(e){return xr(this,arguments,void 0,function*({request:t}){var n,i,s;if(t.granteeDid&&!this.hasGrantParams(t.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let o=t.rawMessage,a;if(nc(t,ve.RecordsWrite)){let u=t.messageParams;if(t.dataStream&&!u?.data){let{dataStream:f}=t,h;if(f instanceof Blob){let[p,m]=f.stream().tee();h=p,a=m}else if(f instanceof ReadableStream){let[p,m]=f.tee();h=p,a=m}!o&&u&&(u.dataCid=yield pr.computeDagPbCidFromStream(h),u.dataSize===void 0&&f instanceof Blob&&(u.dataSize=f.size))}}if(nc(t,ve.ProtocolsConfigure)&&t.encryption&&!o){let u=t.messageParams,f=yield g1(this.agent,t.author);u.definition=yield Gd.deriveAndInjectPublicEncryptionKeys(u.definition,f),this._protocolDefinitionCache.delete(`${t.target}~${u.definition.protocol}`)}if(nc(t,ve.ProtocolsConfigure)&&!t.encryption&&!o){let u=(n=t.messageParams)===null||n===void 0?void 0:n.definition;u?.protocol&&this._protocolDefinitionCache.set(`${t.target}~${u.protocol}`,u)}let d;if(nc(t,ve.RecordsWrite)&&t.encryption&&!o){let u=t.messageParams;if(u?.protocol&&u.protocolPath){let f=t.target!==t.author,h;if(f?h=yield this.fetchRemoteProtocolDefinition(t.target,u.protocol):h=yield this.getProtocolDefinition(t.target,u.protocol,t.granteeDid),!h)throw new Error(`AgentDwnApi: Protocol '${u.protocol}' is not installed for '${t.target}'. Install the protocol before writing encrypted records.`);let p=u.protocolPath.split("/"),m=h.structure;for(let R of p)m=m[R];if(!m?.$encryption)throw new Error(`AgentDwnApi: Protocol '${u.protocol}' at path '${u.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let y=u.protocolPath.split("/")[0],w=u.protocol===Rs.protocol?!1:wm(h,y),b=!u.parentContextId,T;if(u.data)T=u.data instanceof Uint8Array?u.data:new TextEncoder().encode(String(u.data));else if(t.dataStream instanceof Blob)T=new Uint8Array(yield t.dataStream.arrayBuffer());else if(t.dataStream instanceof ReadableStream)T=yield Et.toBytes(t.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let D=pi.A256GCM,I=crypto.getRandomValues(new Uint8Array(32)),M=crypto.getRandomValues(new Uint8Array(uS(D))),C,z=()=>Tm(I,M,m.$encryption.rootKeyId,m.$encryption.publicKeyJwk,St.ProtocolPath);if(f&&w&&b)C=z();else if(f&&w&&!b){let R=u.parentContextId.split("/")[0]||u.parentContextId,$=yield this.extractDerivedPublicKey(t.target,u.protocol,R,t.author);$?C=Tm(I,M,$.rootKeyId,$.derivedPublicKey,St.ProtocolContext):C=z()}else if(f)C=z();else if(w&&!b){let R=u.parentContextId.split("/")[0]||u.parentContextId,$=this._contextKeyCache.get(R);if(!$){let{keyId:P,keyUri:_}=yield ic(this.agent,t.author),S=ke.constructKeyDerivationPathUsingProtocolContextScheme(R);$={keyId:P,keyUri:_,contextDerivationPath:S},this._contextKeyCache.set(R,$)}let E=yield this.agent.keyManager.derivePublicKey({keyUri:$.keyUri,derivationPath:$.contextDerivationPath});C=Tm(I,M,$.keyId,E,St.ProtocolContext)}else w&&b?C=void 0:C=z();let{encryptedBytes:L,dataCid:B,dataSize:H,authenticationTag:ee}=yield fS(T,I,M,D);if(u.dataCid=B,u.dataSize=H,delete u.data,a=Et.fromBytes(L),t.dataStream=void 0,C?(C.authenticationTag=ee,u.encryptionInput=C):d={dataEncryptionKey:I,dataEncryptionIV:M,encryptedBytes:L,authenticationTag:ee},f&&w){let{keyId:R,keyUri:$}=yield ic(this.agent,t.author),E=[St.ProtocolPath,Rs.protocol,"contextKey"],P=yield this.agent.keyManager.derivePublicKey({keyUri:$,derivationPath:E});u.authorKeyDeliveryPublicKey={rootKeyId:R,publicKeyJwk:P}}}}let l,c=gm[t.messageType];if(o){if(l=yield c.parse(o),ol(l)&&t.signAsOwner){let u=yield this.getSigner(t.author);yield l.signAsOwner(u)}else if(t.granteeDid&&ol(l)&&t.signAsOwnerDelegate){let u=yield this.getSigner(t.granteeDid),f=t.messageParams;yield l.signAsOwnerDelegate(u,f.delegatedGrant)}}else{if(t.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let u=t.granteeDid?yield this.getSigner(t.granteeDid):yield this.getSigner(t.author),f=Object.assign({},t.messageParams);if(t.granteeDid&&f.permissionGrantId&&!f.delegatedGrant&&nc(t,ve.RecordsWrite)){let{reply:h}=yield this.processRequest({author:t.granteeDid,target:t.author,messageType:ve.RecordsRead,messageParams:{filter:{recordId:f.permissionGrantId}}});if(h.status.code===200&&(!((i=h.entry)===null||i===void 0)&&i.recordsWrite)&&(!((s=h.entry)===null||s===void 0)&&s.data)){let p=yield Et.toBytes(h.entry.data);f.delegatedGrant=Object.assign(Object.assign({},h.entry.recordsWrite),{encodedData:ae.uint8Array(p).toBase64Url()})}}if(l=yield c.create(Object.assign(Object.assign({},f),{signer:u})),d&&nc(t,ve.RecordsWrite)){let h=l,p=h.message.recordId,{encryptionInput:m,keyId:y,keyUri:v,contextDerivationPath:w}=yield dV(this.agent,t.author,p,d.dataEncryptionKey,d.dataEncryptionIV),b=Object.assign(Object.assign({},m),{authenticationTag:d.authenticationTag});yield h.encryptSymmetricEncryptionKey(b),yield h.sign({signer:u}),this._contextKeyCache.set(p,{keyId:y,keyUri:v,contextDerivationPath:w})}}return{message:l.message,dataStream:a}})}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}getSigner(e){return xr(this,void 0,void 0,function*(){if(e===this.agent.agentDid.uri){let t=yield this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:n=>xr(this,void 0,void 0,function*(){return yield t.sign({data:n})})}}else try{let t=yield this.agent.did.get({didUri:e});if(t){let a=yield t.getSigner();return{algorithm:a.algorithm,keyId:a.keyId,sign:d=>xr(this,void 0,void 0,function*(){return yield a.sign({data:d})})}}let n=yield 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=yield this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),s=yield this.agent.keyManager.getPublicKey({keyUri:i}),o=this.agent.keyManager;return{algorithm:Jr.getJoseSignatureAlgorithmFromPublicKey(s),keyId:n.id,sign:a=>xr(this,void 0,void 0,function*(){return yield o.sign({data:a,keyUri:i})})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}})}getEncryptionKeyDeriver(e){return xr(this,void 0,void 0,function*(){return g1(this.agent,e)})}getEncryptionKeyInfo(e){return xr(this,void 0,void 0,function*(){return ic(this.agent,e)})}getKeyDecrypter(e){return xr(this,void 0,void 0,function*(){return E$(this.agent,e)})}detectNewParticipants(e){return y$(e)}getProtocolDefinition(e,t,n){return xr(this,void 0,void 0,function*(){if(!this._dwn)try{return yield this.fetchRemoteProtocolDefinition(e,t)}catch(s){let o=s instanceof Error?s.message:"";if(o.includes("not found")||o.includes("404")||o.includes("No protocol"))return;throw s}let i;if(n)try{let s=new Pn({agent:this.agent}),{grant:o}=yield s.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:ve.ProtocolsQuery});i=o.id}catch{}return yV(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)})}fetchRemoteProtocolDefinition(e,t){return xr(this,void 0,void 0,function*(){return gV(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)})}extractDerivedPublicKey(e,t,n,i){return xr(this,void 0,void 0,function*(){return wV(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))})}maybeDecryptReply(e,t){return xr(this,void 0,void 0,function*(){return uV(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)})}getDwnMessage(e){return xr(this,arguments,void 0,function*({author:t,messageCid:n}){let i=yield this.getSigner(t),s=yield gm[ve.MessagesRead].create({messageCid:n,signer:i}),o;if(this._dwn?o=yield this._dwn.processMessage(t,s.message):o=yield this.sendDwnRpcRequest({targetDid:t,dwnEndpointUrls:[this._localDwnEndpoint],message:s.message}),o.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${o.status.code} - ${o.status.detail}`);let a=o.entry,l={message:a.message};if(ol(a)){let c=a.data;if(c){let u=yield Et.toBytes(c);l.data=new Blob([u],{type:a.message.descriptor.dataFormat})}}return l})}ensureKeyDeliveryProtocol(e){return xr(this,void 0,void 0,function*(){return fV(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 a of i)this._delegateContextKeyCache.delete(a);let s=[];for(let a of t){let d=`dctx~${e}~${a.protocol}~${a.contextId}`;this._delegateContextKeyCache.set(d,a.derivedPrivateKey),s.push(d)}this._delegateContextKeyCacheIndex.set(e,s);let o=new Set(n??[]);for(let a of t)o.add(a.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 s of t){let o=this._delegateContextKeyCache.get(s);if(!o||!s.startsWith(i))continue;let a=s.slice(i.length),d=a.lastIndexOf("~");d!==-1&&n.push({protocol:a.slice(0,d),contextId:a.slice(d+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){var i,s;for(let[o,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let d=`dctx~${o}~${e}~${t}`;if(this._delegateContextKeyCache.get(d))continue;this._delegateContextKeyCache.set(d,n);let l=(i=this._delegateContextKeyCacheIndex.get(o))!==null&&i!==void 0?i:[];l.push(d),this._delegateContextKeyCacheIndex.set(o,l),(s=this._onDelegateContextKeysChanged)===null||s===void 0||s.call(this,o)}}deliverContextKeyToDelegatesViaDwn(e,t,n,i){return xr(this,void 0,void 0,function*(){try{let o=yield new Pn({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),a=new Set(["Read","Query","Subscribe"]),d=Date.now(),l=new Set;for(let c of o){if(!c.grant.delegated||new Date(c.grant.dateExpires).getTime()<=d)continue;let u=c.grant.scope;if(u.interface!=="Records"||!a.has(u.method)||u.protocolPath||u.contextId)continue;let f=c.grant.grantee,h=c.grant.delegateKeyDelivery;if(!h?.rootKeyId||!h?.publicKeyJwk||l.has(f))continue;let p=h.publicKeyJwk;try{yield this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:h.rootKeyId,publicKeyJwk:p}}),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(s){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${s.message}`)}})}trackEagerSend(e){return this._pendingEagerSends.add(e),e.finally(()=>{this._pendingEagerSends.delete(e)}),e}drainPendingEagerSends(){return xr(this,void 0,void 0,function*(){if(this._pendingEagerSends.size===0)return;let e=[...this._pendingEagerSends];yield Promise.allSettled(e)})}writeContextKeyRecord(e){return xr(this,void 0,void 0,function*(){return hV(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this),this.trackEagerSend.bind(this))})}eagerSendContextKeyRecord(e,t){return xr(this,void 0,void 0,function*(){return pV(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))})}fetchContextKeyRecord(e){return xr(this,void 0,void 0,function*(){return mV(this.agent,e,this.processRequest.bind(this))})}};g();function vV(r){try{let e=W0e(r),t=JSON.parse(e);return F0e(t)?t:void 0}catch{return}}function bV(r){let e=r.indexOf("#");if(e===-1)return vV(r);let t=r.slice(e+1);if(t.length!==0)return vV(t)}function F0e(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!G0e(e.endpoint))}function G0e(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 W0e(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 s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return new TextDecoder().decode(i)}g();g();EP();cx();g();px();uc();var H0e=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),PV=Uint8Array.from({length:16},(r,e)=>e),V0e=PV.map(r=>(9*r+5)%16),D$=[PV],k$=[V0e];for(let r=0;r<4;r++)for(let e of[D$,k$])e.push(e[r].map(t=>H0e[t]));var _V=[[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)),J0e=D$.map((r,e)=>r.map(t=>_V[e][t])),Y0e=k$.map((r,e)=>r.map(t=>_V[e][t])),Z0e=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Q0e=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),hS=(r,e)=>r<<e|r>>>32-e;function xV(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 pS=new Uint32Array(16),T$=class extends Ku{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:s}=this;return[e,t,n,i,s]}set(e,t,n,i,s){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(e,t){for(let h=0;h<16;h++,t+=4)pS[h]=e.getUint32(t,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,d=a,l=this.h3|0,c=l,u=this.h4|0,f=u;for(let h=0;h<5;h++){let p=4-h,m=Z0e[h],y=Q0e[h],v=D$[h],w=k$[h],b=J0e[h],T=Y0e[h];for(let D=0;D<16;D++){let I=hS(n+xV(h,s,a,l)+pS[v[D]]+m,b[D])+u|0;n=u,u=l,l=hS(a,10)|0,a=s,s=I}for(let D=0;D<16;D++){let I=hS(i+xV(p,o,d,c)+pS[w[D]]+y,T[D])+f|0;i=f,f=c,c=hS(d,10)|0,d=o,o=I}}this.set(this.h1+a+c|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+o|0,this.h0+s+d|0)}roundClean(){pS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},EV=Qm(()=>new T$);Gw();xP();uc();Ym();var X0e=qw("ed25519 seed"),A$=2147483648,SV=new Uint8Array([0]);function TV(r,...e){return typeof r=="string"&&(r=k8(r)),yl(r,...e),r}var eve=r=>EV(zu(r)),tve=r=>wl(r).getUint32(0,!1),I$=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 wl(e).setUint32(0,r,!1),e},mS=class r{get publicKeyRaw(){return ka.getPublicKey(this.privateKey)}get publicKey(){return Rh(SV,this.publicKeyRaw)}get pubHash(){return eve(this.publicKey)}get fingerprint(){return tve(this.pubHash)}get fingerprintHex(){return AT(I$(this.fingerprint))}get parentFingerprintHex(){return AT(I$(this.parentFingerprint))}static fromMasterSeed(e){if(e=TV(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=Mu(hf,X0e,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(yl(e.privateKey,32),yl(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 s of n){let o=/^(\d+)('?)$/.exec(s);if(!o||o.length!==3)throw new Error(`Invalid child index: ${s}`);let a=+o[1];if(!Number.isSafeInteger(a)||a>=A$)throw new Error("Invalid index");(t||o[2]==="'")&&(a+=A$),i=i.deriveChild(a)}return i}deriveChild(e){if(e<A$)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Rh(SV,this.privateKey,I$(e)),n=Mu(hf,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 ka.sign(e,this.privateKey)}verify(e,t){return t=TV(t,64),ka.verify(t,e,this.publicKeyRaw)}};g();var R$=`abandon
|
|
11
11
|
ability
|
|
12
12
|
able
|
|
13
13
|
about
|