@enbox/dwn-sdk-js 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -7,7 +7,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
7
7
  || ${o} === "boolean" || ${s} === null`).assign(i,(0,It._)`[${s}]`)}}}function bY({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,It._)`${e} !== undefined`,()=>t.assign((0,It._)`${e}[${r}]`,n))}function I_(t,e,r,n=vh.Correct){let s=n===vh.Correct?It.operators.EQ:It.operators.NEQ,a;switch(t){case"null":return(0,It._)`${e} ${s} null`;case"array":a=(0,It._)`Array.isArray(${e})`;break;case"object":a=(0,It._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=o((0,It._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=o();break;default:return(0,It._)`typeof ${e} ${s} ${t}`}return n===vh.Correct?a:(0,It.not)(a);function o(i=It.nil){return(0,It.and)((0,It._)`typeof ${e} == "number"`,i,r?(0,It._)`isFinite(${e})`:It.nil)}}Ys.checkDataType=I_;function A_(t,e,r,n){if(t.length===1)return I_(t[0],e,r,n);let s,a=(0,BO.toHash)(t);if(a.array&&a.object){let o=(0,It._)`typeof ${e} != "object"`;s=a.null?o:(0,It._)`!${e} || ${o}`,delete a.null,delete a.array,delete a.object}else s=It.nil;a.number&&delete a.integer;for(let o in a)s=(0,It.and)(s,I_(o,e,r,n));return s}Ys.checkDataTypes=A_;var PY={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,It._)`{type: ${t}}`:(0,It._)`{type: ${e}}`};function R_(t){let e=xY(t);(0,mY.reportError)(e,PY)}Ys.reportTypeError=R_;function xY(t){let{gen:e,data:r,schema:n}=t,s=(0,BO.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var KO=Ee(Cb=>{"use strict";w();Object.defineProperty(Cb,"__esModule",{value:!0});Cb.assignDefaults=void 0;var bh=_t(),SY=Lt();function EY(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)LO(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,a)=>LO(t,a,s.default))}Cb.assignDefaults=EY;function LO(t,e,r){let{gen:n,compositeRule:s,data:a,opts:o}=t;if(r===void 0)return;let i=(0,bh._)`${a}${(0,bh.getProperty)(e)}`;if(s){(0,SY.checkStrictMode)(t,`default is ignored for: ${i}`);return}let c=(0,bh._)`${i} === undefined`;o.useDefaults==="empty"&&(c=(0,bh._)`${c} || ${i} === null || ${i} === ""`),n.if(c,(0,bh._)`${i} = ${(0,bh.stringify)(r)}`)}});var Oo=Ee(Ar=>{"use strict";w();Object.defineProperty(Ar,"__esModule",{value:!0});Ar.validateUnion=Ar.validateArray=Ar.usePattern=Ar.callValidateCode=Ar.schemaProperties=Ar.allSchemaProperties=Ar.noPropertyInData=Ar.propertyInData=Ar.isOwnProperty=Ar.hasPropFunc=Ar.reportMissingProp=Ar.checkMissingProp=Ar.checkReportMissingProp=void 0;var Vr=_t(),D_=Lt(),Su=Mo(),kY=Lt();function _Y(t,e){let{gen:r,data:n,it:s}=t;r.if(j_(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Vr._)`${e}`},!0),t.error()})}Ar.checkReportMissingProp=_Y;function TY({gen:t,data:e,it:{opts:r}},n,s){return(0,Vr.or)(...n.map(a=>(0,Vr.and)(j_(t,e,a,r.ownProperties),(0,Vr._)`${s} = ${a}`)))}Ar.checkMissingProp=TY;function IY(t,e){t.setParams({missingProperty:e},!0),t.error()}Ar.reportMissingProp=IY;function zO(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Vr._)`Object.prototype.hasOwnProperty`})}Ar.hasPropFunc=zO;function C_(t,e,r){return(0,Vr._)`${zO(t)}.call(${e}, ${r})`}Ar.isOwnProperty=C_;function AY(t,e,r,n){let s=(0,Vr._)`${e}${(0,Vr.getProperty)(r)} !== undefined`;return n?(0,Vr._)`${s} && ${C_(t,e,r)}`:s}Ar.propertyInData=AY;function j_(t,e,r,n){let s=(0,Vr._)`${e}${(0,Vr.getProperty)(r)} === undefined`;return n?(0,Vr.or)(s,(0,Vr.not)(C_(t,e,r))):s}Ar.noPropertyInData=j_;function qO(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ar.allSchemaProperties=qO;function RY(t,e){return qO(e).filter(r=>!(0,D_.alwaysValidSchema)(t,e[r]))}Ar.schemaProperties=RY;function DY({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:a},it:o},i,c,u){let d=u?(0,Vr._)`${t}, ${e}, ${n}${s}`:e,l=[[Su.default.instancePath,(0,Vr.strConcat)(Su.default.instancePath,a)],[Su.default.parentData,o.parentData],[Su.default.parentDataProperty,o.parentDataProperty],[Su.default.rootData,Su.default.rootData]];o.opts.dynamicRef&&l.push([Su.default.dynamicAnchors,Su.default.dynamicAnchors]);let f=(0,Vr._)`${d}, ${r.object(...l)}`;return c!==Vr.nil?(0,Vr._)`${i}.call(${c}, ${f})`:(0,Vr._)`${i}(${f})`}Ar.callValidateCode=DY;var CY=(0,Vr._)`new RegExp`;function jY({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,a=s(r,n);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,Vr._)`${s.code==="new RegExp"?CY:(0,kY.useFunc)(t,s)}(${r}, ${n})`})}Ar.usePattern=jY;function $Y(t){let{gen:e,data:r,keyword:n,it:s}=t,a=e.name("valid");if(s.allErrors){let i=e.let("valid",!0);return o(()=>e.assign(i,!1)),i}return e.var(a,!0),o(()=>e.break()),a;function o(i){let c=e.const("len",(0,Vr._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:D_.Type.Num},a),e.if((0,Vr.not)(a),i)})}}Ar.validateArray=$Y;function MY(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,D_.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let o=e.let("valid",!1),i=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},i);e.assign(o,(0,Vr._)`${o} || ${i}`),t.mergeValidEvaluated(d,i)||e.if((0,Vr.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}Ar.validateUnion=MY});var WO=Ee(lc=>{"use strict";w();Object.defineProperty(lc,"__esModule",{value:!0});lc.validateKeywordUsage=lc.validSchemaType=lc.funcKeywordCode=lc.macroKeywordCode=void 0;var Si=_t(),cf=Mo(),OY=Oo(),BY=Pg();function NY(t,e){let{gen:r,keyword:n,schema:s,parentSchema:a,it:o}=t,i=e.macro.call(o.self,s,a,o),c=GO(r,n,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);let u=r.name("valid");t.subschema({schema:i,schemaPath:Si.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}lc.macroKeywordCode=NY;function UY(t,e){var r;let{gen:n,keyword:s,schema:a,parentSchema:o,$data:i,it:c}=t;KY(c,e);let u=!i&&e.compile?e.compile.call(c.self,a,o,c):e.validate,d=GO(n,s,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&FO(t),y(()=>t.error());else{let S=e.async?h():p();e.modifying&&FO(t),y(()=>LY(t,S))}}function h(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Si._)`await `),v=>n.assign(l,!1).if((0,Si._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Si._)`${v}.errors`),()=>n.throw(v))),S}function p(){let S=(0,Si._)`${d}.errors`;return n.assign(S,null),m(Si.nil),S}function m(S=e.async?(0,Si._)`await `:Si.nil){let v=c.opts.passContext?cf.default.this:cf.default.self,E=!("compile"in e&&!i||e.schema===!1);n.assign(l,(0,Si._)`${S}${(0,OY.callValidateCode)(t,d,v,E)}`,e.modifying)}function y(S){var v;n.if((0,Si.not)((v=e.valid)!==null&&v!==void 0?v:l),S)}}lc.funcKeywordCode=UY;function FO(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Si._)`${n.parentData}[${n.parentDataProperty}]`))}function LY(t,e){let{gen:r}=t;r.if((0,Si._)`Array.isArray(${e})`,()=>{r.assign(cf.default.vErrors,(0,Si._)`${cf.default.vErrors} === null ? ${e} : ${cf.default.vErrors}.concat(${e})`).assign(cf.default.errors,(0,Si._)`${cf.default.vErrors}.length`),(0,BY.extendErrors)(t)},()=>t.error())}function KY({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function GO(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Si.stringify)(r)})}function zY(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}lc.validSchemaType=zY;function qY({schema:t,opts:e,self:r,errSchemaPath:n},s,a){if(Array.isArray(s.keyword)?!s.keyword.includes(a):s.keyword!==a)throw new Error("ajv implementation error");let o=s.dependencies;if(o?.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}lc.validateKeywordUsage=qY});var HO=Ee(Eu=>{"use strict";w();Object.defineProperty(Eu,"__esModule",{value:!0});Eu.extendSubschemaMode=Eu.extendSubschemaData=Eu.getSubschema=void 0;var fc=_t(),VO=Lt();function FY(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:a,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let i=t.schema[e];return r===void 0?{schema:i,schemaPath:(0,fc._)`${t.schemaPath}${(0,fc.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,fc._)`${t.schemaPath}${(0,fc.getProperty)(e)}${(0,fc.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,VO.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||a===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Eu.getSubschema=FY;function GY(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:a,propertyName:o}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=i.let("data",(0,fc._)`${e.data}${(0,fc.getProperty)(r)}`,!0);c(f),t.errorPath=(0,fc.str)`${u}${(0,VO.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,fc._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof fc.Name?s:i.let("data",s,!0);c(u),o!==void 0&&(t.propertyName=o)}a&&(t.dataTypes=a);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Eu.extendSubschemaData=GY;function WY(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:a}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),a!==void 0&&(t.allErrors=a),t.jtdDiscriminator=e,t.jtdMetadata=r}Eu.extendSubschemaMode=WY});var $_=Ee((PRe,JO)=>{"use strict";w();JO.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,a;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[s]))return!1;for(s=n;s--!==0;){var o=a[s];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var YO=Ee((SRe,ZO)=>{"use strict";w();var ku=ZO.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};jb(e,n,s,t,"",t)};ku.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ku.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ku.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ku.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 jb(t,e,r,n,s,a,o,i,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,a,o,i,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in ku.arrayKeywords)for(var f=0;f<l.length;f++)jb(t,e,r,l[f],s+"/"+d+"/"+f,a,s,d,n,f)}else if(d in ku.propsKeywords){if(l&&typeof l=="object")for(var h in l)jb(t,e,r,l[h],s+"/"+d+"/"+VY(h),a,s,d,n,h)}else(d in ku.keywords||t.allKeys&&!(d in ku.skipKeywords))&&jb(t,e,r,l,s+"/"+d,a,s,d,n)}r(n,s,a,o,i,c,u)}}function VY(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Sg=Ee(Oi=>{"use strict";w();Object.defineProperty(Oi,"__esModule",{value:!0});Oi.getSchemaRefs=Oi.resolveUrl=Oi.normalizeId=Oi._getFullPath=Oi.getFullPath=Oi.inlineRef=void 0;var HY=Lt(),JY=$_(),ZY=YO(),YY=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function QY(t,e=!0){return typeof t=="boolean"?!0:e===!0?!M_(t):e?QO(t)<=e:!1}Oi.inlineRef=QY;var XY=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function M_(t){for(let e in t){if(XY.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(M_)||typeof r=="object"&&M_(r))return!0}return!1}function QO(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!YY.has(r)&&(typeof t[r]=="object"&&(0,HY.eachItem)(t[r],n=>e+=QO(n)),e===1/0))return 1/0}return e}function XO(t,e="",r){r!==!1&&(e=Ph(e));let n=t.parse(e);return e4(t,n)}Oi.getFullPath=XO;function e4(t,e){return t.serialize(e).split("#")[0]+"#"}Oi._getFullPath=e4;var eQ=/#\/?$/;function Ph(t){return t?t.replace(eQ,""):""}Oi.normalizeId=Ph;function tQ(t,e,r){return r=Ph(r),t.resolve(e,r)}Oi.resolveUrl=tQ;var rQ=/^[a-z_][-a-z0-9._]*$/i;function nQ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Ph(t[r]||e),a={"":s},o=XO(n,s,!1),i={},c=new Set;return ZY(t,{allKeys:!0},(l,f,h,p)=>{if(p===void 0)return;let m=o+f,y=a[p];typeof l[r]=="string"&&(y=S.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),a[f]=y;function S(E){let _=this.opts.uriResolver.resolve;if(E=Ph(y?_(y,E):E),c.has(E))throw d(E);c.add(E);let I=this.refs[E];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?u(l,I.schema,E):E!==Ph(m)&&(E[0]==="#"?(u(l,i[E],E),i[E]=l):this.refs[E]=m),E}function v(E){if(typeof E=="string"){if(!rQ.test(E))throw new Error(`invalid anchor "${E}"`);S.call(this,`#${E}`)}}}),i;function u(l,f,h){if(f!==void 0&&!JY(l,f))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Oi.getSchemaRefs=nQ});var _g=Ee(_u=>{"use strict";w();Object.defineProperty(_u,"__esModule",{value:!0});_u.getData=_u.KeywordCxt=_u.validateFunctionCode=void 0;var i4=$O(),t4=xg(),B_=T_(),$b=xg(),sQ=KO(),kg=WO(),O_=HO(),Ve=_t(),gt=Mo(),iQ=Sg(),ud=Lt(),Eg=Pg();function oQ(t){if(c4(t)&&(d4(t),a4(t))){dQ(t);return}o4(t,()=>(0,i4.topBoolOrEmptySchema)(t))}_u.validateFunctionCode=oQ;function o4({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},a){s.code.es5?t.func(e,(0,Ve._)`${gt.default.data}, ${gt.default.valCxt}`,n.$async,()=>{t.code((0,Ve._)`"use strict"; ${r4(r,s)}`),cQ(t,s),t.code(a)}):t.func(e,(0,Ve._)`${gt.default.data}, ${aQ(s)}`,n.$async,()=>t.code(r4(r,s)).code(a))}function aQ(t){return(0,Ve._)`{${gt.default.instancePath}="", ${gt.default.parentData}, ${gt.default.parentDataProperty}, ${gt.default.rootData}=${gt.default.data}${t.dynamicRef?(0,Ve._)`, ${gt.default.dynamicAnchors}={}`:Ve.nil}}={}`}function cQ(t,e){t.if(gt.default.valCxt,()=>{t.var(gt.default.instancePath,(0,Ve._)`${gt.default.valCxt}.${gt.default.instancePath}`),t.var(gt.default.parentData,(0,Ve._)`${gt.default.valCxt}.${gt.default.parentData}`),t.var(gt.default.parentDataProperty,(0,Ve._)`${gt.default.valCxt}.${gt.default.parentDataProperty}`),t.var(gt.default.rootData,(0,Ve._)`${gt.default.valCxt}.${gt.default.rootData}`),e.dynamicRef&&t.var(gt.default.dynamicAnchors,(0,Ve._)`${gt.default.valCxt}.${gt.default.dynamicAnchors}`)},()=>{t.var(gt.default.instancePath,(0,Ve._)`""`),t.var(gt.default.parentData,(0,Ve._)`undefined`),t.var(gt.default.parentDataProperty,(0,Ve._)`undefined`),t.var(gt.default.rootData,gt.default.data),e.dynamicRef&&t.var(gt.default.dynamicAnchors,(0,Ve._)`{}`)})}function dQ(t){let{schema:e,opts:r,gen:n}=t;o4(t,()=>{r.$comment&&e.$comment&&l4(t),hQ(t),n.let(gt.default.vErrors,null),n.let(gt.default.errors,0),r.unevaluated&&uQ(t),u4(t),gQ(t)})}function uQ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Ve._)`${r}.evaluated`),e.if((0,Ve._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Ve._)`${t.evaluated}.props`,(0,Ve._)`undefined`)),e.if((0,Ve._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Ve._)`${t.evaluated}.items`,(0,Ve._)`undefined`))}function r4(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Ve._)`/*# sourceURL=${r} */`:Ve.nil}function lQ(t,e){if(c4(t)&&(d4(t),a4(t))){fQ(t,e);return}(0,i4.boolOrEmptySchema)(t,e)}function a4({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function c4(t){return typeof t.schema!="boolean"}function fQ(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&l4(t),mQ(t),yQ(t);let a=n.const("_errs",gt.default.errors);u4(t,a),n.var(e,(0,Ve._)`${a} === ${gt.default.errors}`)}function d4(t){(0,ud.checkUnknownRules)(t),pQ(t)}function u4(t,e){if(t.opts.jtd)return n4(t,[],!1,e);let r=(0,t4.getSchemaTypes)(t.schema),n=(0,t4.coerceAndCheckDataType)(t,r);n4(t,r,!n,e)}function pQ(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ud.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function hQ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ud.checkStrictMode)(t,"default is ignored in the schema root")}function mQ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,iQ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function yQ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function l4({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let a=r.$comment;if(s.$comment===!0)t.code((0,Ve._)`${gt.default.self}.logger.log(${a})`);else if(typeof s.$comment=="function"){let o=(0,Ve.str)`${n}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,Ve._)`${gt.default.self}.opts.$comment(${a}, ${o}, ${i}.schema)`)}}function gQ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:a}=t;r.$async?e.if((0,Ve._)`${gt.default.errors} === 0`,()=>e.return(gt.default.data),()=>e.throw((0,Ve._)`new ${s}(${gt.default.vErrors})`)):(e.assign((0,Ve._)`${n}.errors`,gt.default.vErrors),a.unevaluated&&wQ(t),e.return((0,Ve._)`${gt.default.errors} === 0`))}function wQ({gen:t,evaluated:e,props:r,items:n}){r instanceof Ve.Name&&t.assign((0,Ve._)`${e}.props`,r),n instanceof Ve.Name&&t.assign((0,Ve._)`${e}.items`,n)}function n4(t,e,r,n){let{gen:s,schema:a,data:o,allErrors:i,opts:c,self:u}=t,{RULES:d}=u;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,ud.schemaHasRulesButRef)(a,d))){s.block(()=>p4(t,"$ref",d.all.$ref.definition));return}c.jtd||vQ(t,e),s.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,B_.shouldUseGroup)(a,f)&&(f.type?(s.if((0,$b.checkDataType)(f.type,o,c.strictNumbers)),s4(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,$b.reportTypeError)(t)),s.endIf()):s4(t,f),i||s.if((0,Ve._)`${gt.default.errors} === ${n||0}`))}}function s4(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,sQ.assignDefaults)(t,e.type),r.block(()=>{for(let a of e.rules)(0,B_.shouldUseRule)(n,a)&&p4(t,a.keyword,a.definition,e.type)})}function vQ(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(bQ(t,e),t.opts.allowUnionTypes||PQ(t,e),xQ(t,t.dataTypes))}function bQ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{f4(t.dataTypes,r)||N_(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),EQ(t,e)}}function PQ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&N_(t,"use allowUnionTypes to allow union type keyword")}function xQ(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,B_.shouldUseRule)(t.schema,s)){let{type:a}=s.definition;a.length&&!a.some(o=>SQ(e,o))&&N_(t,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function SQ(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function f4(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function EQ(t,e){let r=[];for(let n of t.dataTypes)f4(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function N_(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ud.checkStrictMode)(t,e,t.opts.strictTypes)}var Mb=class{constructor(e,r,n){if((0,kg.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ud.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",h4(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,kg.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",gt.default.errors))}result(e,r,n){this.failResult((0,Ve.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Ve.not)(e),void 0,r)}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:r}=this;this.fail((0,Ve._)`${r} !== undefined && (${(0,Ve.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Eg.reportExtraError:Eg.reportError)(this,this.def.error,r)}$dataError(){(0,Eg.reportError)(this,this.def.$dataError||Eg.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Eg.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Ve.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Ve.nil,r=Ve.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:a,def:o}=this;n.if((0,Ve.or)((0,Ve._)`${s} === undefined`,r)),e!==Ve.nil&&n.assign(e,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Ve.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:a}=this;return(0,Ve.or)(o(),i());function o(){if(n.length){if(!(r instanceof Ve.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Ve._)`${(0,$b.checkDataTypes)(c,r,a.opts.strictNumbers,$b.DataType.Wrong)}`}return Ve.nil}function i(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Ve._)`!${c}(${r})`}return Ve.nil}}subschema(e,r){let n=(0,O_.getSubschema)(this.it,e);(0,O_.extendSubschemaData)(n,this.it,e),(0,O_.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return lQ(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ud.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ud.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,Ve.Name)),!0}};_u.KeywordCxt=Mb;function p4(t,e,r,n){let s=new Mb(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,kg.funcKeywordCode)(s,r):"macro"in r?(0,kg.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,kg.funcKeywordCode)(s,r)}var kQ=/^\/(?:[^~]|~0|~1)*$/,_Q=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function h4(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,a;if(t==="")return gt.default.rootData;if(t[0]==="/"){if(!kQ.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,a=gt.default.rootData}else{let u=_Q.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(a=r[e-d],!s)return a}let o=a,i=s.split("/");for(let u of i)u&&(a=(0,Ve._)`${a}${(0,Ve.getProperty)((0,ud.unescapeJsonPointer)(u))}`,o=(0,Ve._)`${o} && ${a}`);return o;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}_u.getData=h4});var Ob=Ee(L_=>{"use strict";w();Object.defineProperty(L_,"__esModule",{value:!0});var U_=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};L_.default=U_});var Tg=Ee(q_=>{"use strict";w();Object.defineProperty(q_,"__esModule",{value:!0});var K_=Sg(),z_=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,K_.resolveUrl)(e,r,n),this.missingSchema=(0,K_.normalizeId)((0,K_.getFullPath)(e,this.missingRef))}};q_.default=z_});var Ig=Ee(Bo=>{"use strict";w();Object.defineProperty(Bo,"__esModule",{value:!0});Bo.resolveSchema=Bo.getCompilingSchema=Bo.resolveRef=Bo.compileSchema=Bo.SchemaEnv=void 0;var Ea=_t(),TQ=Ob(),df=Mo(),ka=Sg(),m4=Lt(),IQ=_g(),xh=class{constructor(e){var r;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=(r=e.baseId)!==null&&r!==void 0?r:(0,ka.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Bo.SchemaEnv=xh;function G_(t){let e=y4.call(this,t);if(e)return e;let r=(0,ka.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:a}=this.opts,o=new Ea.CodeGen(this.scope,{es5:n,lines:s,ownProperties:a}),i;t.$async&&(i=o.scopeValue("Error",{ref:TQ.default,code:(0,Ea._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");t.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:df.default.data,parentData:df.default.parentData,parentDataProperty:df.default.parentDataProperty,dataNames:[df.default.data],dataPathArr:[Ea.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ea.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ea.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ea._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,IQ.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let l=o.toString();d=`${o.scopeRefs(df.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${df.default.self}`,`${df.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:o._values}),this.opts.unevaluated){let{props:p,items:m}=u;h.evaluated={props:p instanceof Ea.Name?void 0:p,items:m instanceof Ea.Name?void 0:m,dynamicProps:p instanceof Ea.Name,dynamicItems:m instanceof Ea.Name},h.source&&(h.source.evaluated=(0,Ea.stringify)(h.evaluated))}return t.validate=h,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Bo.compileSchema=G_;function AQ(t,e,r){var n;r=(0,ka.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let a=CQ.call(this,t,r);if(a===void 0){let o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:i}=this.opts;o&&(a=new xh({schema:o,schemaId:i,root:t,baseId:e}))}if(a!==void 0)return t.refs[r]=RQ.call(this,a)}Bo.resolveRef=AQ;function RQ(t){return(0,ka.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:G_.call(this,t)}function y4(t){for(let e of this._compilations)if(DQ(e,t))return e}Bo.getCompilingSchema=y4;function DQ(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function CQ(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Bb.call(this,t,e)}function Bb(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ka._getFullPath)(this.opts.uriResolver,r),s=(0,ka.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return F_.call(this,r,t);let a=(0,ka.normalizeId)(n),o=this.refs[a]||this.schemas[a];if(typeof o=="string"){let i=Bb.call(this,t,o);return typeof i?.schema!="object"?void 0:F_.call(this,r,i)}if(typeof o?.schema=="object"){if(o.validate||G_.call(this,o),a===(0,ka.normalizeId)(e)){let{schema:i}=o,{schemaId:c}=this.opts,u=i[c];return u&&(s=(0,ka.resolveUrl)(this.opts.uriResolver,s,u)),new xh({schema:i,schemaId:c,root:t,baseId:s})}return F_.call(this,r,o)}}Bo.resolveSchema=Bb;var jQ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function F_(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let i of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,m4.unescapeFragment)(i)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!jQ.has(i)&&u&&(e=(0,ka.resolveUrl)(this.opts.uriResolver,e,u))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,m4.schemaHasRulesButRef)(r,this.RULES)){let i=(0,ka.resolveUrl)(this.opts.uriResolver,e,r.$ref);a=Bb.call(this,n,i)}let{schemaId:o}=this.opts;if(a=a||new xh({schema:r,schemaId:o,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var g4=Ee((MRe,$Q)=>{$Q.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 V_=Ee((ORe,P4)=>{"use strict";w();var MQ=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),v4=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 W_(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var OQ=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function w4(t){return t.length=0,!0}function BQ(t,e,r){if(t.length){let n=W_(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function NQ(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],a=!1,o=!1,i=BQ;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(a===!0&&(o=!0),!i(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(a=!0),n.push(":");continue}else if(u==="%"){if(!i(s,n,r))break;i=w4}else{s.push(u);continue}}return s.length&&(i===w4?r.zone=s.join(""):o?n.push(s.join("")):n.push(W_(s))),r.address=n.join(""),r}function b4(t){if(UQ(t,":")<2)return{host:t,isIPV6:!1};let e=NQ(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function UQ(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function LQ(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function KQ(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function zQ(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!v4(r)){let n=b4(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}P4.exports={nonSimpleDomain:OQ,recomposeAuthority:zQ,normalizeComponentEncoding:KQ,removeDotSegments:LQ,isIPv4:v4,isUUID:MQ,normalizeIPv6:b4,stringArrayToHexStripped:W_}});var _4=Ee((NRe,k4)=>{"use strict";w();var{isUUID:qQ}=V_(),FQ=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,GQ=["http","https","ws","wss","urn","urn:uuid"];function WQ(t){return GQ.indexOf(t)!==-1}function H_(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function x4(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function S4(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function VQ(t){return t.secure=H_(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function HQ(t){if((t.port===(H_(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function JQ(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(FQ);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,a=J_(s);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ZQ(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,a=J_(s);a&&(t=a.serialize(t,e));let o=t,i=t.nss;return o.path=`${n||e.nid}:${i}`,e.skipEscape=!0,o}function YQ(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!qQ(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function QQ(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var E4={scheme:"http",domainHost:!0,parse:x4,serialize:S4},XQ={scheme:"https",domainHost:E4.domainHost,parse:x4,serialize:S4},Nb={scheme:"ws",domainHost:!0,parse:VQ,serialize:HQ},eX={scheme:"wss",domainHost:Nb.domainHost,parse:Nb.parse,serialize:Nb.serialize},tX={scheme:"urn",parse:JQ,serialize:ZQ,skipNormalize:!0},rX={scheme:"urn:uuid",parse:YQ,serialize:QQ,skipNormalize:!0},Ub={http:E4,https:XQ,ws:Nb,wss:eX,urn:tX,"urn:uuid":rX};Object.setPrototypeOf(Ub,null);function J_(t){return t&&(Ub[t]||Ub[t.toLowerCase()])||void 0}k4.exports={wsIsSecure:H_,SCHEMES:Ub,isValidSchemeName:WQ,getSchemeHandler:J_}});var A4=Ee((LRe,Kb)=>{"use strict";w();var{normalizeIPv6:nX,removeDotSegments:Ag,recomposeAuthority:sX,normalizeComponentEncoding:Lb,isIPv4:iX,nonSimpleDomain:oX}=V_(),{SCHEMES:aX,getSchemeHandler:T4}=_4();function cX(t,e){return typeof t=="string"?t=pc(ld(t,e),e):typeof t=="object"&&(t=ld(pc(t,e),e)),t}function dX(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=I4(ld(t,n),ld(e,n),n,!0);return n.skipEscape=!0,pc(s,n)}function I4(t,e,r,n){let s={};return n||(t=ld(pc(t,r),r),e=ld(pc(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ag(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ag(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ag(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ag(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function uX(t,e,r){return typeof t=="string"?(t=unescape(t),t=pc(Lb(ld(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=pc(Lb(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=pc(Lb(ld(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=pc(Lb(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function pc(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],a=T4(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let o=sX(r);if(o!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(o),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let i=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(i=Ag(i)),o===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),s.push(i)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var lX=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ld(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let a=t.match(lX);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host)if(iX(n.host)===!1){let c=nX(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!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",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let o=T4(r.scheme||n.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(r.domainHost||o&&o.domainHost)&&s===!1&&oX(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(i){n.error=n.error||"Host's domain name can not be converted to ASCII: "+i}(!o||o&&!o.skipNormalize)&&(t.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,r)}else n.error=n.error||"URI can not be parsed.";return n}var Z_={SCHEMES:aX,normalize:cX,resolve:dX,resolveComponent:I4,equal:uX,serialize:pc,parse:ld};Kb.exports=Z_;Kb.exports.default=Z_;Kb.exports.fastUri=Z_});var D4=Ee(Y_=>{"use strict";w();Object.defineProperty(Y_,"__esModule",{value:!0});var R4=A4();R4.code='require("ajv/dist/runtime/uri").default';Y_.default=R4});var U4=Ee(Is=>{"use strict";w();Object.defineProperty(Is,"__esModule",{value:!0});Is.CodeGen=Is.Name=Is.nil=Is.stringify=Is.str=Is._=Is.KeywordCxt=void 0;var fX=_g();Object.defineProperty(Is,"KeywordCxt",{enumerable:!0,get:function(){return fX.KeywordCxt}});var Sh=_t();Object.defineProperty(Is,"_",{enumerable:!0,get:function(){return Sh._}});Object.defineProperty(Is,"str",{enumerable:!0,get:function(){return Sh.str}});Object.defineProperty(Is,"stringify",{enumerable:!0,get:function(){return Sh.stringify}});Object.defineProperty(Is,"nil",{enumerable:!0,get:function(){return Sh.nil}});Object.defineProperty(Is,"Name",{enumerable:!0,get:function(){return Sh.Name}});Object.defineProperty(Is,"CodeGen",{enumerable:!0,get:function(){return Sh.CodeGen}});var pX=Ob(),O4=Tg(),hX=__(),Rg=Ig(),mX=_t(),Dg=Sg(),zb=xg(),X_=Lt(),C4=g4(),yX=D4(),B4=(t,e)=>new RegExp(t,e);B4.code="new RegExp";var gX=["removeAdditional","useDefaults","coerceTypes"],wX=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vX={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."},bX={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},j4=200;function PX(t){var e,r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S,v,E,_,I,R,N,$,F;let z=t.strict,B=(e=t.code)===null||e===void 0?void 0:e.optimize,W=B===!0||B===void 0?1:B||0,X=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:B4,D=(s=t.uriResolver)!==null&&s!==void 0?s:yX.default;return{strictSchema:(o=(a=t.strictSchema)!==null&&a!==void 0?a:z)!==null&&o!==void 0?o:!0,strictNumbers:(c=(i=t.strictNumbers)!==null&&i!==void 0?i:z)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:z)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:z)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:z)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:W,regExp:X}:{optimize:W,regExp:X},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:j4,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:j4,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(E=t.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(_=t.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:(N=t.validateFormats)!==null&&N!==void 0?N:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(F=t.int32range)!==null&&F!==void 0?F:!0,uriResolver:D}}var Cg=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...PX(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new mX.ValueScope({scope:{},prefixes:wX,es5:r,lines:n}),this.logger=TX(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hX.getRules)(),$4.call(this,vX,e,"NOT SUPPORTED"),$4.call(this,bX,e,"DEPRECATED","warn"),this._metaOpts=kX.call(this),e.formats&&SX.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&EX.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xX.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=C4;n==="id"&&(s={...C4},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){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 s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,l){await a.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||o.call(this,f)}async function a(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof O4.default))throw l;return i.call(this,l),await c.call(this,l.missingSchema),o.call(this,d)}}function i({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await a.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,s);return this}let a;if(typeof e=="object"){let{schemaId:o}=this.opts;if(a=e[o],a!==void 0&&typeof a!="string")throw new Error(`schema ${o} must be string`)}return r=(0,Dg.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){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 s=this.validate(n,e);if(!s&&r){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return s}getSchema(e){let r;for(;typeof(r=M4.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Rg.SchemaEnv({schema:{},schemaId:n});if(r=Rg.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=M4.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Dg.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.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(AX.call(this,n,r),!r)return(0,X_.eachItem)(n,a=>Q_.call(this,a)),this;DX.call(this,r);let s={...r,type:(0,zb.getJSONTypes)(r.type),schemaType:(0,zb.getJSONTypes)(r.schemaType)};return(0,X_.eachItem)(n,s.type.length===0?a=>Q_.call(this,a,s):a=>s.type.forEach(o=>Q_.call(this,a,s,o))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(a=>a.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,a)=>s+r+a)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let a=s.split("/").slice(1),o=e;for(let i of a)o=o[i];for(let i in n){let c=n[i];if(typeof c!="object")continue;let{$data:u}=c.definition,d=o[i];u&&d&&(o[i]=N4(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,a=this.opts.addUsedSchema){let o,{schemaId:i}=this.opts;if(typeof e=="object")o=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Dg.normalizeId)(o||n);let u=Dg.getSchemaRefs.call(this,e,n);return c=new Rg.SchemaEnv({schema:e,schemaId:i,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Rg.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Rg.compileSchema.call(this,e)}finally{this.opts=r}}};Cg.ValidationError=pX.default;Cg.MissingRefError=O4.default;Is.default=Cg;function $4(t,e,r,n="error"){for(let s in t){let a=s;a in e&&this.logger[n](`${r}: option ${s}. ${t[a]}`)}}function M4(t){return t=(0,Dg.normalizeId)(t),this.schemas[t]||this.refs[t]}function xX(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function SX(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function EX(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function kX(){let t={...this.opts};for(let e of gX)delete t[e];return t}var _X={log(){},warn(){},error(){}};function TX(t){if(t===!1)return _X;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var IX=/^[a-z_$][a-z0-9_$:-]*$/i;function AX(t,e){let{RULES:r}=this;if((0,X_.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!IX.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 Q_(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=s?a.post:a.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},a.rules.push(o)),a.keywords[t]=!0,!e)return;let i={keyword:t,definition:{...e,type:(0,zb.getJSONTypes)(e.type),schemaType:(0,zb.getJSONTypes)(e.schemaType)}};e.before?RX.call(this,o,i,e.before):o.rules.push(i),a.all[t]=i,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function RX(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function DX(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=N4(e)),t.validateSchema=this.compile(e,!0))}var CX={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function N4(t){return{anyOf:[t,CX]}}});var L4=Ee(eT=>{"use strict";w();Object.defineProperty(eT,"__esModule",{value:!0});var jX={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eT.default=jX});var Gb=Ee(uf=>{"use strict";w();Object.defineProperty(uf,"__esModule",{value:!0});uf.callRef=uf.getValidate=void 0;var $X=Tg(),K4=Oo(),Bi=_t(),Eh=Mo(),z4=Ig(),qb=Lt(),MX={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:a,validateName:o,opts:i,self:c}=n,{root:u}=a;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=z4.resolveRef.call(c,u,s,r);if(d===void 0)throw new $X.default(n.opts.uriResolver,s,r);if(d instanceof z4.SchemaEnv)return f(d);return h(d);function l(){if(a===u)return Fb(t,o,a,a.$async);let p=e.scopeValue("root",{ref:u});return Fb(t,(0,Bi._)`${p}.validate`,u,u.$async)}function f(p){let m=q4(t,p);Fb(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",i.code.source===!0?{ref:p,code:(0,Bi.stringify)(p)}:{ref:p}),y=e.name("valid"),S=t.subschema({schema:p,dataTypes:[],schemaPath:Bi.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function q4(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Bi._)`${r.scopeValue("wrapper",{ref:e})}.validate`}uf.getValidate=q4;function Fb(t,e,r,n){let{gen:s,it:a}=t,{allErrors:o,schemaEnv:i,opts:c}=a,u=c.passContext?Eh.default.this:Bi.nil;n?d():l();function d(){if(!i.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,Bi._)`await ${(0,K4.callValidateCode)(t,e,u)}`),h(e),o||s.assign(p,!0)},m=>{s.if((0,Bi._)`!(${m} instanceof ${a.ValidationError})`,()=>s.throw(m)),f(m),o||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,K4.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,Bi._)`${p}.errors`;s.assign(Eh.default.vErrors,(0,Bi._)`${Eh.default.vErrors} === null ? ${m} : ${Eh.default.vErrors}.concat(${m})`),s.assign(Eh.default.errors,(0,Bi._)`${Eh.default.vErrors}.length`)}function h(p){var m;if(!a.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=qb.mergeEvaluated.props(s,y.props,a.props));else{let S=s.var("props",(0,Bi._)`${p}.evaluated.props`);a.props=qb.mergeEvaluated.props(s,S,a.props,Bi.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=qb.mergeEvaluated.items(s,y.items,a.items));else{let S=s.var("items",(0,Bi._)`${p}.evaluated.items`);a.items=qb.mergeEvaluated.items(s,S,a.items,Bi.Name)}}}uf.callRef=Fb;uf.default=MX});var F4=Ee(tT=>{"use strict";w();Object.defineProperty(tT,"__esModule",{value:!0});var OX=L4(),BX=Gb(),NX=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",OX.default,BX.default];tT.default=NX});var G4=Ee(rT=>{"use strict";w();Object.defineProperty(rT,"__esModule",{value:!0});var Wb=_t(),Tu=Wb.operators,Vb={maximum:{okStr:"<=",ok:Tu.LTE,fail:Tu.GT},minimum:{okStr:">=",ok:Tu.GTE,fail:Tu.LT},exclusiveMaximum:{okStr:"<",ok:Tu.LT,fail:Tu.GTE},exclusiveMinimum:{okStr:">",ok:Tu.GT,fail:Tu.LTE}},UX={message:({keyword:t,schemaCode:e})=>(0,Wb.str)`must be ${Vb[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Wb._)`{comparison: ${Vb[t].okStr}, limit: ${e}}`},LX={keyword:Object.keys(Vb),type:"number",schemaType:"number",$data:!0,error:UX,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Wb._)`${r} ${Vb[e].fail} ${n} || isNaN(${r})`)}};rT.default=LX});var W4=Ee(nT=>{"use strict";w();Object.defineProperty(nT,"__esModule",{value:!0});var jg=_t(),KX={message:({schemaCode:t})=>(0,jg.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,jg._)`{multipleOf: ${t}}`},zX={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:KX,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,a=s.opts.multipleOfPrecision,o=e.let("res"),i=a?(0,jg._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,jg._)`${o} !== parseInt(${o})`;t.fail$data((0,jg._)`(${n} === 0 || (${o} = ${r}/${n}, ${i}))`)}};nT.default=zX});var V4=Ee(sT=>{"use strict";w();Object.defineProperty(sT,"__esModule",{value:!0});var lf=_t(),qX=Lt(),FX=o2(),GX={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,lf.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,lf._)`{limit: ${t}}`},WX={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:GX,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,a=e==="maxLength"?lf.operators.GT:lf.operators.LT,o=s.opts.unicode===!1?(0,lf._)`${r}.length`:(0,lf._)`${(0,qX.useFunc)(t.gen,FX.default)}(${r})`;t.fail$data((0,lf._)`${o} ${a} ${n}`)}};sT.default=WX});var H4=Ee(iT=>{"use strict";w();Object.defineProperty(iT,"__esModule",{value:!0});var VX=Oo(),HX=Lt(),kh=_t(),JX={message:({schemaCode:t})=>(0,kh.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,kh._)`{pattern: ${t}}`},ZX={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:JX,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:a,it:o}=t,i=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,u=c.code==="new RegExp"?(0,kh._)`new RegExp`:(0,HX.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,kh._)`${u}(${a}, ${i}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,kh._)`!${d}`)}else{let c=(0,VX.usePattern)(t,s);t.fail$data((0,kh._)`!${c}.test(${r})`)}}};iT.default=ZX});var J4=Ee(oT=>{"use strict";w();Object.defineProperty(oT,"__esModule",{value:!0});var $g=_t(),YX={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,$g.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,$g._)`{limit: ${t}}`},QX={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YX,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?$g.operators.GT:$g.operators.LT;t.fail$data((0,$g._)`Object.keys(${r}).length ${s} ${n}`)}};oT.default=QX});var Z4=Ee(aT=>{"use strict";w();Object.defineProperty(aT,"__esModule",{value:!0});var Mg=Oo(),Og=_t(),XX=Lt(),eee={message:({params:{missingProperty:t}})=>(0,Og.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Og._)`{missingProperty: ${t}}`},tee={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eee,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:a,it:o}=t,{opts:i}=o;if(!a&&r.length===0)return;let c=r.length>=i.loopRequired;if(o.allErrors?u():d(),i.strictRequired){let h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let m of r)if(h?.[m]===void 0&&!p.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,XX.checkStrictMode)(o,S,o.opts.strictRequired)}}function u(){if(c||a)t.block$data(Og.nil,l);else for(let h of r)(0,Mg.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||a){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,Mg.checkMissingProp)(t,r,h)),(0,Mg.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Mg.noPropertyInData)(e,s,h,i.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,Mg.propertyInData)(e,s,h,i.ownProperties)),e.if((0,Og.not)(p),()=>{t.error(),e.break()})},Og.nil)}}};aT.default=tee});var Y4=Ee(cT=>{"use strict";w();Object.defineProperty(cT,"__esModule",{value:!0});var Bg=_t(),ree={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Bg.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Bg._)`{limit: ${t}}`},nee={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ree,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Bg.operators.GT:Bg.operators.LT;t.fail$data((0,Bg._)`${r}.length ${s} ${n}`)}};cT.default=nee});var Hb=Ee(dT=>{"use strict";w();Object.defineProperty(dT,"__esModule",{value:!0});var Q4=$_();Q4.code='require("ajv/dist/runtime/equal").default';dT.default=Q4});var X4=Ee(lT=>{"use strict";w();Object.defineProperty(lT,"__esModule",{value:!0});var uT=xg(),As=_t(),see=Lt(),iee=Hb(),oee={message:({params:{i:t,j:e}})=>(0,As.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,As._)`{i: ${t}, j: ${e}}`},aee={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:oee,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:a,schemaCode:o,it:i}=t;if(!n&&!s)return;let c=e.let("valid"),u=a.items?(0,uT.getSchemaTypes)(a.items):[];t.block$data(c,d,(0,As._)`${o} === false`),t.ok(c);function d(){let p=e.let("i",(0,As._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,As._)`${p} > 1`,()=>(l()?f:h)(p,m))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,m){let y=e.name("item"),S=(0,uT.checkDataTypes)(u,y,i.opts.strictNumbers,uT.DataType.Wrong),v=e.const("indices",(0,As._)`{}`);e.for((0,As._)`;${p}--;`,()=>{e.let(y,(0,As._)`${r}[${p}]`),e.if(S,(0,As._)`continue`),u.length>1&&e.if((0,As._)`typeof ${y} == "string"`,(0,As._)`${y} += "_"`),e.if((0,As._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(m,(0,As._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,As._)`${v}[${y}] = ${p}`)})}function h(p,m){let y=(0,see.useFunc)(e,iee.default),S=e.name("outer");e.label(S).for((0,As._)`;${p}--;`,()=>e.for((0,As._)`${m} = ${p}; ${m}--;`,()=>e.if((0,As._)`${y}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};lT.default=aee});var eB=Ee(pT=>{"use strict";w();Object.defineProperty(pT,"__esModule",{value:!0});var fT=_t(),cee=Lt(),dee=Hb(),uee={message:"must be equal to constant",params:({schemaCode:t})=>(0,fT._)`{allowedValue: ${t}}`},lee={keyword:"const",$data:!0,error:uee,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:a}=t;n||a&&typeof a=="object"?t.fail$data((0,fT._)`!${(0,cee.useFunc)(e,dee.default)}(${r}, ${s})`):t.fail((0,fT._)`${a} !== ${r}`)}};pT.default=lee});var tB=Ee(hT=>{"use strict";w();Object.defineProperty(hT,"__esModule",{value:!0});var Ng=_t(),fee=Lt(),pee=Hb(),hee={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ng._)`{allowedValues: ${t}}`},mee={keyword:"enum",schemaType:"array",$data:!0,error:hee,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:a,it:o}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let i=s.length>=o.opts.loopEnum,c,u=()=>c??(c=(0,fee.useFunc)(e,pee.default)),d;if(i||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let h=e.const("vSchema",a);d=(0,Ng.or)(...s.map((p,m)=>f(h,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",a,h=>e.if((0,Ng._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function f(h,p){let m=s[p];return typeof m=="object"&&m!==null?(0,Ng._)`${u()}(${r}, ${h}[${p}])`:(0,Ng._)`${r} === ${m}`}}};hT.default=mee});var rB=Ee(mT=>{"use strict";w();Object.defineProperty(mT,"__esModule",{value:!0});var yee=G4(),gee=W4(),wee=V4(),vee=H4(),bee=J4(),Pee=Z4(),xee=Y4(),See=X4(),Eee=eB(),kee=tB(),_ee=[yee.default,gee.default,wee.default,vee.default,bee.default,Pee.default,xee.default,See.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Eee.default,kee.default];mT.default=_ee});var gT=Ee(Ug=>{"use strict";w();Object.defineProperty(Ug,"__esModule",{value:!0});Ug.validateAdditionalItems=void 0;var ff=_t(),yT=Lt(),Tee={message:({params:{len:t}})=>(0,ff.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ff._)`{limit: ${t}}`},Iee={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Tee,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,yT.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}nB(t,n)}};function nB(t,e){let{gen:r,schema:n,data:s,keyword:a,it:o}=t;o.items=!0;let i=r.const("len",(0,ff._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ff._)`${i} <= ${e.length}`);else if(typeof n=="object"&&!(0,yT.alwaysValidSchema)(o,n)){let u=r.var("valid",(0,ff._)`${i} <= ${e.length}`);r.if((0,ff.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,i,d=>{t.subschema({keyword:a,dataProp:d,dataPropType:yT.Type.Num},u),o.allErrors||r.if((0,ff.not)(u),()=>r.break())})}}Ug.validateAdditionalItems=nB;Ug.default=Iee});var wT=Ee(Lg=>{"use strict";w();Object.defineProperty(Lg,"__esModule",{value:!0});Lg.validateTuple=void 0;var sB=_t(),Jb=Lt(),Aee=Oo(),Ree={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return iB(t,"additionalItems",e);r.items=!0,!(0,Jb.alwaysValidSchema)(r,e)&&t.ok((0,Aee.validateArray)(t))}};function iB(t,e,r=t.schema){let{gen:n,parentSchema:s,data:a,keyword:o,it:i}=t;d(s),i.opts.unevaluated&&r.length&&i.items!==!0&&(i.items=Jb.mergeEvaluated.items(n,r.length,i.items));let c=n.name("valid"),u=n.const("len",(0,sB._)`${a}.length`);r.forEach((l,f)=>{(0,Jb.alwaysValidSchema)(i,l)||(n.if((0,sB._)`${u} > ${f}`,()=>t.subschema({keyword:o,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:h}=i,p=r.length,m=p===l.minItems&&(p===l.maxItems||l[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,Jb.checkStrictMode)(i,y,f.strictTuples)}}}Lg.validateTuple=iB;Lg.default=Ree});var oB=Ee(vT=>{"use strict";w();Object.defineProperty(vT,"__esModule",{value:!0});var Dee=wT(),Cee={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Dee.validateTuple)(t,"items")};vT.default=Cee});var cB=Ee(bT=>{"use strict";w();Object.defineProperty(bT,"__esModule",{value:!0});var aB=_t(),jee=Lt(),$ee=Oo(),Mee=gT(),Oee={message:({params:{len:t}})=>(0,aB.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,aB._)`{limit: ${t}}`},Bee={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Oee,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,jee.alwaysValidSchema)(n,e)&&(s?(0,Mee.validateAdditionalItems)(t,s):t.ok((0,$ee.validateArray)(t)))}};bT.default=Bee});var dB=Ee(PT=>{"use strict";w();Object.defineProperty(PT,"__esModule",{value:!0});var No=_t(),Zb=Lt(),Nee={message:({params:{min:t,max:e}})=>e===void 0?(0,No.str)`must contain at least ${t} valid item(s)`:(0,No.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,No._)`{minContains: ${t}}`:(0,No._)`{minContains: ${t}, maxContains: ${e}}`},Uee={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Nee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t,o,i,{minContains:c,maxContains:u}=n;a.opts.next?(o=c===void 0?1:c,i=u):o=1;let d=e.const("len",(0,No._)`${s}.length`);if(t.setParams({min:o,max:i}),i===void 0&&o===0){(0,Zb.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&o>i){(0,Zb.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Zb.alwaysValidSchema)(a,r)){let m=(0,No._)`${d} >= ${o}`;i!==void 0&&(m=(0,No._)`${m} && ${d} <= ${i}`),t.pass(m);return}a.items=!0;let l=e.name("valid");i===void 0&&o===1?h(l,()=>e.if(l,()=>e.break())):o===0?(e.let(l,!0),i!==void 0&&e.if((0,No._)`${s}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.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,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:Zb.Type.Num,compositeRule:!0},m),y()})}function p(m){e.code((0,No._)`${m}++`),i===void 0?e.if((0,No._)`${m} >= ${o}`,()=>e.assign(l,!0).break()):(e.if((0,No._)`${m} > ${i}`,()=>e.assign(l,!1).break()),o===1?e.assign(l,!0):e.if((0,No._)`${m} >= ${o}`,()=>e.assign(l,!0)))}}};PT.default=Uee});var Yb=Ee(hc=>{"use strict";w();Object.defineProperty(hc,"__esModule",{value:!0});hc.validateSchemaDeps=hc.validatePropertyDeps=hc.error=void 0;var xT=_t(),Lee=Lt(),Kg=Oo();hc.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,xT.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,xT._)`{property: ${t},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${e},
10
- deps: ${r}}`};var Kee={keyword:"dependencies",type:"object",schemaType:"object",error:hc.error,code(t){let[e,r]=zee(t);uB(t,e),lB(t,r)}};function zee({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function uB(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let o in e){let i=e[o];if(i.length===0)continue;let c=(0,Kg.propertyInData)(r,n,o,s.opts.ownProperties);t.setParams({property:o,depsCount:i.length,deps:i.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of i)(0,Kg.checkReportMissingProp)(t,u)}):(r.if((0,xT._)`${c} && (${(0,Kg.checkMissingProp)(t,i,a)})`),(0,Kg.reportMissingProp)(t,a),r.else())}}hc.validatePropertyDeps=uB;function lB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Lee.alwaysValidSchema)(a,e[i])||(r.if((0,Kg.propertyInData)(r,n,i,a.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:i},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}hc.validateSchemaDeps=lB;hc.default=Kee});var pB=Ee(ST=>{"use strict";w();Object.defineProperty(ST,"__esModule",{value:!0});var fB=_t(),qee=Lt(),Fee={message:"property name must be valid",params:({params:t})=>(0,fB._)`{propertyName: ${t.propertyName}}`},Gee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Fee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,qee.alwaysValidSchema)(s,r))return;let a=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,fB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};ST.default=Gee});var kT=Ee(ET=>{"use strict";w();Object.defineProperty(ET,"__esModule",{value:!0});var Qb=Oo(),_a=_t(),Wee=Mo(),Xb=Lt(),Vee={message:"must NOT have additional properties",params:({params:t})=>(0,_a._)`{additionalProperty: ${t.additionalProperty}}`},Hee={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:a,it:o}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Xb.alwaysValidSchema)(o,r))return;let u=(0,Qb.allSchemaProperties)(n.properties),d=(0,Qb.allSchemaProperties)(n.patternProperties);l(),t.ok((0,_a._)`${a} === ${Wee.default.errors}`);function l(){e.forIn("key",s,y=>{!u.length&&!d.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let S;if(u.length>8){let v=(0,Xb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Qb.isOwnProperty)(e,v,y)}else u.length?S=(0,_a.or)(...u.map(v=>(0,_a._)`${y} === ${v}`)):S=_a.nil;return d.length&&(S=(0,_a.or)(S,...d.map(v=>(0,_a._)`${(0,Qb.usePattern)(t,v)}.test(${y})`))),(0,_a.not)(S)}function h(y){e.code((0,_a._)`delete ${s}[${y}]`)}function p(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Xb.alwaysValidSchema)(o,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,_a.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,_a.not)(S),()=>e.break()))}}function m(y,S,v){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Xb.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};ET.default=Hee});var yB=Ee(TT=>{"use strict";w();Object.defineProperty(TT,"__esModule",{value:!0});var Jee=_g(),hB=Oo(),_T=Lt(),mB=kT(),Zee={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&mB.default.code(new Jee.KeywordCxt(a,mB.default,"additionalProperties"));let o=(0,hB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=_T.mergeEvaluated.props(e,(0,_T.toHash)(o),a.props));let i=o.filter(l=>!(0,_T.alwaysValidSchema)(a,r[l]));if(i.length===0)return;let c=e.name("valid");for(let l of i)u(l)?d(l):(e.if((0,hB.propertyInData)(e,s,l,a.opts.ownProperties)),d(l),a.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return a.opts.useDefaults&&!a.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};TT.default=Zee});var bB=Ee(IT=>{"use strict";w();Object.defineProperty(IT,"__esModule",{value:!0});var gB=Oo(),e1=_t(),wB=Lt(),vB=Lt(),Yee={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:a}=t,{opts:o}=a,i=(0,gB.allSchemaProperties)(r),c=i.filter(m=>(0,wB.alwaysValidSchema)(a,r[m]));if(i.length===0||c.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof e1.Name)&&(a.props=(0,vB.evaluatedPropsToName)(e,a.props));let{props:l}=a;f();function f(){for(let m of i)u&&h(m),a.allErrors?p(m):(e.var(d,!0),p(m),e.if(d))}function h(m){for(let y in u)new RegExp(m).test(y)&&(0,wB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,e1._)`${(0,gB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:vB.Type.Str},d),a.opts.unevaluated&&l!==!0?e.assign((0,e1._)`${l}[${y}]`,!0):!S&&!a.allErrors&&e.if((0,e1.not)(d),()=>e.break())})})}}};IT.default=Yee});var PB=Ee(AT=>{"use strict";w();Object.defineProperty(AT,"__esModule",{value:!0});var Qee=Lt(),Xee={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Qee.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};AT.default=Xee});var xB=Ee(RT=>{"use strict";w();Object.defineProperty(RT,"__esModule",{value:!0});var ete=Oo(),tte={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ete.validateUnion,error:{message:"must match a schema in anyOf"}};RT.default=tte});var SB=Ee(DT=>{"use strict";w();Object.defineProperty(DT,"__esModule",{value:!0});var t1=_t(),rte=Lt(),nte={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},ste={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nte,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let a=r,o=e.let("valid",!1),i=e.let("passing",null),c=e.name("_valid");t.setParams({passing:i}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){a.forEach((d,l)=>{let f;(0,rte.alwaysValidSchema)(s,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,t1._)`${c} && ${o}`).assign(o,!1).assign(i,(0,t1._)`[${i}, ${l}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(i,l),f&&t.mergeEvaluated(f,t1.Name)})})}}};DT.default=ste});var EB=Ee(CT=>{"use strict";w();Object.defineProperty(CT,"__esModule",{value:!0});var ite=Lt(),ote={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((a,o)=>{if((0,ite.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};CT.default=ote});var TB=Ee(jT=>{"use strict";w();Object.defineProperty(jT,"__esModule",{value:!0});var r1=_t(),_B=Lt(),ate={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},cte={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ate,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_B.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=kB(n,"then"),a=kB(n,"else");if(!s&&!a)return;let o=e.let("valid",!0),i=e.name("_valid");if(c(),t.reset(),s&&a){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(i,u("then",d),u("else",d))}else s?e.if(i,u("then")):e.if((0,r1.not)(i),u("else"));t.pass(o,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},i);e.assign(o,i),t.mergeValidEvaluated(f,o),l?e.assign(l,(0,r1._)`${d}`):t.setParams({ifClause:d})}}}};function kB(t,e){let r=t.schema[e];return r!==void 0&&!(0,_B.alwaysValidSchema)(t,r)}jT.default=cte});var IB=Ee($T=>{"use strict";w();Object.defineProperty($T,"__esModule",{value:!0});var dte=Lt(),ute={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,dte.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};$T.default=ute});var AB=Ee(MT=>{"use strict";w();Object.defineProperty(MT,"__esModule",{value:!0});var lte=gT(),fte=oB(),pte=wT(),hte=cB(),mte=dB(),yte=Yb(),gte=pB(),wte=kT(),vte=yB(),bte=bB(),Pte=PB(),xte=xB(),Ste=SB(),Ete=EB(),kte=TB(),_te=IB();function Tte(t=!1){let e=[Pte.default,xte.default,Ste.default,Ete.default,kte.default,_te.default,gte.default,wte.default,yte.default,vte.default,bte.default];return t?e.push(fte.default,hte.default):e.push(lte.default,pte.default),e.push(mte.default),e}MT.default=Tte});var BT=Ee(zg=>{"use strict";w();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicAnchor=void 0;var OT=_t(),Ite=Mo(),RB=Ig(),Ate=Gb(),Rte={keyword:"$dynamicAnchor",schemaType:"string",code:t=>DB(t,t.schema)};function DB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,OT._)`${Ite.default.dynamicAnchors}${(0,OT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Dte(t);r.if((0,OT._)`!${s}`,()=>r.assign(s,a))}zg.dynamicAnchor=DB;function Dte(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:s,baseId:a,localRefs:o,meta:i}=e.root,{schemaId:c}=n.opts,u=new RB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return RB.compileSchema.call(n,u),(0,Ate.getValidate)(t,u)}zg.default=Rte});var NT=Ee(qg=>{"use strict";w();Object.defineProperty(qg,"__esModule",{value:!0});qg.dynamicRef=void 0;var CB=_t(),Cte=Mo(),jB=Gb(),jte={keyword:"$dynamicRef",schemaType:"string",code:t=>$B(t,t.schema)};function $B(t,e){let{gen:r,keyword:n,it:s}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(s.allErrors)o();else{let c=r.let("valid",!1);o(c),t.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[a]){let u=r.let("_v",(0,CB._)`${Cte.default.dynamicAnchors}${(0,CB.getProperty)(a)}`);r.if(u,i(u,c),i(s.validateName,c))}else i(s.validateName,c)()}function i(c,u){return u?()=>r.block(()=>{(0,jB.callRef)(t,c),r.let(u,!0)}):()=>(0,jB.callRef)(t,c)}}qg.dynamicRef=$B;qg.default=jte});var MB=Ee(UT=>{"use strict";w();Object.defineProperty(UT,"__esModule",{value:!0});var $te=BT(),Mte=Lt(),Ote={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,$te.dynamicAnchor)(t,""):(0,Mte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};UT.default=Ote});var OB=Ee(LT=>{"use strict";w();Object.defineProperty(LT,"__esModule",{value:!0});var Bte=NT(),Nte={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Bte.dynamicRef)(t,t.schema)};LT.default=Nte});var BB=Ee(KT=>{"use strict";w();Object.defineProperty(KT,"__esModule",{value:!0});var Ute=BT(),Lte=NT(),Kte=MB(),zte=OB(),qte=[Ute.default,Lte.default,Kte.default,zte.default];KT.default=qte});var UB=Ee(zT=>{"use strict";w();Object.defineProperty(zT,"__esModule",{value:!0});var NB=Yb(),Fte={keyword:"dependentRequired",type:"object",schemaType:"object",error:NB.error,code:t=>(0,NB.validatePropertyDeps)(t)};zT.default=Fte});var LB=Ee(qT=>{"use strict";w();Object.defineProperty(qT,"__esModule",{value:!0});var Gte=Yb(),Wte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Gte.validateSchemaDeps)(t)};qT.default=Wte});var KB=Ee(FT=>{"use strict";w();Object.defineProperty(FT,"__esModule",{value:!0});var Vte=Lt(),Hte={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Vte.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};FT.default=Hte});var zB=Ee(GT=>{"use strict";w();Object.defineProperty(GT,"__esModule",{value:!0});var Jte=UB(),Zte=LB(),Yte=KB(),Qte=[Jte.default,Zte.default,Yte.default];GT.default=Qte});var FB=Ee(WT=>{"use strict";w();Object.defineProperty(WT,"__esModule",{value:!0});var Iu=_t(),qB=Lt(),Xte=Mo(),ere={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Iu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},tre={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:ere,code(t){let{gen:e,schema:r,data:n,errsCount:s,it:a}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:i}=a;i instanceof Iu.Name?e.if((0,Iu._)`${i} !== true`,()=>e.forIn("key",n,l=>e.if(u(i,l),()=>c(l)))):i!==!0&&e.forIn("key",n,l=>i===void 0?c(l):e.if(d(i,l),()=>c(l))),a.props=!0,t.ok((0,Iu._)`${s} === ${Xte.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,qB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:qB.Type.Str},f),o||e.if((0,Iu.not)(f),()=>e.break())}}function u(l,f){return(0,Iu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Iu._)`${f} !== ${p}`);return(0,Iu.and)(...h)}}};WT.default=tre});var WB=Ee(VT=>{"use strict";w();Object.defineProperty(VT,"__esModule",{value:!0});var pf=_t(),GB=Lt(),rre={message:({params:{len:t}})=>(0,pf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pf._)`{limit: ${t}}`},nre={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:rre,code(t){let{gen:e,schema:r,data:n,it:s}=t,a=s.items||0;if(a===!0)return;let o=e.const("len",(0,pf._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,pf._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,GB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,pf._)`${o} <= ${a}`);e.if((0,pf.not)(c),()=>i(c,a)),t.ok(c)}s.items=!0;function i(c,u){e.forRange("i",u,o,d=>{t.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:GB.Type.Num},c),s.allErrors||e.if((0,pf.not)(c),()=>e.break())})}}};VT.default=nre});var VB=Ee(HT=>{"use strict";w();Object.defineProperty(HT,"__esModule",{value:!0});var sre=FB(),ire=WB(),ore=[sre.default,ire.default];HT.default=ore});var HB=Ee(JT=>{"use strict";w();Object.defineProperty(JT,"__esModule",{value:!0});var An=_t(),are={message:({schemaCode:t})=>(0,An.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,An._)`{format: ${t}}`},cre={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:are,code(t,e){let{gen:r,data:n,$data:s,schema:a,schemaCode:o,it:i}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=i;if(!c.validateFormats)return;s?f():h();function f(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,An._)`${p}[${o}]`),y=r.let("fType"),S=r.let("format");r.if((0,An._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,An._)`${m}.type || "string"`).assign(S,(0,An._)`${m}.validate`),()=>r.assign(y,(0,An._)`"string"`).assign(S,m)),t.fail$data((0,An.or)(v(),E()));function v(){return c.strictSchema===!1?An.nil:(0,An._)`${o} && !${S}`}function E(){let _=d.$async?(0,An._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,An._)`${S}(${n})`,I=(0,An._)`(typeof ${S} == "function" ? ${_} : ${S}.test(${n}))`;return(0,An._)`${S} && ${S} !== true && ${y} === ${e} && !${I}`}}function h(){let p=l.formats[a];if(!p){v();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(_());function v(){if(c.strictSchema===!1){l.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${a}" ignored in schema at path "${u}"`}}function E(I){let R=I instanceof RegExp?(0,An.regexpCode)(I):c.code.formats?(0,An._)`${c.code.formats}${(0,An.getProperty)(a)}`:void 0,N=r.scopeValue("formats",{key:a,ref:I,code:R});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,An._)`${N}.validate`]:["string",I,N]}function _(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,An._)`await ${S}(${n})`}return typeof y=="function"?(0,An._)`${S}(${n})`:(0,An._)`${S}.test(${n})`}}}};JT.default=cre});var JB=Ee(ZT=>{"use strict";w();Object.defineProperty(ZT,"__esModule",{value:!0});var dre=HB(),ure=[dre.default];ZT.default=ure});var ZB=Ee(_h=>{"use strict";w();Object.defineProperty(_h,"__esModule",{value:!0});_h.contentVocabulary=_h.metadataVocabulary=void 0;_h.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_h.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var QB=Ee(YT=>{"use strict";w();Object.defineProperty(YT,"__esModule",{value:!0});var lre=F4(),fre=rB(),pre=AB(),hre=BB(),mre=zB(),yre=VB(),gre=JB(),YB=ZB(),wre=[hre.default,lre.default,fre.default,(0,pre.default)(!0),gre.default,YB.metadataVocabulary,YB.contentVocabulary,mre.default,yre.default];YT.default=wre});var eN=Ee(n1=>{"use strict";w();Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var XB;(function(t){t.Tag="tag",t.Mapping="mapping"})(XB||(n1.DiscrError=XB={}))});var rN=Ee(XT=>{"use strict";w();Object.defineProperty(XT,"__esModule",{value:!0});var Th=_t(),QT=eN(),tN=Ig(),vre=Tg(),bre=Lt(),Pre={message:({params:{discrError:t,tagName:e}})=>t===QT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Th._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xre={keyword:"discriminator",type:"object",schemaType:"object",error:Pre,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:a}=t,{oneOf:o}=s;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=n.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Th._)`${r}${(0,Th.getProperty)(i)}`);e.if((0,Th._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:QT.DiscrError.Tag,tag:u,tagName:i})),t.ok(c);function d(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Th._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:QT.DiscrError.Mapping,tag:u,tagName:i}),e.endIf()}function l(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,Th.Name),p}function f(){var h;let p={},m=S(s),y=!0;for(let _=0;_<o.length;_++){let I=o[_];if(I?.$ref&&!(0,bre.schemaHasRulesButRef)(I,a.self.RULES)){let N=I.$ref;if(I=tN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),I instanceof tN.SchemaEnv&&(I=I.schema),I===void 0)throw new vre.default(a.opts.uriResolver,a.baseId,N)}let R=(h=I?.properties)===null||h===void 0?void 0:h[i];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(I)),v(R,_)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:_}){return Array.isArray(_)&&_.includes(i)}function v(_,I){if(_.const)E(_.const,I);else if(_.enum)for(let R of _.enum)E(R,I);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function E(_,I){if(typeof _!="string"||_ in p)throw new Error(`discriminator: "${i}" values must be unique strings`);p[_]=I}}}};XT.default=xre});var nN=Ee((NDe,Sre)=>{Sre.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 sN=Ee((UDe,Ere)=>{Ere.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 iN=Ee((LDe,kre)=>{kre.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 oN=Ee((KDe,_re)=>{_re.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 aN=Ee((zDe,Tre)=>{Tre.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 cN=Ee((qDe,Ire)=>{Ire.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 dN=Ee((FDe,Are)=>{Are.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 uN=Ee((GDe,Rre)=>{Rre.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 lN=Ee(eI=>{"use strict";w();Object.defineProperty(eI,"__esModule",{value:!0});var Dre=nN(),Cre=sN(),jre=iN(),$re=oN(),Mre=aN(),Ore=cN(),Bre=dN(),Nre=uN(),Ure=["/properties"];function Lre(t){return[Dre,Cre,jre,$re,Mre,e(this,Ore),Bre,e(this,Nre)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Ure):n}}eI.default=Lre});var nI=Ee((Hr,rI)=>{"use strict";w();Object.defineProperty(Hr,"__esModule",{value:!0});Hr.MissingRefError=Hr.ValidationError=Hr.CodeGen=Hr.Name=Hr.nil=Hr.stringify=Hr.str=Hr._=Hr.KeywordCxt=Hr.Ajv2020=void 0;var Kre=U4(),zre=QB(),qre=rN(),Fre=lN(),tI="https://json-schema.org/draft/2020-12/schema",Ih=class extends Kre.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),zre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(qre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(Fre.default.call(this,e),this.refs["http://json-schema.org/schema"]=tI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(tI)?tI:void 0)}};Hr.Ajv2020=Ih;rI.exports=Hr=Ih;rI.exports.Ajv2020=Ih;Object.defineProperty(Hr,"__esModule",{value:!0});Hr.default=Ih;var Gre=_g();Object.defineProperty(Hr,"KeywordCxt",{enumerable:!0,get:function(){return Gre.KeywordCxt}});var Ah=_t();Object.defineProperty(Hr,"_",{enumerable:!0,get:function(){return Ah._}});Object.defineProperty(Hr,"str",{enumerable:!0,get:function(){return Ah.str}});Object.defineProperty(Hr,"stringify",{enumerable:!0,get:function(){return Ah.stringify}});Object.defineProperty(Hr,"nil",{enumerable:!0,get:function(){return Ah.nil}});Object.defineProperty(Hr,"Name",{enumerable:!0,get:function(){return Ah.Name}});Object.defineProperty(Hr,"CodeGen",{enumerable:!0,get:function(){return Ah.CodeGen}});var Wre=Ob();Object.defineProperty(Hr,"ValidationError",{enumerable:!0,get:function(){return Wre.default}});var Vre=Tg();Object.defineProperty(Hr,"MissingRefError",{enumerable:!0,get:function(){return Vre.default}})});var b9=Ee((YOe,_A)=>{"use strict";w();var Xde=Object.prototype.hasOwnProperty,_i="~";function Bw(){}Object.create&&(Bw.prototype=Object.create(null),new Bw().__proto__||(_i=!1));function eue(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function v9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new eue(r,n||t,s),o=_i?_i+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}function wP(t,e){--t._eventsCount===0?t._events=new Bw:delete t._events[e]}function ri(){this._events=new Bw,this._eventsCount=0}ri.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Xde.call(r,n)&&e.push(_i?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ri.prototype.listeners=function(e){var r=_i?_i+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,o=new Array(a);s<a;s++)o[s]=n[s].fn;return o};ri.prototype.listenerCount=function(e){var r=_i?_i+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ri.prototype.emit=function(e,r,n,s,a,o){var i=_i?_i+e:e;if(!this._events[i])return!1;var c=this._events[i],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,s),!0;case 5:return c.fn.call(c.context,r,n,s,a),!0;case 6:return c.fn.call(c.context,r,n,s,a,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var f=c.length,h;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,r);break;case 3:c[l].fn.call(c[l].context,r,n);break;case 4:c[l].fn.call(c[l].context,r,n,s);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];c[l].fn.apply(c[l].context,d)}}return!0};ri.prototype.on=function(e,r,n){return v9(this,e,r,n,!1)};ri.prototype.once=function(e,r,n){return v9(this,e,r,n,!0)};ri.prototype.removeListener=function(e,r,n,s){var a=_i?_i+e:e;if(!this._events[a])return this;if(!r)return wP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&wP(this,a);else{for(var i=0,c=[],u=o.length;i<u;i++)(o[i].fn!==r||s&&!o[i].once||n&&o[i].context!==n)&&c.push(o[i]);c.length?this._events[a]=c.length===1?c[0]:c:wP(this,a)}return this};ri.prototype.removeAllListeners=function(e){var r;return e?(r=_i?_i+e:e,this._events[r]&&wP(this,r)):(this._events=new Bw,this._eventsCount=0),this};ri.prototype.off=ri.prototype.removeListener;ri.prototype.addListener=ri.prototype.on;ri.prefixed=_i;ri.EventEmitter=ri;typeof _A<"u"&&(_A.exports=ri)});w();w();var dm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(dm||{});w();w();hn();Na();w();w();var jm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,LD=new Set,n2=typeof process=="object"&&process?process:{},KD=(t,e,r,n)=>{typeof n2.emitWarning=="function"?n2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},I0=globalThis.AbortController,UD=globalThis.AbortSignal;if(typeof I0>"u"){UD=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},I0=class{constructor(){e()}signal=new UD;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n)}}};let t=n2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,KD("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var AF=t=>!LD.has(t),Zhe=Symbol("type"),Kd=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),zD=t=>Kd(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?mp:null:null,mp=class extends Array{constructor(e){super(e),this.fill(0)}},s2=class t{heap;length;static#c=!1;static create(e){let r=zD(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},A0=class t{#c;#l;#w;#h;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#s;#r;#e;#d;#f;#a;#i;#y;#o;#x;#S;#g;#v;#k;#u;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#g,sizes:e.#x,keyMap:e.#s,keyList:e.#r,valList:e.#e,next:e.#d,prev:e.#f,get head(){return e.#a},get tail(){return e.#i},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,s,a)=>e.#C(r,n,s,a),moveToTail:r=>e.#I(r),indexes:r=>e.#b(r),rindexes:r=>e.#P(r),isStale:r=>e.#p(r)}}get max(){return this.#c}get maxSize(){return this.#l}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#A}get dispose(){return this.#w}get disposeAfter(){return this.#h}constructor(e){let{max:r=0,ttl:n,ttlResolution:s=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:i,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:_,ignoreFetchAbort:I}=e;if(r!==0&&!Kd(r))throw new TypeError("max option must be a nonnegative integer");let R=r?zD(r):Array;if(!R)throw new Error("invalid max value: "+r);if(this.#c=r,this.#l=h,this.maxEntrySize=p||this.#l,this.sizeCalculation=m,this.sizeCalculation){if(!this.#l&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#A=y,this.#k=!!y,this.#s=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#d=new R(r),this.#f=new R(r),this.#a=0,this.#i=0,this.#y=s2.create(r),this.#n=0,this.#m=0,typeof u=="function"&&(this.#w=u),typeof d=="function"?(this.#h=d,this.#o=[]):(this.#h=void 0,this.#o=void 0),this.#v=!!this.#w,this.#u=!!this.#h,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#l!==0&&!Kd(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Kd(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Kd(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Kd(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#c===0&&this.ttl===0&&this.#l===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#l){let N="LRU_CACHE_UNBOUNDED";AF(N)&&(LD.add(N),KD("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,t))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#j(){let e=new mp(this.#c),r=new mp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=jm.now())=>{if(r[a]=o!==0?i:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#p(a)&&this.delete(this.#r[a])},o+1);c.unref&&c.unref()}},this.#_=a=>{r[a]=e[a]!==0?jm.now():0},this.#E=(a,o)=>{if(e[o]){let i=e[o],c=r[o];a.ttl=i,a.start=c,a.now=n||s();let u=a.now-c;a.remainingTTL=i-u}};let n=0,s=()=>{let a=jm.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#s.get(a);if(o===void 0)return 0;let i=e[o],c=r[o];if(i===0||c===0)return 1/0;let u=(n||s())-c;return i-u},this.#p=a=>e[a]!==0&&r[a]!==0&&(n||s())-r[a]>e[a]}#_=()=>{};#E=()=>{};#$=()=>{};#p=()=>!1;#N(){let e=new mp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#M=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Kd(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Kd(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#R=(r,n,s)=>{if(e[r]=n,this.#l){let a=this.#l-e[r];for(;this.#m>a;)this.#D(!0)}this.#m+=e[r],s&&(s.entrySize=n,s.totalCalculatedSize=this.#m)}}#T=e=>{};#R=(e,r,n)=>{};#M=(e,r,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#i;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#P({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#O(e){return e!==void 0&&this.#s.get(this.#r[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#P())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#b()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#P()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#b())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#P())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#P()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#P({allowStale:!0}))this.#p(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#b({allowStale:!0})){let n=this.#r[r],s=this.#e[r],a=this.#t(s)?s.__staleWhileFetching:s;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#g&&this.#S){o.ttl=this.#g[r];let i=jm.now()-this.#S[r];o.start=Math.floor(Date.now()-i)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let s=Date.now()-n.start;n.start=jm.now()-s}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,d=this.#M(e,r,n.size||0,i);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let l=this.#n===0?void 0:this.#s.get(e);if(l===void 0)l=this.#n===0?this.#i:this.#y.length!==0?this.#y.pop():this.#n===this.#c?this.#D(!1):this.#n,this.#r[l]=e,this.#e[l]=r,this.#s.set(e,l),this.#d[this.#i]=l,this.#f[l]=this.#i,this.#i=l,this.#n++,this.#R(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(r!==f){if(this.#k&&this.#t(f)?f.__abortController.abort(new Error("replaced")):o||(this.#v&&this.#w?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"])),this.#T(l),this.#R(l,d,c),this.#e[l]=r,c){c.set="replace";let h=f&&this.#t(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(s!==0&&!this.#g&&this.#j(),this.#g&&(u||this.#$(l,s,a),c&&this.#E(c,l)),!o&&this.#u&&this.#o){let f=this.#o,h;for(;h=f?.shift();)this.#h?.(...h)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#D(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}}#D(e){let r=this.#a,n=this.#r[r],s=this.#e[r];return this.#k&&this.#t(s)?s.__abortController.abort(new Error("evicted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,n,"evict"),this.#u&&this.#o?.push([s,n,"evict"])),this.#T(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#n===1?(this.#a=this.#i=0,this.#y.length=0):this.#a=this.#d[r],this.#s.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=r,a=this.#s.get(e);if(a!==void 0){let o=this.#e[a];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(a))s&&(s.has="stale",this.#E(s,a));else return n&&this.#_(a),s&&(s.has="hit",this.#E(s,a)),!0}else s&&(s.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,s=this.#s.get(e);if(s!==void 0&&(n||!this.#p(s))){let a=this.#e[s];return this.#t(a)?a.__staleWhileFetching:a}}#C(e,r,n,s){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new I0,{signal:i}=n;i?.addEventListener("abort",()=>o.abort(i.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:s},u=(m,y=!1)=>{let{aborted:S}=o.signal,v=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,v&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!v&&!y)return l(o.signal.reason);let E=h;return this.#e[r]===h&&(m===void 0?E.__staleWhileFetching?this.#e[r]=E.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),l(m)),l=m=>{let{aborted:y}=o.signal,S=y&&n.allowStaleOnFetchAbort,v=S||n.allowStaleOnFetchRejection,E=v||n.noDeleteOnFetchRejection,_=h;if(this.#e[r]===h&&(!E||_.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=_.__staleWhileFetching)),v)return n.status&&_.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,y)=>{let S=this.#A?.(e,a,c);S&&S instanceof Promise&&S.then(v=>m(v),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=v=>u(v,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(u,d),p=Object.assign(h,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,p,{...c.options,status:void 0}),r=this.#s.get(e)):this.#e[r]=p,p}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof I0}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:y=!1,status:S,signal:v}=r;if(!this.#k)return S&&(S.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,status:S});let E={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:i,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:S,signal:v},_=this.#s.get(e);if(_===void 0){S&&(S.fetch="miss");let I=this.#C(e,_,E,m);return I.__returned=I}else{let I=this.#e[_];if(this.#t(I)){let z=n&&I.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",z&&(S.returnedStale=!0)),z?I.__staleWhileFetching:I.__returned=I}let R=this.#p(_);if(!y&&!R)return S&&(S.fetch="hit"),this.#I(_),s&&this.#_(_),S&&this.#E(S,_),I;let N=this.#C(e,_,E,m),F=N.__staleWhileFetching!==void 0&&n;return S&&(S.fetch=R?"stale":"refresh",F&&R&&(S.returnedStale=!0)),F?N.__staleWhileFetching:N.__returned=N}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,i=this.#s.get(e);if(i!==void 0){let c=this.#e[i],u=this.#t(c);return o&&this.#E(o,i),this.#p(i)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.delete(e),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#I(i),s&&this.#_(i),c))}else o&&(o.get="miss")}#B(e,r){this.#f[r]=e,this.#d[e]=r}#I(e){e!==this.#i&&(e===this.#a?this.#a=this.#d[e]:this.#B(this.#f[e],this.#d[e]),this.#B(this.#i,e),this.#i=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#s.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#T(n);let s=this.#e[n];this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,e,"delete"),this.#u&&this.#o?.push([s,e,"delete"])),this.#s.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#i?this.#i=this.#f[n]:n===this.#a?this.#a=this.#d[n]:(this.#d[this.#f[n]]=this.#d[n],this.#f[this.#d[n]]=this.#f[n]),this.#n--,this.#y.push(n)}}if(this.#u&&this.#o?.length){let n=this.#o,s;for(;s=n?.shift();)this.#h?.(...s)}return r}clear(){for(let e of this.#P({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#v&&this.#w?.(r,n,"delete"),this.#u&&this.#o?.push([r,n,"delete"])}}if(this.#s.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#g&&this.#S&&(this.#g.fill(0),this.#S.fill(0)),this.#x&&this.#x.fill(0),this.#a=0,this.#i=0,this.#y.length=0,this.#m=0,this.#n=0,this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}};var R0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new A0({max:1e5,ttl:e*1e3})}cache;async set(e,r){try{this.cache.set(e,r)}catch{}}async get(e){return this.cache.get(e)}};j0();ht();var qd=class t{static _singleton;cache;constructor(e){this.cache=e||new R0(600)}static get singleton(){return t._singleton===void 0&&(t._singleton=new t),t._singleton}static async verifySignatures(e,r){return await t.singleton.verifySignatures(e,r)}async verifySignatures(e,r){let n=[];for(let s of e.signatures){let a,o=Te.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new ne("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new ne("GeneralJwsVerifierMissingAlg","JWS protected header is missing required 'alg' property");let u=`${s.protected}.${e.payload}.${s.signature}`,d=await this.cache.get(u);if(d===void 0){let f=await t.getPublicKey(i,r);a=await vt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=vt.extractDid(i);if(a)n.push(l);else throw new ne("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=vt.extractDid(e),{didDocument:s}=await r.resolve(n),{verificationMethod:a=[]}=s||{},o;for(let c of a)if(e.endsWith(c.id)){o=c;break}if(!o)throw new ne("GeneralJwsVerifierGetPublicKeyNotFound","public key needed to verify signature not found in DID Document");Kc("JwkVerificationMethod",o);let{publicKeyJwk:i}=o;return i}};bi();ht();async function dn(t,e,r){if(t===void 0)throw new ne("AuthenticateJwsMissing","Missing JWS.");if(await qd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await qd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await xt.parse(t.authorDelegatedGrant);await qd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await xt.parse(t.ownerDelegatedGrant);await qd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await qd.verifySignatures(r,e)}w();var cg=class{_protocols=new Map;register(e){this._protocols.set(e.uri,e)}get(e){return this._protocols.get(e)}getDefinition(e){return this._protocols.get(e)?.definition}has(e){return this._protocols.has(e)}all(){return[...this._protocols.values()]}mapErrorToStatusCode(e){for(let r of this._protocols.values()){let n=r.mapErrorToStatusCode?.(e);if(n!==void 0)return n}}};zE();w();var dg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Hc();w();w();Na();or();var xn=class{_message;get message(){return this._message}_signer;get signer(){return this._signer}_author;get author(){return this._author}_signaturePayload;get signaturePayload(){return this._signaturePayload}get isSignedByAuthorDelegate(){return we.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=we.getSigner(e),e.authorization.authorDelegatedGrant!==void 0?this._author=we.getSigner(e.authorization.authorDelegatedGrant):this._author=this._signer,this._signaturePayload=vt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var Jl=class t extends xn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Count",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter)};Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};w();Al();or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var Zl=class t extends xn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new ne("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Hd();zp();w();or();w();function ut(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}w();Hd();hn();w();Xt();Mv();w();w();var jo=class{static maxDataSizeAllowedToBeEncoded=3e4};hn();wa();or();pa();w();hn();or();ht();var ug=class t{id;requester;description;delegated;scope;conditions;static parse(e){return t.validateMessage(e),new t(e)}static validateMessage(e){if(e.encodedData===void 0||e.encodedData===null)throw new ne("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(we.getSigner(e)===void 0)throw new ne("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(Te.base64UrlToObject(e.encodedData).scope===void 0)throw new ne("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=we.getSigner(e);let r=e.encodedData,n=Te.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};On();bi();Hs();j0();ht();Xt();Ro();var Ir=class t{static uri="https://identity.foundation/dwn/permissions";static requestPath="request";static grantPath="grant";static revocationPath="grant/revocation";static definition={published:!0,protocol:t.uri,types:{request:{dataFormats:["application/json"]},grant:{dataFormats:["application/json"]},revocation:{dataFormats:["application/json"]}},structure:{request:{$size:{max:1e4},$actions:[{who:"anyone",can:["create"]}]},grant:{$size:{max:1e4},$actions:[{who:"recipient",of:"grant",can:["read"]}],revocation:{$size:{max:1e4},$actions:[{who:"anyone",can:["read"]}]}}}};get uri(){return t.uri}get definition(){return t.definition}validateRecord(e,r){t.validateSchema(e,r)}async preProcessWrite(e,r,n){if(r.descriptor.protocolPath!==t.revocationPath)return;let s=r.descriptor.parentId,a=await t.fetchGrant(e,n,s),o=r.descriptor.tags?.protocol,i="protocol"in a.scope?a.scope.protocol:void 0;if(i!==o)throw new ne("PermissionsProtocolValidateRevocationProtocolTagMismatch",`Revocation protocol ${o} does not match grant protocol ${i}`)}async postProcessWrite(e,r,n){if(r.message.descriptor.protocolPath!==t.revocationPath)return;let a={permissionGrantId:r.message.descriptor.parentId,dateCreated:{gte:r.message.descriptor.messageTimestamp}},{messages:o}=await n.messageStore.query(e,[a]);if(o.length===0)return;for(let c of o)if(c.descriptor.method==="Write"){let u=c;u.descriptor.dataSize>jo.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>we.getCid(c)));await n.stateIndex.delete(e,i),await Promise.all(i.map(c=>n.messageStore.delete(e,c)))}mapErrorToStatusCode(e){if(e.startsWith("PermissionsProtocolValidate"))return 400}constructAdditionalMessageFilter(e){let{protocol:r,messageTimestamp:n}=e;if(r===void 0)return;let s={protocol:t.uri,..._e.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Gt.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return Te.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateRequestRecordsScopeMissingProtocol","Permission request for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await xt.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRequestData:n,permissionRequestBytes:a,dataEncodedMessage:i}}static async createGrant(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateGrantRecordsScopeMissingProtocol","Permission grants for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={dateExpires:e.dateExpires,requestId:e.requestId,description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await xt.create({signer:e.signer,messageTimestamp:e.dateGranted,dateCreated:e.dateGranted,recipient:e.grantedTo,protocol:t.uri,protocolPath:t.grantPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionGrantData:n,permissionGrantBytes:a,dataEncodedMessage:i}}static async createRevocation(e){let r={description:e.description},n=e.grant.id,s;this.hasProtocolScope(e.grant.scope)&&(s={protocol:hi(e.grant.scope.protocol)});let a=Te.objectToBytes(r),o=await xt.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=Te.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Kc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Kc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Kc("PermissionRevocationData",s);else throw new ne("PermissionsProtocolValidateSchemaUnexpectedRecord",`Unexpected permission record: ${e.descriptor.protocolPath}`)}static async fetchGrant(e,r,n){let s={recordId:n,isLatestBaseState:!0},{messages:a}=await r.query(e,[s]),o=a[0],i=o?.descriptor.interface,c=o?.descriptor.method;if(i!=="Records"||c!=="Write"||o.descriptor.protocolPath!==t.grantPath)throw new ne("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Xr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new ne("PermissionsProtocolGetScopeInvalidProtocol",`Unexpected protocol for permission record: ${n.descriptor.protocol}`);return n.descriptor.protocolPath===t.revocationPath?(await t.fetchGrant(e,r,n.descriptor.parentId)).scope:n.descriptor.protocolPath===t.grantPath?Xr.parse(n).scope:ug.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=hi(r.protocol)),r}static isRecordPermissionScope(e){return e.interface==="Records"}static hasProtocolScope(e){return"protocol"in e&&e.protocol!==void 0}static validateTags(e,r){if(e.descriptor.tags===void 0||e.descriptor.tags.protocol===void 0)throw new ne("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new ne("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(Fn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new ne("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};On();bi();ht();var wu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await no.performBaseValidation({incomingMessage:r,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i});let c=o.scope;await t.verifyScope(s,n,c,i)}static async authorizeSubscribeOrSync(e){let{incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;if(await no.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),Ir.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${c.descriptor.protocol} does not match the scoped protocol ${i}`)}else{let c=r;for(let u of c.descriptor.filters)if(u.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${u.protocol} does not match the scoped protocol ${i}`)}}}static async verifyScope(e,r,n,s){if(n.protocol!==void 0){if(r.descriptor.interface==="Records"){let a=r,o=_e.isRecordsWrite(a)?a:await xt.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===Ir.uri){let i=await Ir.getScopeFromPermissionRecord(e,s,o);if(Ir.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new ne("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};w();Hc();or();Hs();ht();Xt();var Yl=class t extends xn{static async parse(e){return we.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{signer:r,permissionGrantId:n}=e,s={interface:"Messages",method:"Read",messageCid:e.messageCid,messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),...n!==void 0&&{permissionGrantId:n}},a=await we.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Dr.parseCid(e)}catch{throw new ne("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};On();ht();var bb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Yl.parse(r)}catch(o){return ut(o,400)}try{await dn(r.authorization,this.deps.didResolver)}catch(o){return ut(o,401)}let s=await this.deps.messageStore.get(e,r.descriptor.messageCid);if(s===void 0)return{status:{code:404,detail:"Not Found"}};try{await t.authorizeMessagesRead(e,n,s,this.deps.messageStore)}catch(o){return ut(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(_e.isRecordsWrite(s)){let o=a.message;if(o.encodedData!==void 0){let i=Te.base64UrlToBytes(o.encodedData);a.data=rs.fromBytes(i),delete o.encodedData}else{let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}}return{status:{code:200,detail:"OK"},entry:a}}static async authorizeMessagesRead(e,r,n,s){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let a=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await wu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new ne("MessagesReadAuthorizationFailed","protocol message failed authorization")}};w();or();w();wa();Ro();ms();var Pb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol!==void 0?hi(n.protocol):void 0,a={...n,protocol:s};Ft(a),Il(a)||r.push(a)}return r}static convertFilters(e,r){let n=[];for(let s of e){if(r!==void 0)for(let a of r.all()){let o=a.constructAdditionalMessageFilter?.(s);o!==void 0&&n.push(o)}if(n.push(this.convertFilter(s)),(s.protocolPathPrefix!==void 0||s.contextIdPrefix!==void 0)&&s.protocol!==void 0){let a={interface:"Protocols",method:"Configure",protocol:s.protocol};if(s.messageTimestamp!==void 0){let o=Gt.convertRangeCriterion(s.messageTimestamp);o&&(a.messageTimestamp=o)}n.push(a)}}return n}static convertFilter(e){let r={...e},{messageTimestamp:n,protocolPathPrefix:s,contextIdPrefix:a}=e,o=n?Gt.convertRangeCriterion(n):void 0;return o&&(r.messageTimestamp=o,delete r.dateUpdated),s!==void 0&&(delete r.protocolPathPrefix,r.protocolPath={gte:s,lt:s+"/\uFFFF"}),a!==void 0&&(delete r.contextIdPrefix,r.contextId={gte:a,lt:a+"/\uFFFF"}),r}};w();or();ms();Hs();Ro();Xt();var Ql=class t extends xn{static async parse(e){we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&Fn(r.protocol);return yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=yt.getCurrentTimestamp(),n={interface:"Messages",method:"Subscribe",filters:e.filters??[],messageTimestamp:e.messageTimestamp??r,permissionGrantId:e.permissionGrantId,cursor:e.cursor};Ft(n);let{permissionGrantId:s,signer:a}=e,o=await we.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return we.validateJsonSchema(i),new t(i)}};ht();var xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Ql.parse(r)}catch(u){return ut(u,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ut(u,401)}let{filters:a,cursor:o}=r.descriptor,i=Pb.convertFilters(a,this.deps.coreProtocols),c=await we.getCid(r);try{let u=await this.deps.eventLog.subscribe(e,c,n,{cursor:o,filters:i});return{status:{code:200,detail:"OK"},subscription:u}}catch(u){if(u instanceof ne&&u.code==="EventLogProgressGap"){let d=u.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:d!==void 0?{code:"ProgressGap",...d}:void 0}}return ut(u,500)}}static async authorizeMessagesSubscribe(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await wu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSubscribeAuthorizationFailed","message failed authorization")}};w();hn();bu();w();or();ms();Hs();Ro();Xt();var fg=class t extends xn{static async parse(e){return we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&Fn(e.descriptor.protocol),new t(e)}static async create(e){let r={interface:"Messages",method:"Sync",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),action:e.action,protocol:e.protocol,prefix:e.prefix,permissionGrantId:e.permissionGrantId,hashes:e.hashes,depth:e.depth};Ft(r);let{permissionGrantId:n,signer:s}=e,a=await we.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return we.validateJsonSchema(o),new t(o)}};ht();var xZ=jo.maxDataSizeAllowedToBeEncoded,Sb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fg.parse(r)}catch(i){return ut(i,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ut(i,401)}let{action:s,protocol:a,prefix:o}=r.descriptor;try{switch(s){case"root":{let i=a!==void 0?await this.deps.stateIndex.getProtocolRoot(e,a):await this.deps.stateIndex.getRoot(e);return{status:{code:200,detail:"OK"},root:Jn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i):await this.deps.stateIndex.getSubtreeHash(e,i);return{status:{code:200,detail:"OK"},hash:Jn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolLeaves(e,a,i):await this.deps.stateIndex.getLeaves(e,i);return{status:{code:200,detail:"OK"},entries:c}}case"diff":return this.handleDiff(e,r);default:return{status:{code:400,detail:`Unknown action: ${s}`}}}}catch(i){return ut(i,500)}}async handleDiff(e,r){let{protocol:n,hashes:s,depth:a}=r.descriptor;if(!s||a===void 0)return{status:{code:400,detail:"diff action requires hashes and depth"}};let o=this.deps.stateIndex,i=[],c=[],u=await this.getDefaultHashHex(a),d=new Set;for(let[h,p]of Object.entries(s))p!==u&&d.add(h);let l=await this.collectSubtreeHashes(e,n,a);for(let h of Object.keys(l))d.add(h);for(let h of d){let p=s[h],m=l[h];if(p===m)continue;if(m===void 0){c.push(h);continue}if(p===void 0){let v=t.parseBitPrefix(h),E=n!==void 0?await o.getProtocolLeaves(e,n,v):await o.getLeaves(e,v);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n!==void 0?await o.getProtocolLeaves(e,n,y):await o.getLeaves(e,y);i.push(...S),c.push(h)}let f=await this.buildDiffEntries(e,i);return{status:{code:200,detail:"OK"},onlyRemote:f,onlyLocal:c}}async collectSubtreeHashes(e,r,n){let s=this.deps.stateIndex,a={},o=await this.getDefaultHashHex(n),i=async(c,u)=>{let d=t.parseBitPrefix(c),l=r!==void 0?await s.getProtocolSubtreeHash(e,r,d):await s.getSubtreeHash(e,d),f=Jn(l);if(f!==o){if(u>=n){a[c]=f;return}await Promise.all([i(c+"0",u+1),i(c+"1",u+1)])}};return await i("",0),a}_defaultHashHexCache;async getDefaultHashHex(e){if(this._defaultHashHexCache===void 0){let{initDefaultHashes:r}=await Promise.resolve().then(()=>(bu(),wO)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Jn(n[s]))}return this._defaultHashHexCache.get(e)??""}async buildDiffEntries(e,r){let n=[];for(let s of r){let{message:a,encodedData:o,data:i}=await this.readMessageByCid(e,s);if(!a)continue;let c={messageCid:s,message:a};if(o)c.encodedData=o;else if(i){let u=await t.streamToBytes(i);u.byteLength<=xZ&&(c.encodedData=Te.bytesToBase64Url(u))}n.push(c)}return n}async readMessageByCid(e,r){let n=await this.deps.messageStore.get(e,r);if(!n)return{};let s;"encodedData"in n&&(s=n.encodedData,delete n.encodedData);let a;if(n.descriptor.interface==="Records"&&n.descriptor.method==="Write"){let o=n.descriptor?.dataCid;if(o&&this.deps.dataStore){let i=n.descriptor?.recordId;if(i){let c=await this.deps.dataStore.get(e,i,o);c?.dataStream&&(a=c.dataStream)}}}return{message:n,encodedData:s,data:a}}static async streamToBytes(e){let r=e.getReader(),n=[],s=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;n.push(c),s+=c.byteLength}let a=new Uint8Array(s),o=0;for(let i of n)a.set(i,o),o+=i.byteLength;return a}static parseBitPrefix(e){if(!/^[01]*$/.test(e))throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: length must be <= 256, got: ${e.length}`);return Array.from(e,r=>r==="1")}static async authorizeMessagesSync(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await wu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSyncAuthorizationFailed","message failed authorization")}};w();or();w();var fN=Ln(nI(),1);or();pa();w();Mv();ht();var Au=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await no.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:s,permissionGrant:a,messageStore:o}=e;await no.performBaseValidation({incomingMessage:s,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:o});let c=a.scope.protocol,u=s.descriptor.filter?.protocol;if(c!==void 0&&u!==c)throw new ne("ProtocolsGrantAuthorizationQueryProtocolScopeMismatch",`Grant protocol scope ${c} does not match protocol in message ${u}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ne("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};Hs();ht();Xt();w();Lp();zp();function Ni(t){let e=t.indexOf(":");if(e===-1)return;let r=t.substring(0,e),n=t.substring(e+1);return{alias:r,protocolPath:n}}function hf(t){return t.includes(":")}function s1(t){return t.split("/").slice(-1)[0]}function fd(t,e){let r=t.split("/"),n,s=e;for(let a of r){if(!Object.hasOwn(s,a))return;n=s[a],s=n}return n}var sI=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let s=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let u=r,d=["protocolPath",e.protocol];async function l(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await l(y,m);continue}let S=await u.derivePublicKey(m);y.$encryption={rootKeyId:u.rootKeyId,publicKeyJwk:S},await l(y,m)}}return await l(s.structure,d),s}let a=r;async function o(u,d){for(let l in u)if(!l.startsWith("$")){let f=await Ja.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await vn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Ja.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ro();var pd=class t extends xn{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Configure",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),definition:t.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await we.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),s={descriptor:r,authorization:n};return we.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await Au.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:s}=e;Fn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Qa(o)}s!==void 0&&t.validateUses(s,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let s in e){if(!n.test(s))throw new ne("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{Fn(e[s])}catch{throw new ne("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new ne("ProtocolsConfigureInvalidUsesSelfReference",`'uses' alias '${s}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),s=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:s,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ne("ProtocolsConfigureRecordNestingDepthExceeded","Record nesting depth exceeded 10 levels.");for(let s in r){if(s.startsWith("$"))continue;let a=r[s],o;e===""?o=s:o=`${e}/${s}`,a.$role?n.push(o):t.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:s,roles:a,uses:o,types:i}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new ne("ProtocolsConfigureInvalidRefNotAtRoot",`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);t.validateRefNode(r,n,o)}if(r.$size!==void 0){let{min:u=0,max:d}=r.$size;if(d!==void 0&&d<u)throw new ne("ProtocolsConfigureInvalidSize",`Invalid size range found: max limit ${d} less than min limit ${u} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:u,strategy:d}=r.$recordLimit;if(!Number.isInteger(u)||u<1)throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(dm);if(!l.includes(d))throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new fN.default.default,{$allowUndefinedTags:d,$requiredTags:l,...f}=r.$tags;for(let h in f){let p=f[h];if(!u.validateSchema(p)){let m=u.errorsText(u.errors,{dataVar:`${n}/$tags/${h}`});throw new ne("ProtocolsConfigureInvalidTagSchema",`tags schema validation error: ${m}`)}}}let c=r.$actions??[];for(let u=0;u<c.length;u++){let d=c[u];if(d.role!==void 0){if(hf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ne("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne("ProtocolsConfigureInvalidActionOfNotAllowed",`'of' is not allowed at rule set protocol path (${n})`);if(d.who==="recipient"&&d.of===void 0&&d.can.some(f=>!["co-update","co-delete","co-prune"].includes(f)))throw new ne("ProtocolsConfigureInvalidRecipientOfAction","Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who==="author"&&!d.of)throw new ne("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(hf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionUpdateWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes("delete")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionDeleteWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes("prune")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionPruneWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let l=u+1;l<c.length;l++){let f=c[l];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ne("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ne("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let u=n.split("/").pop();i[u]?.encryptionRequired===!0&&c.some(f=>f.who==="anyone"&&f.can.includes("read"))&&console.warn(`ProtocolsConfigure: type '${u}' 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.`)}r.$delivery!==void 0&&(r.$actions===void 0||r.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${r.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),r.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes("update")||d.can.includes("co-update"))&&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 u in r){if(u.startsWith("$"))continue;let d=r[u];if(d.$ref===void 0&&!s.includes(u))throw new ne("ProtocolsConfigureInvalidRuleSetRecordType",`Rule set ${u} is not declared as an allowed type in the protocol definition.`);let l;n===""?l=u:l=`${n}/${u}`,t.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:l,recordTypes:s,roles:a,uses:o,types:i})}}static validateRefNode(e,r,n){let s=e.$ref,a=Ni(s);if(a===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${a.alias}' at protocol path '${r}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let i of o)if(e[i]!==void 0)throw new ne("ProtocolsConfigureInvalidRefNodeHasDirectives",`'$ref' node at protocol path '${r}' must not have '${i}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,s){let a=Ni(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r===void 0||r[a.alias]===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let s in e.types)r[s]={...e.types[s]};for(let s in r){let a=r[s].schema;a!==void 0&&(r[s].schema=Cl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=hi(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:hi(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ht();Xt();var i1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await pd.parse(r)}catch(d){return ut(d,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return ut(d,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(d){return ut(d,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getCid(r);for(let d of a)if(await we.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let i=await we.getNewestMessage(a),c=!1;(i===void 0||await we.isNewer(r,i))&&(c=!0,i=r);let u;if(c){let d=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},d,l),u={status:{code:202,detail:"Accepted"}}}else{let d=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),u={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==i){let l=await pd.parse(d),f=t.constructIndexes(l,!1),h=await we.getCid(d);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,d,f)}return u}static constructIndexes(e,r){let{definition:n,...s}=e.message.descriptor,{author:a}=e;return{...s,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:r}}static async authorizeProtocolsConfigure(e,r,n){if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Au.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("ProtocolsConfigureAuthorizationFailed","message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:s}=r;if(s===void 0)return;let a=new Map;for(let o in s){let i=s[o],c=await t.fetchInstalledProtocolDefinition(e,i,n);if(c===void 0)throw new ne("ProtocolsConfigureComposedProtocolNotInstalled",`composed protocol '${i}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let s={interface:"Protocols",method:"Configure",protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[s]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let s in e){if(s.startsWith("$"))continue;let a=e[s],o=r===""?s:`${r}/${s}`;if(a.$ref!==void 0){let c=Ni(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),l=u.structure;for(let f=0;f<d.length;f++){let h=d[f],p=l[h];if(p===void 0)throw new ne("ProtocolsConfigureInvalidRefProtocolPath",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${u.protocol}'.`);if(p.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne("ProtocolsConfigureInvalidRefTargetThroughRef",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${u.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}l=p}}}let i=a.$actions??[];for(let c of i){if(c.role!==void 0){let u=Ni(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let l=fd(u.protocolPath,d.structure);if(l===void 0||!l.$role)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Ni(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(fd(u.protocolPath,d.structure)===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,o,n)}}};w();ht();w();or();ms();Hs();ht();Xt();Ro();var mf=class t extends xn{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&Fn(e.descriptor.filter.protocol),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Ft(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return we.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:hi(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Ir.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Au.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ne("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};ms();Xt();var o1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await mf.parse(r)}catch(o){return ut(o,400)}try{await dn(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code==="AuthenticateJwsMissing"||o.code==="ProtocolsQueryUnauthorized"||o.code==="ProtocolsGrantAuthorizationQueryProtocolScopeMismatch"){let i=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:i}}else return ut(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};Ft(s);let{messages:a}=await this.deps.messageStore.query(e,[s]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:"Protocols",method:"Configure",published:!0,isLatestBaseState:!0},{messages:s}=await this.deps.messageStore.query(e,[n]);return s}};w();or();w();Ya();ht();Xt();w();wa();bi();ht();Xt();async function Fg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(hf(c)){let p=Ni(c);if(p===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses===void 0||s.uses[p.alias]===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role alias '${p.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);u=s.uses[p.alias],d=p.protocolPath;let m=await o(t,u,a,i),y=fd(d,m.structure);if(y===void 0||!y.$role)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else{let p=fd(c,s.structure);if(p===void 0||!p.$role)throw new ne("ProtocolAuthorizationNotARole",`Protocol path ${c} does not match role record type.`)}let l={interface:"Records",method:"Write",protocol:u,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Gt.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new ne("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function Zre(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await xt.fetchInitialRecordsWrite(r,t,s);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push("co-prune"),e.author===a.author&&o.push("prune")):(o.push("co-delete"),e.author===a.author&&o.push("delete")),o;case"Count":return["read"];case"Query":return["read"];case"Read":return["read"];case"Subscribe":return["read"];case"Write":let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?["squash","create"]:["create"];{let u=e.message.recordId,d=await xt.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Gg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await Zre(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new ne("ProtocolAuthorizationActionRulesNotFound",`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let l of u){if(!l.can.some(p=>i.includes(p)))continue;if(l.who==="anyone")return;if(c===void 0)continue;if(d!==void 0){if(l.role===d)return;continue}if(l.who==="recipient"&&l.of===void 0){let p;if(e.message.descriptor.method==="Write"?p=e.message:p=n[n.length-1],p.descriptor.recipient===c)return;continue}if(await Yre(c,l,n,a))return}throw new ne("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Yre(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(hf(s)&&n?.uses!==void 0){let o=Ni(s);if(o!==void 0){let i=n.uses[o.alias];i!==void 0&&(a=r.find(c=>c.descriptor.protocol===i&&c.descriptor.protocolPath===o.protocolPath))}}else a=r.find(o=>o.descriptor.protocolPath===s);if(a===void 0)return!1;if(e.who==="recipient")return t===a.descriptor.recipient;{let o=(await xt.parse(a)).author;return t===o}}w();bi();ht();Xt();async function Rh(t,e,r){let n={interface:"Records",method:"Write",recordId:e},{messages:s}=await r.query(t,[n]);return s.length===0?void 0:await xt.getInitialWrite(s)}async function Wg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Rh(t,s,r);if(a===void 0)throw new ne("ProtocolAuthorizationParentNotFoundConstructingRecordChain",`Unexpected error that should never trigger: no parent found with ID ${s} when constructing record chain.`);n.push(a),s=a.descriptor.parentId}return n.reverse()}async function iI(t,e,r){let n=await Rh(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}w();var pN=Ln(nI(),1);wa();On();ht();Xt();async function hN(t,e,r,n,s){let a=e.message.descriptor.protocolPath,o=s1(a),i=e.message.descriptor.parentId;if(i===void 0){if(a!==o)throw new ne("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await Qre(t,c,a,r,n,s),d={isLatestBaseState:!0,interface:"Records",method:"Write",protocol:u,recordId:i},{messages:l}=await r.query(t,[d]),f=l[0];if(f===void 0)throw u!==c?new ne("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Qre(t,e,r,n,s,a){let o=r.split("/");if(o.length<=1)return e;let i=await s(t,e,n,a),c=i.structure[o[0]];if(c?.$ref!==void 0){let u=Ni(c.$ref);if(u!==void 0&&i.uses!==void 0){let d=i.uses[u.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function mN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=s1(o),c=await Xre(t,o,r,n,s,a);ene(e,c,i)}async function Xre(t,e,r,n,s,a){let o=e.split("/"),i=r.structure[o[0]];if(i?.$ref!==void 0&&o.length===1){let c=Ni(i.$ref);if(c!==void 0&&r.uses!==void 0){let u=r.uses[c.alias];if(u!==void 0)return(await s(t,u,n,a)).types}}return r.types}function ene(t,e,r){let n=r??s1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne("ProtocolAuthorizationInvalidType",`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=t.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ne("ProtocolAuthorizationInvalidSchema",`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:i}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(i))throw new ne("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ne("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function yN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new ne("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new ne("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function gN(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:s}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...i}=e.$tags,c=a||!1,u=o||[],d=new pN.default.default,l=d.compile({type:"object",properties:i,required:u,additionalProperties:c});if(!l(r)){let h=d.errorsText(l.errors,{dataVar:`${n}/${s}/$tags`});throw new ne("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function wN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new ne("ProtocolAuthorizationRoleMissingRecipient","Role records must have a recipient");let o=s.message.descriptor.protocolPath,i={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:s.message.descriptor.protocol,protocolPath:o,recipient:a},c=_e.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Gt.constructPrefixFilterAsRangeFilter(c);i.contextId=f}let{messages:u}=await n.query(t,[i]);if(u.filter(f=>f.recordId!==s.message.recordId).length>0)throw new ne("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function vN(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=r.$recordLimit,i=e.message.descriptor.protocolPath,c={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:i},u=_e.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Gt.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new ne("ProtocolAuthorizationRecordLimitExceeded",`record limit of ${a} reached at protocol path '${i}'${u!==""?` under parent context '${u}'`:""}: new records are rejected until existing records are deleted.`):new ne("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function bN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne("ProtocolAuthorizationSquashNotEnabled",`squash writes are not enabled at protocol path '${t.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await t.isInitialWrite())throw new ne("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function PN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ne("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Qs=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await iI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await mN(e,r.message,o,n,i,a),await hN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await wN(e,r,c,n),yN(r,c),gN(r,c),await PN(r,c),await bN(r,c),await vN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Rh(e,r.message.recordId,n),o;a===void 0?o=await Wg(e,r.message.descriptor.parentId,n):o=await Wg(e,r.message.recordId,n);let i=await iI(e,r,n),c=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,i,s),u=t.getRuleSet(r.message.descriptor.protocolPath,c),d=t.createBoundFetchDefinition(s);await Fg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Gg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Wg(e,n.message.recordId,s),i=await Rh(e,n.message.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await Fg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Gg(e,r,d,o,s,u)}static async authorizeQueryOrSubscribe(e,r,n,s){let{protocol:a,protocolPath:o,contextId:i}=r.message.descriptor.filter,c=await t.fetchProtocolDefinition(e,a,n,void 0,s),u=t.getRuleSet(o,c),d=t.createBoundFetchDefinition(s);await Fg(e,r,a,i,c,n,d),await Gg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Wg(e,r.message.descriptor.recordId,s),i=await Rh(e,r.message.descriptor.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await Fg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Gg(e,r,d,o,s,u)}static async fetchProtocolDefinition(e,r,n,s,a){if(a!==void 0){let u=a.getDefinition(r);if(u!==void 0)return u}let o={interface:"Protocols",method:"Configure",protocol:r};s!==void 0?o.messageTimestamp={lte:s}:o.isLatestBaseState=!0;let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new ne("ProtocolAuthorizationProtocolNotFound",`unable to find protocol definition for ${r}`);return i[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,s,a)=>t.fetchProtocolDefinition(r,n,s,a,e)}static getRuleSet(e,r){let n=fd(e,r.structure);if(n===void 0)throw new ne("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};On();Xt();var a1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(a){return ut(a,400)}let s;if(_e.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ut(a,401)}n.author===e?s=await this.countRecordsAsOwner(e,n):s=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:s}}async countRecordsAsOwner(e,r){let{filter:n}=r.message.descriptor,s={..._e.convertFilter(n),interface:"Records",method:"Write",isLatestBaseState:!0};return this.deps.messageStore.count(e,[s])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,s=[];return _e.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),_e.filterIncludesUnpublishedRecords(n)&&(_e.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),_e.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),_e.shouldBuildUnpublishedRecipientFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,s)}async countPublishedRecords(e,r){let n=t.buildPublishedRecordsFilter(r);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Xt();or();On();w();or();pa();On();Xa();ms();Hs();Xt();var hd=class t extends xn{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=yt.getCurrentTimestamp(),s={interface:"Records",method:"Delete",messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),new t(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u}=e.descriptor,d={isLatestBaseState:!0,protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u,contextId:e.contextId,author:this.author,...n};return Ft(d),d}async authorizeDelegate(e,r){let n=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Xa();bi();w();var c1=class t{constructor(e,r){this.resumableTaskStore=e;this.resumableTaskHandlers={RecordsDelete:async n=>await r.performRecordsDelete(n),RecordsSquash:async n=>await r.performRecordsSquash(n)}}static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;async run(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,r);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,r)},t.timeoutExtensionFrequencyInSeconds*1e3);let s=this.resumableTaskHandlers[e.task.name];await s(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{t.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 r=e;for(;r.length>0;){let n=r;r=[];for(let s of n)try{await this.runWithAutomaticTimeoutExtension(s)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",s),r.push(s)}}}};var d1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hd.parse(r)}catch(u){return ut(u,400)}try{await dn(r.authorization,this.deps.didResolver)}catch(u){return ut(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getNewestMessage(a);if(!_e.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await xt.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ut(u,401)}return await this.deps.resumableTaskManager.run({name:"RecordsDelete",data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,s,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await kn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:s})}else await Qs.authorizeDelete(e,r,n,s,a)}};w();Al();or();On();bi();Ya();Xt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ut(o,400)}let s,a;if(_e.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);s=o.messages,a=o.cursor}else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ut(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);s=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);s=o.messages,a=o.cursor}}for(let o of s)if(!await xt.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:s,cursor:a}}convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:s,pagination:a}=r.message.descriptor,o={..._e.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0},i=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],i,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:s,filter:a}=r.message.descriptor,o=[];_e.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),_e.filterIncludesUnpublishedRecords(a)&&(_e.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),_e.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),_e.shouldBuildUnpublishedRecipientFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let i=this.convertDateSort(n);return this.deps.messageStore.query(e,o,i,s)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:s}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,s)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Hd();hn();or();On();Xa();w();Al();or();pa();On();Xa();ms();Hs();ht();Xt();var Vg=class t extends xn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsReadParseFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:s,protocolRole:a,dateSort:o}=e,i=yt.getCurrentTimestamp();if(e.filter.published===!1&&(o==="publishedAscending"||o==="publishedDescending"))throw new ne("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:_e.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};Ft(c);let u;n!==void 0&&(u=await we.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return we.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};bi();ht();Xt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Vg.parse(r)}catch(l){return ut(l,400)}try{n.author!==void 0&&await dn(r.authorization,this.deps.didResolver)}catch(l){return ut(l,401)}let s={interface:"Records",isLatestBaseState:!0,..._e.convertFilter(r.descriptor.filter)},a=_e.convertDateSort(r.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[s],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let i=o[0];if(i.descriptor.method==="Delete"){let l=i,f=l.descriptor.recordId,h=await xt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ut(new ne("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await xt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await xt.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ut(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await xt.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ut(l,401)}let u;if(c.encodedData!==void 0){let l=Te.base64UrlToBytes(c.encodedData);u=rs.fromBytes(l),delete c.encodedData}else{let l=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(l?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};u=l.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await xt.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,r,n,s,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s);let{descriptor:o}=n.message;if(r.author!==e){if(o.published===!0)return;if(r.author!==void 0&&(r.author===o.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await kn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:s})}else await Qs.authorizeRead(e,r,n,s,a)}}};w();Al();or();On();w();or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var yf=class t extends xn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Subscribe",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};bi();Ya();ht();Xt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await yf.parse(r)}catch(f){return ut(f,400)}let a=[],o=[];if(_e.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ut(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await we.getCid(r),{cursor:c}=s.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,i,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code==="EventLogProgressGap"){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h!==void 0?{code:"ProgressGap",...h}:void 0}}return ut(f,500)}let u=await this.deps.eventLog.subscribe(e,i,n,{filters:a}),d,l;try{let{dateSort:f,pagination:h}=s.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);d=m.messages,l=m.cursor;for(let y of d)if(!await xt.isInitialWrite(y)){let v=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete v.encodedData,y.initialWrite=v}}catch(f){return await u.close(),ut(f,500)}return{status:{code:200,detail:"OK"},subscription:u,entries:d,cursor:l}}static convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{..._e.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return _e.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),_e.filterIncludesUnpublishedRecords(n)&&(_e.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({..._e.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),_e.shouldProtocolAuthorize(e.signaturePayload)&&r.push({..._e.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),_e.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({..._e.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{..._e.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{..._e.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return _e.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),_e.filterIncludesUnpublishedRecords(s)&&(_e.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({..._e.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),_e.shouldProtocolAuthorize(e.signaturePayload)&&r.push({..._e.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),_e.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({..._e.convertFilter(s,n),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Hc();Hd();hn();wa();or();On();Xa();bi();Ya();w();wa();or();On();bi();Xt();var Dh=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:s}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=s}async performRecordsDelete({tenant:e,message:r}){let n={interface:"Records",recordId:r.descriptor.recordId},{messages:s}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(s);if(!_e.canPerformDeleteAgainstRecord(r,a))return;let o=await hd.parse(r),i=await xt.getInitialWrite(s),c=o.constructIndexes(i),u=await we.getCid(r);await this.messageStore.put(e,r,c),await this.stateIndex.insert(e,u,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:i},c,u),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,s,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:s,messageTimestamp:a}=r.descriptor,o={interface:"Records",protocol:n,protocolPath:s},i=_e.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Gt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;_e.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f!==void 0?f.push(d):u.set(l,[d])}for(let[d,l]of u){if(d===r.recordId)continue;let f=await we.getNewestMessage(l);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,l,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,s){if(n.descriptor.method!=="Write")return;let a=n;a.descriptor.dataSize<=jo.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==s.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,s,a){let o={interface:"Records",parentId:r},{messages:i}=await n.query(e,[o]),c=new Map;for(let u of i){let d;_e.isRecordsWrite(u)?d=u.recordId:d=u.descriptor.recordId;let l=c.get(d);l?l.push(u):c.set(d,[u])}for(let u of c.keys())await t.purgeRecordDescendants(e,u,n,s,a);for(let u of c.keys())await t.purgeRecordMessages(e,c.get(u),n,s,a)}static async purgeRecordMessages(e,r,n,s,a){let o=r.filter(u=>u.descriptor.method==="Write"),i=await we.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>we.getCid(u)));await a.delete(e,c),await Promise.all(c.map(u=>n.delete(e,u)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,s,a,o){let i=[];for(let c of r){if(await we.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await we.getCid(c);if(await s.delete(e,d),await xt.isInitialWrite(c)){let p=await(await xt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await we.getCid(c);i.push(f)}}await o.delete(e,i)}}};ht();Xt();var p1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await xt.parse(r),await Qs.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return ut(p,400)}try{await dn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(p){return ut(p,401)}let a={interface:"Records",recordId:r.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),i=await s.isInitialWrite(),c;if(!i)try{c=await xt.getInitialWrite(o),xt.verifyEqualityOfImmutableProperties(c,r)}catch(p){return ut(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return ut(p,409)}let u=await we.getNewestMessage(o),d=!1,l;if(u===void 0||await we.isNewer(r,u)?(d=!0,l=r):l=u,!d){let p=!1;if(u!==void 0&&n!==void 0&&await xt.isInitialWrite(u)){let y=!!u.encodedData,S=this.deps.dataStore?!!await this.deps.dataStore.get(e,s.message.recordId,r.descriptor.dataCid):!1;p=!y&&!S}if(!p)return{status:{code:409,detail:"Conflict"}}}let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(u?.descriptor.method==="Delete")throw new ne("RecordsWriteNotAllowedAfterDelete","RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,r,this.deps.messageStore);let p=!1,m=r;if(n!==void 0)m=await this.processMessageWithDataStream(e,r,n),p=!0;else if(!i){let v=u;m=await this.processMessageWithoutDataStream(e,r,v),p=!0}let y=await s.constructIndexes(p);await this.deps.messageStore.put(e,m,y);let S=await we.getCid(r);await this.deps.stateIndex.insert(e,S,y),this.deps.eventLog!==void 0&&p&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,S)}catch(p){if(p instanceof ne&&(p.code==="RecordsWriteMissingEncodedDataInPrevious"||p.code==="RecordsWriteMissingDataInPrevious"||p.code==="RecordsWriteNotAllowedAfterDelete"||p.code==="RecordsWriteDataCidMismatch"||p.code==="RecordsWriteDataSizeMismatch"||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return ut(p,400);throw p}let h={status:i&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Dh.deleteAllOlderMessagesButKeepInitialWrite(e,o,l,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:"RecordsSquash",data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,s,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=Te.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=jo.maxDataSizeAllowedToBeEncoded){let a=await rs.toBytes(n),o=await Dr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=rs.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Dr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,o)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,i,c.dataSize)}catch(i){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),i}}return s}async processMessageWithoutDataStream(e,r,n){let s={...r},{dataCid:a,dataSize:o}=r.descriptor;if(t.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=jo.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)s.encodedData=n.encodedData;else throw new ne("RecordsWriteMissingEncodedDataInPrevious","No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new ne("RecordsWriteMissingDataInPrevious","No dataStream was provided and unable to get data from previous message");return s}static validateDataIntegrity(e,r,n,s){if(e!==n)throw new ne("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new ne("RecordsWriteDataSizeMismatch",`actual data size ${s} bytes does not match dataSize in descriptor: ${r}`)}async enforceSquashBackstop(e,r){if(r.descriptor.protocol===void 0||r.descriptor.protocolPath===void 0)return;let n;try{n=await Qs.fetchProtocolDefinition(e,r.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,d);return}let s=r.descriptor.protocolPath.split("/"),a=n.structure[s[0]];for(let d=1;d<s.length&&a!==void 0;d++)a=a[s[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=_e.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Gt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:-1},{limit:1});if(c.length===0)return;let u=c[0];if(r.descriptor.messageTimestamp<=u.descriptor.messageTimestamp)throw new ne("ProtocolAuthorizationSquashBackstop",`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${u.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new ne("RecordsWriteOwnerAndTenantMismatch",`Owner ${r.owner} must be the same as tenant ${e} when specified.`);if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.isSignedByOwnerDelegate&&await r.authorizeOwnerDelegate(n),r.owner===void 0){if(r.author===e)return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await kn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Qs.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};w();var rne=Object.create,BI=Object.defineProperty,nne=Object.getOwnPropertyDescriptor,sne=Object.getOwnPropertyNames,ine=Object.getPrototypeOf,one=Object.prototype.hasOwnProperty,zt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),NI=(t,e)=>{for(var r in e)BI(t,r,{get:e[r],enumerable:!0})},ane=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sne(e))!one.call(t,s)&&s!==r&&BI(t,s,{get:()=>e[s],enumerable:!(n=nne(e,s))||n.enumerable});return t},Df=(t,e,r)=>(r=t!=null?rne(ine(t)):{},ane(e||!t||!t.__esModule?BI(r,"default",{value:t,enumerable:!0}):r,t)),cne=zt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),s=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),a=i=>i===1/0||s(i),o=class NU{constructor({max:c=1/0,ttl:u,updateAgeOnGet:d=!1,checkAgeOnGet:l=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,u!==void 0&&!a(u))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=u,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!l,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(c,u){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let l in this.expirations){this.setTimer(l,l-n());break}},u);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==NU.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[u,d]of c)this.dispose(d,u,"delete")}setTTL(c,u=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let l=this.expirations[d];!l||l.length<=1?delete this.expirations[d]:this.expirations[d]=l.filter(f=>f!==c)}if(u!==1/0){let l=Math.floor(n()+u);this.expirationMap.set(c,l),this.expirations[l]||(this.expirations[l]=[],this.setTimer(l,u)),this.expirations[l].push(c)}else this.expirationMap.set(c,1/0)}set(c,u,{ttl:d=this.ttl,noUpdateTTL:l=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){l||this.setTTL(c,d);let h=this.data.get(c);h!==u&&(this.data.set(c,u),f||this.dispose(h,c,"set"))}else this.setTTL(c,d),this.data.set(c,u);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let u=this.expirationMap.get(c);return u===1/0?u:u!==void 0?Math.max(0,Math.ceil(u-n())):0}get(c,{updateAgeOnGet:u=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:l=this.checkAgeOnGet}={}){let f=this.data.get(c);if(l&&this.getRemainingTTL(c)===0){this.delete(c);return}return u&&this.setTTL(c,d),f}dispose(c,u){}delete(c){let u=this.expirationMap.get(c);if(u!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let l=this.expirations[u];return l&&(l.length<=1?delete this.expirations[u]:this.expirations[u]=l.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let u=this.expirations[c];if(this.size-u.length>=this.max){delete this.expirations[c];let d=[];for(let l of u)d.push([l,this.data.get(l)]),this.data.delete(l),this.expirationMap.delete(l);for(let[l,f]of d)this.dispose(f,l,"evict")}else{let d=this.size-this.max,l=[];for(let f of u.splice(0,d))l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let u in this.expirations){if(u==="Infinity"||u>c)return;let d=[...this.expirations[u]||[]],l=[];delete this.expirations[u];for(let f of d)l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let u of this.expirations[c])yield[u,this.data.get(u)]}*keys(){for(let c in this.expirations)for(let u of this.expirations[c])yield u}*values(){for(let c in this.expirations)for(let u of this.expirations[c])yield this.data.get(u)}[Symbol.iterator](){return this.entries()}};e.exports=o}),dne=zt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,s)=>Object.assign(n,s),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}}),_c=zt((t,e)=>{"use strict";e.exports=class extends Error{constructor(r,n){super(r||""),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)}}}),une=zt(t=>{"use strict";t.byteLength=c,t.toByteArray=d,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=s.length;a<o;++a)e[a]=s[a],r[s.charCodeAt(a)]=a;var a,o;r[45]=62,r[95]=63;function i(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 S=y===m?0:4-y%4;return[y,S]}function c(p){var m=i(p),y=m[0],S=m[1];return(y+S)*3/4-S}function u(p,m,y){return(m+y)*3/4-y}function d(p){var m,y=i(p),S=y[0],v=y[1],E=new n(u(p,S,v)),_=0,I=v>0?S-4:S,R;for(R=0;R<I;R+=4)m=r[p.charCodeAt(R)]<<18|r[p.charCodeAt(R+1)]<<12|r[p.charCodeAt(R+2)]<<6|r[p.charCodeAt(R+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return v===2&&(m=r[p.charCodeAt(R)]<<2|r[p.charCodeAt(R+1)]>>4,E[_++]=m&255),v===1&&(m=r[p.charCodeAt(R)]<<10|r[p.charCodeAt(R+1)]<<4|r[p.charCodeAt(R+2)]>>2,E[_++]=m>>8&255,E[_++]=m&255),E}function l(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var S,v=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),v.push(l(S));return v.join("")}function h(p){for(var m,y=p.length,S=y%3,v=[],E=16383,_=0,I=y-S;_<I;_+=E)v.push(f(p,_,_+E>I?I:_+E));return S===1?(m=p[y-1],v.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],v.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),v.join("")}}),lne=zt(t=>{t.read=function(e,r,n,s,a){var o,i,c=a*8-s-1,u=(1<<c)-1,d=u>>1,l=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=c;l>0;o=o*256+e[r+f],f+=h,l-=8);for(i=o&(1<<-l)-1,o>>=-l,l+=s;l>0;i=i*256+e[r+f],f+=h,l-=8);if(o===0)o=1-d;else{if(o===u)return i?NaN:(p?-1:1)*(1/0);i=i+Math.pow(2,s),o=o-d}return(p?-1:1)*i*Math.pow(2,o-s)},t.write=function(e,r,n,s,a,o){var i,c,u,d=o*8-a-1,l=(1<<d)-1,f=l>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:o-1,m=s?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(c=isNaN(r)?1:0,i=l):(i=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-i))<1&&(i--,u*=2),i+f>=1?r+=h/u:r+=h*Math.pow(2,1-f),r*u>=2&&(i++,u/=2),i+f>=l?(c=0,i=l):i+f>=1?(c=(r*u-1)*Math.pow(2,a),i=i+f):(c=r*Math.pow(2,f-1)*Math.pow(2,a),i=0));a>=8;e[n+p]=c&255,p+=m,c/=256,a-=8);for(i=i<<a|c,d+=a;d>0;e[n+p]=i&255,p+=m,i/=256,d-=8);e[n+p-m]|=y*128}}),UI=zt(t=>{"use strict";var e=une(),r=lne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=v,t.INSPECT_MAX_BYTES=50;var s=2147483647;t.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function o(T){if(T>s)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,i.prototype),M}function i(T,M,L){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(T)}return c(T,M,L)}i.poolSize=8192;function c(T,M,L){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return p(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Se(T,ArrayBuffer)||T&&Se(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Se(T,SharedArrayBuffer)||T&&Se(T.buffer,SharedArrayBuffer)))return m(T,M,L);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return i.from(te,M,L);let ae=y(T);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return i.from(T[Symbol.toPrimitive]("string"),M,L);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}i.from=function(T,M,L){return c(T,M,L)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function u(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,L){return u(T),T<=0?o(T):M!==void 0?typeof L=="string"?o(T).fill(M,L):o(T).fill(M):o(T)}i.alloc=function(T,M,L){return d(T,M,L)};function l(T){return u(T),o(T<0?0:S(T)|0)}i.allocUnsafe=function(T){return l(T)},i.allocUnsafeSlow=function(T){return l(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!i.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let L=E(T,M)|0,te=o(L),ae=te.write(T,M);return ae!==L&&(te=te.slice(0,ae)),te}function h(T){let M=T.length<0?0:S(T.length)|0,L=o(M);for(let te=0;te<M;te+=1)L[te]=T[te]&255;return L}function p(T){if(Se(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return h(T)}function m(T,M,L){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(L||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&L===void 0?te=new Uint8Array(T):L===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,L),Object.setPrototypeOf(te,i.prototype),te}function y(T){if(i.isBuffer(T)){let M=S(T.length)|0,L=o(M);return L.length===0||T.copy(L,0,0,M),L}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):h(T);if(T.type==="Buffer"&&Array.isArray(T.data))return h(T.data)}function S(T){if(T>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return T|0}function v(T){return+T!=T&&(T=0),i.alloc(+T)}i.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==i.prototype},i.compare=function(T,M){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),Se(M,Uint8Array)&&(M=i.from(M,M.offset,M.byteLength)),!i.isBuffer(T)||!i.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let L=T.length,te=M.length;for(let ae=0,he=Math.min(L,te);ae<he;++ae)if(T[ae]!==M[ae]){L=T[ae],te=M[ae];break}return L<te?-1:te<L?1:0},i.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return i.alloc(0);let L;if(M===void 0)for(M=0,L=0;L<T.length;++L)M+=T[L].length;let te=i.allocUnsafe(M),ae=0;for(L=0;L<T.length;++L){let he=T[L];if(Se(he,Uint8Array))ae+he.length>te.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(te,ae)):Uint8Array.prototype.set.call(te,he,ae);else if(i.isBuffer(he))he.copy(te,ae);else throw new TypeError('"list" argument must be an Array of Buffers');ae+=he.length}return te};function E(T,M){if(i.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Se(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let L=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&L===0)return 0;let ae=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return L;case"utf8":case"utf-8":return ge(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return qe(T).length;default:if(ae)return te?-1:ge(T).length;M=(""+M).toLowerCase(),ae=!0}}i.byteLength=E;function _(T,M,L){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((L===void 0||L>this.length)&&(L=this.length),L<=0)||(L>>>=0,M>>>=0,L<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,M,L);case"utf8":case"utf-8":return D(this,M,L);case"ascii":return x(this,M,L);case"latin1":case"binary":return P(this,M,L);case"base64":return X(this,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,M,L);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}i.prototype._isBuffer=!0;function I(T,M,L){let te=T[M];T[M]=T[L],T[L]=te}i.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)I(this,M,M+1);return this},i.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)I(this,M,M+3),I(this,M+1,M+2);return this},i.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)I(this,M,M+7),I(this,M+1,M+6),I(this,M+2,M+5),I(this,M+3,M+4);return this},i.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?D(this,0,T):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(T){if(!i.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:i.compare(this,T)===0},i.prototype.inspect=function(){let T="",M=t.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(i.prototype[n]=i.prototype.inspect),i.prototype.compare=function(T,M,L,te,ae){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),!i.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),L===void 0&&(L=T?T.length:0),te===void 0&&(te=0),ae===void 0&&(ae=this.length),M<0||L>T.length||te<0||ae>this.length)throw new RangeError("out of range index");if(te>=ae&&M>=L)return 0;if(te>=ae)return-1;if(M>=L)return 1;if(M>>>=0,L>>>=0,te>>>=0,ae>>>=0,this===T)return 0;let he=ae-te,xe=L-M,Ot=Math.min(he,xe),Un=this.slice(te,ae),Or=T.slice(M,L);for(let hr=0;hr<Ot;++hr)if(Un[hr]!==Or[hr]){he=Un[hr],xe=Or[hr];break}return he<xe?-1:xe<he?1:0};function R(T,M,L,te,ae){if(T.length===0)return-1;if(typeof L=="string"?(te=L,L=0):L>2147483647?L=2147483647:L<-2147483648&&(L=-2147483648),L=+L,et(L)&&(L=ae?0:T.length-1),L<0&&(L=T.length+L),L>=T.length){if(ae)return-1;L=T.length-1}else if(L<0)if(ae)L=0;else return-1;if(typeof M=="string"&&(M=i.from(M,te)),i.isBuffer(M))return M.length===0?-1:N(T,M,L,te,ae);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(T,M,L):Uint8Array.prototype.lastIndexOf.call(T,M,L):N(T,[M],L,te,ae);throw new TypeError("val must be string, number or Buffer")}function N(T,M,L,te,ae){let he=1,xe=T.length,Ot=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;he=2,xe/=2,Ot/=2,L/=2}function Un(hr,ir){return he===1?hr[ir]:hr.readUInt16BE(ir*he)}let Or;if(ae){let hr=-1;for(Or=L;Or<xe;Or++)if(Un(T,Or)===Un(M,hr===-1?0:Or-hr)){if(hr===-1&&(hr=Or),Or-hr+1===Ot)return hr*he}else hr!==-1&&(Or-=Or-hr),hr=-1}else for(L+Ot>xe&&(L=xe-Ot),Or=L;Or>=0;Or--){let hr=!0;for(let ir=0;ir<Ot;ir++)if(Un(T,Or+ir)!==Un(M,ir)){hr=!1;break}if(hr)return Or}return-1}i.prototype.includes=function(T,M,L){return this.indexOf(T,M,L)!==-1},i.prototype.indexOf=function(T,M,L){return R(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return R(this,T,M,L,!1)};function $(T,M,L,te){L=Number(L)||0;let ae=T.length-L;te?(te=Number(te),te>ae&&(te=ae)):te=ae;let he=M.length;te>he/2&&(te=he/2);let xe;for(xe=0;xe<te;++xe){let Ot=parseInt(M.substr(xe*2,2),16);if(et(Ot))return xe;T[L+xe]=Ot}return xe}function F(T,M,L,te){return Et(ge(M,T.length-L),T,L,te)}function z(T,M,L,te){return Et(Me(M),T,L,te)}function B(T,M,L,te){return Et(qe(M),T,L,te)}function W(T,M,L,te){return Et(Le(M,T.length-L),T,L,te)}i.prototype.write=function(T,M,L,te){if(M===void 0)te="utf8",L=this.length,M=0;else if(L===void 0&&typeof M=="string")te=M,L=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(L)?(L=L>>>0,te===void 0&&(te="utf8")):(te=L,L=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ae=this.length-M;if((L===void 0||L>ae)&&(L=ae),T.length>0&&(L<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let he=!1;for(;;)switch(te){case"hex":return $(this,T,M,L);case"utf8":case"utf-8":return F(this,T,M,L);case"ascii":case"latin1":case"binary":return z(this,T,M,L);case"base64":return B(this,T,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,M,L);default:if(he)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(T,M,L){return M===0&&L===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,L))}function D(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],xe=null,Ot=he>239?4:he>223?3:he>191?2:1;if(ae+Ot<=L){let Un,Or,hr,ir;switch(Ot){case 1:he<128&&(xe=he);break;case 2:Un=T[ae+1],(Un&192)===128&&(ir=(he&31)<<6|Un&63,ir>127&&(xe=ir));break;case 3:Un=T[ae+1],Or=T[ae+2],(Un&192)===128&&(Or&192)===128&&(ir=(he&15)<<12|(Un&63)<<6|Or&63,ir>2047&&(ir<55296||ir>57343)&&(xe=ir));break;case 4:Un=T[ae+1],Or=T[ae+2],hr=T[ae+3],(Un&192)===128&&(Or&192)===128&&(hr&192)===128&&(ir=(he&15)<<18|(Un&63)<<12|(Or&63)<<6|hr&63,ir>65535&&ir<1114112&&(xe=ir))}}xe===null?(xe=65533,Ot=1):xe>65535&&(xe-=65536,te.push(xe>>>10&1023|55296),xe=56320|xe&1023),te.push(xe),ae+=Ot}return b(te)}var C=4096;function b(T){let M=T.length;if(M<=C)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=C));return L}function x(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]&127);return te}function P(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]);return te}function k(T,M,L){let te=T.length;(!M||M<0)&&(M=0),(!L||L<0||L>te)&&(L=te);let ae="";for(let he=M;he<L;++he)ae+=wt[T[he]];return ae}function A(T,M,L){let te=T.slice(M,L),ae="";for(let he=0;he<te.length-1;he+=2)ae+=String.fromCharCode(te[he]+te[he+1]*256);return ae}i.prototype.slice=function(T,M){let L=this.length;T=~~T,M=M===void 0?L:~~M,T<0?(T+=L,T<0&&(T=0)):T>L&&(T=L),M<0?(M+=L,M<0&&(M=0)):M>L&&(M=L),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,i.prototype),te};function O(T,M,L){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>L)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return te},i.prototype.readUintBE=i.prototype.readUIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T+--M],ae=1;for(;M>0&&(ae*=256);)te+=this[T+--M]*ae;return te},i.prototype.readUint8=i.prototype.readUInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]|this[T+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]<<8|this[T+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},i.prototype.readBigUInt64LE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ae=this[++T]+this[++T]*2**8+this[++T]*2**16+L*2**24;return BigInt(te)+(BigInt(ae)<<BigInt(32))}),i.prototype.readBigUInt64BE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ae=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L;return(BigInt(te)<<BigInt(32))+BigInt(ae)}),i.prototype.readIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return ae*=128,te>=ae&&(te-=Math.pow(2,8*M)),te},i.prototype.readIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=M,ae=1,he=this[T+--te];for(;te>0&&(ae*=256);)he+=this[T+--te]*ae;return ae*=128,he>=ae&&(he-=Math.pow(2,8*M)),he},i.prototype.readInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},i.prototype.readInt16LE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T]|this[T+1]<<8;return L&32768?L|4294901760:L},i.prototype.readInt16BE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T+1]|this[T]<<8;return L&32768?L|4294901760:L},i.prototype.readInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},i.prototype.readInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},i.prototype.readBigInt64LE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(L<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),i.prototype.readBigInt64BE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L)}),i.prototype.readFloatLE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!0,23,4)},i.prototype.readFloatBE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!1,23,4)},i.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!0,52,8)},i.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!1,52,8)};function q(T,M,L,te,ae,he){if(!i.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ae||M<he)throw new RangeError('"value" argument is out of bounds');if(L+te>T.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;q(this,T,M,L,xe,0)}let ae=1,he=0;for(this[M]=T&255;++he<L&&(ae*=256);)this[M+he]=T/ae&255;return M+L},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;q(this,T,M,L,xe,0)}let ae=L-1,he=1;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)this[M+ae]=T/he&255;return M+L},i.prototype.writeUint8=i.prototype.writeUInt8=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,1,255,0),this[M]=T&255,M+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function G(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,L}function V(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L+7]=he,he=he>>8,T[L+6]=he,he=he>>8,T[L+5]=he,he=he>>8,T[L+4]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=xe,xe=xe>>8,T[L+2]=xe,xe=xe>>8,T[L+1]=xe,xe=xe>>8,T[L]=xe,L+8}i.prototype.writeBigUInt64LE=St(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=St(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Ot=Math.pow(2,8*L-1);q(this,T,M,L,Ot-1,-Ot)}let ae=0,he=1,xe=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&xe===0&&this[M+ae-1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Ot=Math.pow(2,8*L-1);q(this,T,M,L,Ot-1,-Ot)}let ae=L-1,he=1,xe=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&xe===0&&this[M+ae+1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},i.prototype.writeInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},i.prototype.writeInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},i.prototype.writeBigInt64LE=St(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=St(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function H(T,M,L,te,ae,he){if(L+te>T.length)throw new RangeError("Index out of range");if(L<0)throw new RangeError("Index out of range")}function Y(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return Y(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return Y(this,T,M,!1,L)};function K(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return K(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return K(this,T,M,!1,L)},i.prototype.copy=function(T,M,L,te){if(!i.isBuffer(T))throw new TypeError("argument should be a Buffer");if(L||(L=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<L&&(te=L),te===L||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-L&&(te=T.length-M+L);let ae=te-L;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,L,te):Uint8Array.prototype.set.call(T,this.subarray(L,te),M),ae},i.prototype.fill=function(T,M,L,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,L=this.length):typeof L=="string"&&(te=L,L=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!i.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let he=T.charCodeAt(0);(te==="utf8"&&he<128||te==="latin1")&&(T=he)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<L)throw new RangeError("Out of range index");if(L<=M)return this;M=M>>>0,L=L===void 0?this.length:L>>>0,T||(T=0);let ae;if(typeof T=="number")for(ae=M;ae<L;++ae)this[ae]=T;else{let he=i.isBuffer(T)?T:i.from(T,te),xe=he.length;if(xe===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%xe]}return this};var Q={};function se(T,M,L){Q[T]=class extends L{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,L){let te=`The value of "${T}" is out of range.`,ae=L;return Number.isInteger(L)&&Math.abs(L)>2**32?ae=re(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=re(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function re(T){let M="",L=T.length,te=T[0]==="-"?1:0;for(;L>=te+4;L-=3)M=`_${T.slice(L-3,L)}${M}`;return`${T.slice(0,L)}${M}`}function Z(T,M,L){le(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&pe(M,T.length-(L+1))}function de(T,M,L,te,ae,he){if(T>L||T<M){let xe=typeof M=="bigint"?"n":"",Ot;throw he>3?M===0||M===BigInt(0)?Ot=`>= 0${xe} and < 2${xe} ** ${(he+1)*8}${xe}`:Ot=`>= -(2${xe} ** ${(he+1)*8-1}${xe}) and < 2 ** ${(he+1)*8-1}${xe}`:Ot=`>= ${M}${xe} and <= ${L}${xe}`,new Q.ERR_OUT_OF_RANGE("value",Ot,T)}Z(te,ae,he)}function le(T,M){if(typeof T!="number")throw new Q.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,L){throw Math.floor(T)!==T?(le(T,L),new Q.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var ve=/[^+/0-9A-Za-z-_]/g;function ce(T){if(T=T.split("=")[0],T=T.trim().replace(ve,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ge(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let xe=0;xe<te;++xe){if(L=T.charCodeAt(xe),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(xe+1===te){(M-=3)>-1&&he.push(239,191,189);continue}ae=L;continue}if(L<56320){(M-=3)>-1&&he.push(239,191,189),ae=L;continue}L=(ae-55296<<10|L-56320)+65536}else ae&&(M-=3)>-1&&he.push(239,191,189);if(ae=null,L<128){if((M-=1)<0)break;he.push(L)}else if(L<2048){if((M-=2)<0)break;he.push(L>>6|192,L&63|128)}else if(L<65536){if((M-=3)<0)break;he.push(L>>12|224,L>>6&63|128,L&63|128)}else if(L<1114112){if((M-=4)<0)break;he.push(L>>18|240,L>>12&63|128,L>>6&63|128,L&63|128)}else throw new Error("Invalid code point")}return he}function Me(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Le(T,M){let L,te,ae,he=[];for(let xe=0;xe<T.length&&!((M-=2)<0);++xe)L=T.charCodeAt(xe),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function qe(T){return e.toByteArray(ce(T))}function Et(T,M,L,te){let ae;for(ae=0;ae<te&&!(ae+L>=M.length||ae>=T.length);++ae)M[ae+L]=T[ae];return ae}function Se(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function et(T){return T!==T}var wt=function(){let T="0123456789abcdef",M=new Array(256);for(let L=0;L<16;++L){let te=L*16;for(let ae=0;ae<16;++ae)M[te+ae]=T[L]+T[ae]}return M}();function St(T){return typeof BigInt>"u"?Mt:T}function Mt(){throw new Error("BigInt not supported")}}),UU=zt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),LU=zt(t=>{"use strict";var e=_c(),r=new Set(["buffer","view","utf8"]),n=class{constructor(s){if(this.encode=s.encode||this.encode,this.decode=s.decode||this.decode,this.name=s.name||this.name,this.format=s.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"||!r.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");s.createViewTranscoder&&(this.createViewTranscoder=s.createViewTranscoder),s.createBufferTranscoder&&(this.createBufferTranscoder=s.createBufferTranscoder),s.createUTF8Transcoder&&(this.createUTF8Transcoder=s.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"})}};t.Encoding=n}),KU=zt(t=>{"use strict";var{Buffer:e}=UI()||{},{Encoding:r}=LU(),n=UU(),s=class extends r{constructor(i){super({...i,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:i=>this.decode(e.from(i.buffer,i.byteOffset,i.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends r{constructor(i){super({...i,format:"view"})}createBufferTranscoder(){return new s({encode:i=>{let c=this.encode(i);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends r{constructor(i){super({...i,format:"utf8"})}createBufferTranscoder(){return new s({encode:i=>e.from(this.encode(i),"utf8"),decode:i=>this.decode(i.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:i,textDecoder:c}=n();return new a({encode:u=>i.encode(this.encode(u)),decode:u=>this.decode(c.decode(u)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=s,t.ViewFormat=a,t.UTF8Format=o}),fne=zt(t=>{"use strict";var{Buffer:e}=UI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=UU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=KU(),i=c=>c;t.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:i,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:i,name:"view",createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:`${this.name}+buffer`})}}),t.hex=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),t.base64=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),pne=zt(t=>{"use strict";var e=_c(),r=fne(),{Encoding:n}=LU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=KU(),i=Symbol("formats"),c=Symbol("encodings"),u=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(S=>u.has(S)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[i]=new Set(y);for(let S in r)try{this.encoding(S)}catch(v){if(v.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw v}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let S=this[c].get(y);if(S===void 0){if(typeof y=="string"&&y!==""){if(S=p[y],!S)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");S=l(y)}let{name:v,format:E}=S;if(!this[i].has(E))if(this[i].has("view"))S=S.createViewTranscoder();else if(this[i].has("buffer"))S=S.createBufferTranscoder();else if(this[i].has("utf8"))S=S.createUTF8Transcoder();else throw new e(`Encoding '${v}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,v,S.name,S.commonName])this[c].set(_,S)}return S}};t.Transcoder=d;function l(y){if(y instanceof n)return y;let S="type"in y&&typeof y.type=="string"?y.type:void 0,v=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:v});case"utf8":return new o({...y,name:v});case"buffer":return new s({...y,name:v});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:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),hne=zt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(n=!1));function a(u,d,l){this.fn=u,this.context=d,this.once=l||!1}function o(u,d,l,f,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new a(l,f||u,h),m=n?n+d:d;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],p]:u._events[m].push(p):(u._events[m]=p,u._eventsCount++),u}function i(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],d,l;if(this._eventsCount===0)return u;for(l in d=this._events)r.call(d,l)&&u.push(n?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},c.prototype.listeners=function(u){var d=n?n+u:u,l=this._events[d];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,h=l.length,p=new Array(h);f<h;f++)p[f]=l[f].fn;return p},c.prototype.listenerCount=function(u){var d=n?n+u:u,l=this._events[d];return l?l.fn?1:l.length:0},c.prototype.emit=function(u,d,l,f,h,p){var m=n?n+u:u;if(!this._events[m])return!1;var y=this._events[m],S=arguments.length,v,E;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),S){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,l),!0;case 4:return y.fn.call(y.context,d,l,f),!0;case 5:return y.fn.call(y.context,d,l,f,h),!0;case 6:return y.fn.call(y.context,d,l,f,h,p),!0}for(E=1,v=new Array(S-1);E<S;E++)v[E-1]=arguments[E];y.fn.apply(y.context,v)}else{var _=y.length,I;for(E=0;E<_;E++)switch(y[E].once&&this.removeListener(u,y[E].fn,void 0,!0),S){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,l);break;case 4:y[E].fn.call(y[E].context,d,l,f);break;default:if(!v)for(I=1,v=new Array(S-1);I<S;I++)v[I-1]=arguments[I];y[E].fn.apply(y[E].context,v)}}return!0},c.prototype.on=function(u,d,l){return o(this,u,d,l,!1)},c.prototype.once=function(u,d,l){return o(this,u,d,l,!0)},c.prototype.removeListener=function(u,d,l,f){var h=n?n+u:u;if(!this._events[h])return this;if(!d)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===d&&(!f||p.once)&&(!l||p.context===l)&&i(this,h);else{for(var m=0,y=[],S=p.length;m<S;m++)(p[m].fn!==d||f&&!p[m].once||l&&p[m].context!==l)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},c.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&i(this,d)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),mne=zt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),eP=zt(t=>{"use strict";var e=mne();t.fromCallback=function(r,n){if(r===void 0){var s=new Promise(function(a,o){r=function(i,c){i?o(i):a(c)}});r[n!==void 0?n:"promise"]=s}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r},t.fromPromise=function(r,n){if(n===void 0)return r;r.then(function(s){e(()=>n(null,s))}).catch(function(s){e(()=>n(s))})}}),LI=zt(t=>{"use strict";t.getCallback=function(e,r){return typeof e=="function"?e:r},t.getOptions=function(e,r){return typeof e=="object"&&e!==null?e:r!==void 0?r:{}}}),Ef=zt(t=>{"use strict";var{fromCallback:e}=eP(),r=_c(),{getOptions:n,getCallback:s}=LI(),a=Symbol("promise"),o=Symbol("callback"),i=Symbol("working"),c=Symbol("handleOne"),u=Symbol("handleMany"),d=Symbol("autoClose"),l=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),S=Symbol("keyEncoding"),v=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),I=Symbol("keys"),R=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),F=Object.freeze({}),z=()=>{},B=!1,W=class{constructor(x,P,k){if(typeof x!="object"||x===null){let A=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[i]=!1,this[h]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[u]=this[u].bind(this),this[p]=this[p].bind(this),this[S]=P[S],this[v]=P[v],this[_]=k,this[N]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[$]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[$]}get limit(){return this[N]}next(x){let P;if(x===void 0)P=new Promise((k,A)=>{x=(O,q,G)=>{O?A(O):this[_]?q===void 0&&G===void 0?k():k([q,G]):k(q)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(x,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(x,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=x,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,k){return k=s(P,k),k=e(k,a),P=n(P,F),Number.isInteger(x)?(this[h]?this.nextTick(k,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(k,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[N]<1/0&&(x=Math.min(x,this[N]-this[$])),this[i]=!0,this[o]=k,x<=0?this.nextTick(this[u],null,[]):this._nextv(x,P,this[u])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(x,P,k){let A=[],O=(q,G,V)=>{if(q)return k(q);if(this[_]?G===void 0&&V===void 0:G===void 0)return k(null,A);A.push(this[_]?[G,V]:G),A.length===x?k(null,A):this._next(O)};this._next(O)}all(x,P){return P=s(x,P),P=e(P,a),x=n(x,F),this[h]?this.nextTick(P,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[d]=!0,this[$]>=this[N]?this.nextTick(this[u],null,[]):this._all(x,this[u])),P[a]}_all(x,P){let k=this[$],A=[],O=()=>{let G=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;G<=0?this.nextTick(P,null,A):this._nextv(G,F,q)},q=(G,V)=>{G?P(G):V.length===0?P(null,A):(A.push.apply(A,V),k+=V.length,O())};O()}[l](){let x=this[o];return this[E]&&x===null?z:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),x)}[f](x,P,k){this[d]?this.close(x.bind(null,P,k)):x(P,k)}seek(x,P){if(P=n(P,F),!this[h]){if(this[i])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(P.keyEncoding||this[S]),A=k.format;P.keyEncoding!==A&&(P={...P,keyEncoding:A});let O=this.db.prefixKey(k.encode(x),A);this._seek(O,P)}}}_seek(x,P){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[h]?this[y].push(x):(this[h]=!0,this[y].push(x),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),x[a]}_close(x){this.nextTick(x)}[p](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},X=class extends W{constructor(x,P){super(x,P,!0),this[I]=P.keys!==!1,this[R]=P.values!==!1}[c](x,P,k){let A=this[l]();if(x)return A(x);try{P=this[I]&&P!==void 0?this[S].decode(P):void 0,k=this[R]&&k!==void 0?this[v].decode(k):void 0}catch(O){return A(new b("entry",O))}P===void 0&&k===void 0||this[$]++,A(null,P,k)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A of P){let O=A[0],q=A[1];A[0]=this[I]&&O!==void 0?this[S].decode(O):void 0,A[1]=this[R]&&q!==void 0?this[v].decode(q):void 0}}catch(A){return this[f](k,new b("entries",A))}this[$]+=P.length,this[f](k,null,P)}end(x){return!B&&typeof console<"u"&&(B=!0,console.warn(new r("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(x)}},D=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[l]();if(x)return k(x);try{P=P!==void 0?this[S].decode(P):void 0}catch(A){return k(new b("key",A))}P!==void 0&&this[$]++,k(null,P)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A=0;A<P.length;A++){let O=P[A];P[A]=O!==void 0?this[S].decode(O):void 0}}catch(A){return this[f](k,new b("keys",A))}this[$]+=P.length,this[f](k,null,P)}},C=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[l]();if(x)return k(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(A){return k(new b("value",A))}P!==void 0&&this[$]++,k(null,P)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A=0;A<P.length;A++){let O=P[A];P[A]=O!==void 0?this[v].decode(O):void 0}}catch(A){return this[f](k,new b("values",A))}this[$]+=P.length,this[f](k,null,P)}},b=class extends r{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(X.prototype,x.split(" ")[0],{get(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});X.keyEncoding=S,X.valueEncoding=v,t.AbstractIterator=X,t.AbstractKeyIterator=D,t.AbstractValueIterator=C}),yne=zt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Ef(),n=Symbol("iterator"),s=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),i=class extends e{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends r{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let u of[i,c]){let d=u===i,l=d?f=>f[0]:f=>f[1];u.prototype._next=function(f){this[s]=f,this[n].next(this[a])},u.prototype[a]=function(f,h,p){let m=this[s];f?m(f):m(null,d?h:p)},u.prototype._nextv=function(f,h,p){this[s]=p,this[n].nextv(f,h,this[o])},u.prototype._all=function(f,h){this[s]=h,this[n].all(f,this[o])},u.prototype[o]=function(f,h){let p=this[s];f?p(f):p(null,h.map(l))},u.prototype._seek=function(f,h){this[n].seek(f,h)},u.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=i,t.DefaultValueIterator=c}),gne=zt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Ef(),s=_c(),a=Symbol("nut"),o=Symbol("undefer"),i=Symbol("factory"),c=class extends e{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.iterator(f),this.db.defer(()=>this[o]())}},u=class extends r{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.values(f),this.db.defer(()=>this[o]())}};for(let l of[c,u,d])l.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[i]())},l.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new s("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._nextv=function(f,h,p){this[a]!==null?this[a].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new s("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._all=function(f,h){this[a]!==null?this[a].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new s("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},l.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};t.DeferredIterator=c,t.DeferredKeyIterator=u,t.DeferredValueIterator=d}),zU=zt(t=>{"use strict";var{fromCallback:e}=eP(),r=_c(),{getCallback:n,getOptions:s}=LI(),a=Symbol("promise"),o=Symbol("status"),i=Symbol("operations"),c=Symbol("finishClose"),u=Symbol("closeCallbacks"),d=class{constructor(l){if(typeof l!="object"||l===null){let f=l===null?"null":typeof l;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[i]=[],this[u]=[],this[o]="open",this[c]=this[c].bind(this),this.db=l,this.db.attachResource(this),this.nextTick=l.nextTick}get length(){return this[i].length}put(l,f,h){if(this[o]!=="open")throw new r("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(l)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,S=m.keyEncoding(h&&h.keyEncoding),v=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:v.format},m!==this.db&&(h.sublevel=null);let _=m.prefixKey(S.encode(l),E),I=v.encode(f);return this._put(_,I,h),this[i].push({...y,type:"put",key:l,value:f}),this}_put(l,f,h){}del(l,f){if(this[o]!=="open")throw new r("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(l);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),S=y.format;return f={...f,keyEncoding:S},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(l),S),f),this[i].push({...m,type:"del",key:l}),this}_del(l,f){}clear(){if(this[o]!=="open")throw new r("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[i]=[],this}_clear(){}write(l,f){return f=n(l,f),f=e(f,a),l=s(l),this[o]!=="open"?this.nextTick(f,new r("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(l,h=>{this[o]="closing",this[u].push(()=>f(h)),h||this.db.emit("batch",this[i]),this._close(this[c])})),f[a]}_write(l,f){}close(l){return l=e(l,a),this[o]==="closing"?this[u].push(l):this[o]==="closed"?this.nextTick(l):(this[u].push(l),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),l[a]}_close(l){this.nextTick(l)}[c](){this[o]="closed",this.db.detachResource(this);let l=this[u];this[u]=[];for(let f of l)f()}};t.AbstractChainedBatch=d}),wne=zt(t=>{"use strict";var{AbstractChainedBatch:e}=zU(),r=_c(),n=Symbol("encoded"),s=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,i){this[n].push({...i,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=s}),vne=zt((t,e)=>{"use strict";var r=_c(),n=Object.prototype.hasOwnProperty,s=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let i={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new r(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});s.has(c)?i[c]=o.encode(a[c]):i[c]=a[c]}return i.reverse=!!i.reverse,i.limit=Number.isInteger(i.limit)&&i.limit>=0?i.limit:-1,i}}),qU=zt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(s=>setTimeout(()=>{throw s},0))}),bne=zt((t,e)=>{"use strict";var r=qU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),Pne=zt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Ef(),s=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),i=Symbol("handleMany"),c=Symbol("callback"),u=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h,p){let m=this[c];if(f)return m(f);h!==void 0&&(h=this[s](h)),m(f,h,p)}[i](f,h){let p=this[c];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[s](y))}p(f,h)}},d=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h){let p=this[c];if(f)return p(f);h!==void 0&&(h=this[s](h)),p(f,h)}[i](f,h){let p=this[c];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[s](y))}p(f,h)}},l=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[u,d])f.prototype._next=function(h){this[c]=h,this[a].next(this[o])},f.prototype._nextv=function(h,p,m){this[c]=m,this[a].nextv(h,p,this[i])},f.prototype._all=function(h,p){this[c]=p,this[a].all(h,this[i])};for(let f of[l])f.prototype._next=function(h){this[a].next(h)},f.prototype._nextv=function(h,p,m){this[a].nextv(h,p,m)},f.prototype._all=function(h,p){this[a].all(h,p)};for(let f of[u,d,l])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=u,t.AbstractSublevelKeyIterator=d,t.AbstractSublevelValueIterator=l}),xne=zt((t,e)=>{"use strict";var r=_c(),{Buffer:n}=UI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Pne(),i=Symbol("prefix"),c=Symbol("upperBound"),u=Symbol("prefixRange"),d=Symbol("parent"),l=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:E}){class _ extends E{static defaults(R){if(typeof R=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(R&&R.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return R==null?h:R.separator?R:{...R,separator:"!"}}constructor(R,N,$){let{separator:F,manifest:z,...B}=_.defaults($);N=v(N,F);let W=F.charCodeAt(0)+1,X=R[d]||R;if(!f.encode(N).every(b=>b>W&&b<127))throw new r(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(X,z),B);let D=(R.prefix||"")+F+N+F,C=D.slice(0,-1)+String.fromCharCode(W);this[d]=X,this[i]=new y(D),this[c]=new y(C),this[l]=new S,this.nextTick=X.nextTick}prefixKey(R,N){if(N==="utf8")return this[i].utf8+R;if(R.byteLength===0)return this[i][N];if(N==="view"){let $=this[i].view,F=new Uint8Array($.byteLength+R.byteLength);return F.set($,0),F.set(R,$.byteLength),F}else{let $=this[i].buffer;return n.concat([$,R],$.byteLength+R.byteLength)}}[u](R,N){R.gte!==void 0?R.gte=this.prefixKey(R.gte,N):R.gt!==void 0?R.gt=this.prefixKey(R.gt,N):R.gte=this[i][N],R.lte!==void 0?R.lte=this.prefixKey(R.lte,N):R.lt!==void 0?R.lt=this.prefixKey(R.lt,N):R.lte=this[c][N]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(R,N){this[d].open({passive:!0},N)}_put(R,N,$,F){this[d].put(R,N,$,F)}_get(R,N,$){this[d].get(R,N,$)}_getMany(R,N,$){this[d].getMany(R,N,$)}_del(R,N,$){this[d].del(R,N,$)}_batch(R,N,$){this[d].batch(R,N,$)}_clear(R,N){this[u](R,R.keyEncoding),this[d].clear(R,N)}_iterator(R){this[u](R,R.keyEncoding);let N=this[d].iterator(R),$=this[l].get(this[i].utf8.length,R.keyEncoding);return new s(this,R,N,$)}_keys(R){this[u](R,R.keyEncoding);let N=this[d].keys(R),$=this[l].get(this[i].utf8.length,R.keyEncoding);return new a(this,R,N,$)}_values(R){this[u](R,R.keyEncoding);let N=this[d].values(R);return new o(this,R,N)}}return{AbstractSublevel:_}};var p=function(E,_){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,_){return E.supports.encodings[_]?E.keyEncoding(_).name===_:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},S=class{constructor(){this.cache=new Map}get(E,_){let I=this.cache.get(_);return I===void 0&&(_==="view"?I=(function(R,N){return N.subarray(R)}).bind(null,E):I=(function(R,N){return N.slice(R)}).bind(null,E),this.cache.set(_,I)),I}},v=function(E,_){let I=0,R=E.length;for(;I<R&&E[I]===_;)I++;for(;R>I&&E[R-1]===_;)R--;return E.slice(I,R)}}),xN=zt(t=>{"use strict";var{supports:e}=dne(),{Transcoder:r}=pne(),{EventEmitter:n}=hne(),{fromCallback:s}=eP(),a=_c(),{AbstractIterator:o}=Ef(),{DefaultKeyIterator:i,DefaultValueIterator:c}=yne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=gne(),{DefaultChainedBatch:f}=wne(),{getCallback:h,getOptions:p}=LI(),m=vne(),y=Symbol("promise"),S=Symbol("landed"),v=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),I=Symbol("undefer"),R=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),F=Symbol("defaultOptions"),z=Symbol("transcoder"),B=Symbol("keyEncoding"),W=Symbol("valueEncoding"),X=()=>{},D=class extends n{constructor(P,k){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");k=p(k);let{keyEncoding:A,valueEncoding:O,passive:q,...G}=k;this[v]=new Set,this[_]=[],this[R]=!0,this[N]=G,this[$]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(x(this)),this[B]=this[z].encoding(A||"utf8"),this[W]=this[z].encoding(O||"utf8");for(let V of this[z].encodings())this.supports.encodings[V.commonName]||(this.supports.encodings[V.commonName]=!0);this[F]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[R]&&this.open({passive:!1},X)})}get status(){return this[$]}keyEncoding(P){return this[z].encoding(P??this[B])}valueEncoding(P){return this[z].encoding(P??this[W])}open(P,k){k=h(P,k),k=s(k,y),P={...this[N],...p(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let A=O=>{this[$]==="closing"||this[$]==="opening"?this.once(S,O?()=>A(O):A):this[$]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:O})):k()};return P.passive?this[$]==="opening"?this.once(S,A):this.nextTick(A):this[$]==="closed"||this[R]?(this[R]=!1,this[$]="opening",this.emit("opening"),this._open(P,O=>{if(O){this[$]="closed",this[E](()=>{this.emit(S),A(O)}),this[I]();return}this[$]="open",this[I](),this.emit(S),this[$]==="open"&&this.emit("open"),this[$]==="open"&&this.emit("ready"),A()})):this[$]==="open"?this.nextTick(A):this.once(S,()=>this.open(P,k)),k[y]}_open(P,k){this.nextTick(k)}close(P){P=s(P,y);let k=A=>{this[$]==="opening"||this[$]==="closing"?this.once(S,A?k(A):k):this[$]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):P()};if(this[$]==="open"){this[$]="closing",this.emit("closing");let A=O=>{this[$]="open",this[I](),this.emit(S),k(O)};this[E](()=>{this._close(O=>{if(O)return A(O);this[$]="closed",this[I](),this.emit(S),this[$]==="closed"&&this.emit("closed"),k()})})}else this[$]==="closed"?this.nextTick(k):this.once(S,()=>this.close(P));return P[y]}[E](P){if(this[v].size===0)return this.nextTick(P);let k=this[v].size,A=!0,O=()=>{--k===0&&(A?this.nextTick(P):P())};for(let q of this[v])q.close(O);A=!1,this[v].clear()}_close(P){this.nextTick(P)}get(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.get(P,k,A)),A[y];if(b(this,A))return A[y];let O=this._checkKey(P);if(O)return this.nextTick(A,O),A[y];let q=this.keyEncoding(k.keyEncoding),G=this.valueEncoding(k.valueEncoding),V=q.format,H=G.format;return(k.keyEncoding!==V||k.valueEncoding!==H)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:H})),this._get(this.prefixKey(q.encode(P),V),k,(Y,K)=>{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{K=G.decode(K)}catch(Q){return A(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,K)}),A[y]}_get(P,k,A){this.nextTick(A,new Error("NotFound"))}getMany(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.getMany(P,k,A)),A[y];if(b(this,A))return A[y];if(!Array.isArray(P))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(P.length===0)return this.nextTick(A,null,[]),A[y];let O=this.keyEncoding(k.keyEncoding),q=this.valueEncoding(k.valueEncoding),G=O.format,V=q.format;(k.keyEncoding!==G||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:G,valueEncoding:V}));let H=new Array(P.length);for(let Y=0;Y<P.length;Y++){let K=P[Y],Q=this._checkKey(K);if(Q)return this.nextTick(A,Q),A[y];H[Y]=this.prefixKey(O.encode(K),G)}return this._getMany(H,k,(Y,K)=>{if(Y)return A(Y);try{for(let Q=0;Q<K.length;Q++)K[Q]!==void 0&&(K[Q]=q.decode(K[Q]))}catch(Q){return A(new a(`Could not decode one or more of ${K.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,K)}),A[y]}_getMany(P,k,A){this.nextTick(A,null,new Array(P.length).fill(void 0))}put(P,k,A,O){if(O=h(A,O),O=s(O,y),A=p(A,this[F].entry),this[$]==="opening")return this.defer(()=>this.put(P,k,A,O)),O[y];if(b(this,O))return O[y];let q=this._checkKey(P)||this._checkValue(k);if(q)return this.nextTick(O,q),O[y];let G=this.keyEncoding(A.keyEncoding),V=this.valueEncoding(A.valueEncoding),H=G.format,Y=V.format;(A.keyEncoding!==H||A.valueEncoding!==Y)&&(A=Object.assign({},A,{keyEncoding:H,valueEncoding:Y}));let K=this.prefixKey(G.encode(P),H),Q=V.encode(k);return this._put(K,Q,A,se=>{if(se)return O(se);this.emit("put",P,k),O()}),O[y]}_put(P,k,A,O){this.nextTick(O)}del(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].key),this[$]==="opening")return this.defer(()=>this.del(P,k,A)),A[y];if(b(this,A))return A[y];let O=this._checkKey(P);if(O)return this.nextTick(A,O),A[y];let q=this.keyEncoding(k.keyEncoding),G=q.format;return k.keyEncoding!==G&&(k=Object.assign({},k,{keyEncoding:G})),this._del(this.prefixKey(q.encode(P),G),k,V=>{if(V)return A(V);this.emit("del",P),A()}),A[y]}_del(P,k,A){this.nextTick(A)}batch(P,k,A){if(!arguments.length){if(this[$]==="opening")return new f(this);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?A=P:A=h(k,A),A=s(A,y),k=p(k,this[F].empty),this[$]==="opening")return this.defer(()=>this.batch(P,k,A)),A[y];if(b(this,A))return A[y];if(!Array.isArray(P))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(P.length===0)return this.nextTick(A),A[y];let O=new Array(P.length),{keyEncoding:q,valueEncoding:G,...V}=k;for(let H=0;H<P.length;H++){if(typeof P[H]!="object"||P[H]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let Y=Object.assign({},P[H]);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 K=this._checkKey(Y.key);if(K)return this.nextTick(A,K),A[y];let Q=Y.sublevel!=null?Y.sublevel:this,se=Q.keyEncoding(Y.keyEncoding||q),re=se.format;if(Y.key=Q.prefixKey(se.encode(Y.key),re),Y.keyEncoding=re,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(A,Z),A[y];let de=Q.valueEncoding(Y.valueEncoding||G);Y.value=de.encode(Y.value),Y.valueEncoding=de.format}Q!==this&&(Y.sublevel=null),O[H]=Y}return this._batch(O,V,H=>{if(H)return A(H);this.emit("batch",P),A()}),A[y]}_batch(P,k,A){this.nextTick(A)}sublevel(P,k){return this._sublevel(P,C.defaults(k))}_sublevel(P,k){return new C(this,P,k)}prefixKey(P,k){return P}clear(P,k){if(k=h(P,k),k=s(k,y),P=p(P,this[F].empty),this[$]==="opening")return this.defer(()=>this.clear(P,k)),k[y];if(b(this,k))return k[y];let A=P,O=this.keyEncoding(P.keyEncoding);return P=m(P,O),P.keyEncoding=O.format,P.limit===0?this.nextTick(k):this._clear(P,q=>{if(q)return k(q);this.emit("clear",A),k()}),k[y]}_clear(P,k){this.nextTick(k)}iterator(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P.keys=P.keys!==!1,P.values=P.values!==!1,P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new u(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new o(this,P)}keys(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new d(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new i(this,P)}values(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new l(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[_].push(P)}[I](){if(this[_].length===0)return;let P=this[_];this[_]=[];for(let k of P)k()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[v].add(P)}detachResource(P){this[v].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};D.prototype.nextTick=bne();var{AbstractSublevel:C}=xne()({AbstractLevel:D});t.AbstractLevel=D,t.AbstractSublevel=C;var b=function(P,k){return P[$]!=="open"?(P.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(k=>!!P.supports.encodings[k])}}),FU=zt(t=>{"use strict";t.AbstractLevel=xN().AbstractLevel,t.AbstractSublevel=xN().AbstractSublevel,t.AbstractIterator=Ef().AbstractIterator,t.AbstractKeyIterator=Ef().AbstractKeyIterator,t.AbstractValueIterator=Ef().AbstractValueIterator,t.AbstractChainedBatch=zU().AbstractChainedBatch}),Sne=zt((t,e)=>{e.exports=n;var r=qU();function n(s,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let i,c,u,d,l,f=!0,h;Array.isArray(s)?(i=[],u=c=s.length):(d=Object.keys(s),i={},u=c=d.length);function p(y){function S(){o&&o(y,i),o=null}f?r(S):S()}function m(y,S,v){if(i[y]=v,S&&(l=!0),--u===0||S)p(S);else if(!l&&h<c){let E;d?(E=d[h],h+=1,s[E](function(_,I){m(E,_,I)})):(E=h,h+=1,s[E](function(_,I){m(E,_,I)}))}}h=a,u?d?d.some(function(y,S){return s[y](function(v,E){m(y,v,E)}),S===a-1}):s.some(function(y,S){return y(function(v,E){m(S,v,E)}),S===a-1}):p(null),f=!1}}),GU=zt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,s=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,o=r.lte===void 0;return n!==void 0&&s!==void 0?IDBKeyRange.bound(n,s,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):s!==void 0?IDBKeyRange.upperBound(s,o):null}}),WU=zt((t,e)=>{"use strict";var r=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):r.encode(n)}}),Ene=zt(t=>{"use strict";var{AbstractIterator:e}=FU(),r=GU(),n=WU(),s=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),i=Symbol("currentOptions"),c=Symbol("position"),u=Symbol("location"),d=Symbol("first"),l={},f=class extends e{constructor(p,m,y){super(p,y),this[s]=[],this[a]=this.limit===0,this[o]=y,this[i]={...y},this[c]=void 0,this[u]=m,this[d]=!0}_nextv(p,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[s].length>0)return p=Math.min(p,this[s].length),this.nextTick(y,null,this[s].splice(0,p));this[c]!==void 0&&(this[o].reverse?(this[i].lt=this[c],this[i].lte=void 0):(this[i].gt=this[c],this[i].gte=void 0));let S;try{S=r(this[i])}catch{return this[a]=!0,this.nextTick(y,null,[])}let v=this.db.db.transaction([this[u]],"readonly"),E=v.objectStore(this[u]),_=[];if(this[o].reverse){let I=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[I](S,"prev").onsuccess=R=>{let N=R.target.result;if(N){let{key:$,value:F}=N;this[c]=$,_.push([this[o].keys&&$!==void 0?n($):void 0,this[o].values&&F!==void 0?n(F):void 0]),_.length<p?N.continue():h(v)}else this[a]=!0}}else{let I,R,N=()=>{if(I===void 0||R===void 0)return;let $=Math.max(I.length,R.length);$===0||p===1/0?this[a]=!0:this[c]=I[$-1],_.length=$;for(let F=0;F<$;F++){let z=I[F],B=R[F];_[F]=[this[o].keys&&z!==void 0?n(z):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(v)};this[o].keys||p<1/0?E.getAllKeys(S,p<1/0?p:void 0).onsuccess=$=>{I=$.target.result,N()}:(I=[],this.nextTick(N)),this[o].values?E.getAll(S,p<1/0?p:void 0).onsuccess=$=>{R=$.target.result,N()}:(R=[],this.nextTick(N))}v.onabort=()=>{y(v.error||new Error("aborted by user")),y=null},v.oncomplete=()=>{y(null,_),y=null}}_next(p){if(this[s].length>0){let[m,y]=this[s].shift();this.nextTick(p,null,m,y)}else if(this[a])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,l,(y,S)=>{if(y)return p(y);this[s]=S,this._next(p)})}}_all(p,m){this[d]=!1;let y=this[s].splice(0,this[s].length),S=this.limit-this.count-y.length;if(S<=0)return this.nextTick(m,null,y);this._nextv(S,l,(v,E)=>{if(v)return m(v);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(p,m){this[d]=!0,this[s]=[],this[a]=!1,this[c]=void 0,this[i]={...this[o]};let y;try{y=r(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[o].reverse?this[i].lte=p:this[i].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),kne=zt((t,e)=>{"use strict";e.exports=function(r,n,s,a,o){if(a.limit===0)return r.nextTick(o);let i=r.db.transaction([n],"readwrite"),c=i.objectStore(n),u=0;i.oncomplete=function(){o()},i.onabort=function(){o(i.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",l=a.reverse?"prev":"next";c[d](s,l).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(a.limit<=0||++u<a.limit)&&h.continue()})}}}),_ne=zt(t=>{"use strict";var{AbstractLevel:e}=FU(),r=_c(),n=Sne(),{fromCallback:s}=eP(),{Iterator:a}=Ene(),o=WU(),i=kne(),c=GU(),u="level-js-",d=Symbol("idb"),l=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),S=class extends e{constructor(v,E,_){if(typeof E=="function"||typeof _=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:I,version:R,...N}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof v!="string")throw new Error("constructor requires a location string argument");this[f]=v,this[l]=I??u,this[h]=parseInt(R||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[l]}get version(){return this[h]}get db(){return this[d]}get type(){return"browser-level"}_open(v,E){let _=indexedDB.open(this[l]+this[f],this[h]);_.onerror=function(){E(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,E()},_.onupgradeneeded=I=>{let R=I.target.result;R.objectStoreNames.contains(this[f])||R.createObjectStore(this[f])}}[p](v){return this[d].transaction([this[f]],v).objectStore(this[f])}[m](v,E){let _=v.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,v.result)}}_get(v,E,_){let I=this[p]("readonly"),R;try{R=I.get(v)}catch(N){return this.nextTick(_,N)}this[m](R,function(N,$){if(N)return _(N);if($===void 0)return _(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(v,E,_){let I=this[p]("readonly"),R=v.map(N=>$=>{let F;try{F=I.get(N)}catch(z){return $(z)}F.onsuccess=()=>{let z=F.result;$(null,z===void 0?z:o(z))},F.onerror=z=>{z.stopPropagation(),$(F.error)}});n(R,16,_)}_del(v,E,_){let I=this[p]("readwrite"),R;try{R=I.delete(v)}catch(N){return this.nextTick(_,N)}this[m](R,_)}_put(v,E,_,I){let R=this[p]("readwrite"),N;try{N=R.put(E,v)}catch($){return this.nextTick(I,$)}this[m](N,I)}_iterator(v){return new a(this,this[f],v)}_batch(v,E,_){let I=this[p]("readwrite"),R=I.transaction,N=0,$;R.onabort=function(){_($||R.error||new Error("aborted by user"))},R.oncomplete=function(){_()};function F(){let z=v[N++],B=z.key,W;try{W=z.type==="del"?I.delete(B):I.put(z.value,B)}catch(X){$=X,R.abort();return}N<v.length?W.onsuccess=F:typeof R.commit=="function"&&R.commit()}F()}_clear(v,E){let _,I;try{_=c(v)}catch{return this.nextTick(E)}if(v.limit>=0)return i(this,this[f],_,v,E);try{let R=this[p]("readwrite");I=_?R.delete(_):R.clear()}catch(R){return this.nextTick(E,R)}this[m](I,E)}_close(v){this[d].close(),this.nextTick(v)}};S.destroy=function(v,E,_){typeof E=="function"&&(_=E,E=u),_=s(_,y);let I=indexedDB.deleteDatabase(E+v);return I.onsuccess=function(){_()},I.onerror=function(R){_(R)},_[y]},t.BrowserLevel=S}),VU=zt(t=>{t.Level=_ne().BrowserLevel}),Tne=zt((t,e)=>{(function(r,n){typeof t=="object"&&typeof e<"u"?n(t):typeof define=="function"&&define.amd?define(["exports"],n):n(r.URI=r.URI||{})})(t,function(r){"use strict";function n(){for(var J=arguments.length,ie=Array(J),oe=0;oe<J;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,be=1;be<ye;++be)ie[be]=ie[be].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(J){return"(?:"+J+")"}function a(J){return J===void 0?"undefined":J===null?"null":Object.prototype.toString.call(J).split(" ").pop().split("]").shift().toLowerCase()}function o(J){return J.toUpperCase()}function i(J){return J!=null?J instanceof Array?J:typeof J.length!="number"||J.split||J.setInterval||J.call?[J]:Array.prototype.slice.call(J):[]}function c(J,ie){var oe=J;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(J){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",be="[\\x22]",ze=n(ye,"[A-Fa-f]"),At="[\\x0A]",ur="[\\x20]",zr=s(s("%[EFef]"+ze+"%"+ze+ze+"%"+ze+ze)+"|"+s("%[89A-Fa-f]"+ze+"%"+ze+ze)+"|"+s("%"+ze+ze)),qr="[\\:\\/\\?\\#\\[\\]\\@]",tr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",pn=n(qr,tr),$n=J?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",sn=J?"[\\uE000-\\uF8FF]":"[]",wr=n(ie,ye,"[\\-\\.\\_\\~]",$n),mr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Ns=s(s(zr+"|"+n(wr,tr,"[\\:]"))+"*"),sm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),Ti=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Yo=s(Ti+"\\."+Ti+"\\."+Ti+"\\."+Ti),vr=s(ze+"{1,4}"),Fi=s(s(vr+"\\:"+vr)+"|"+Yo),bo=s(s(vr+"\\:")+"{6}"+Fi),Tc=s("\\:\\:"+s(vr+"\\:")+"{5}"+Fi),Yu=s(s(vr)+"?\\:\\:"+s(vr+"\\:")+"{4}"+Fi),ja=s(s(s(vr+"\\:")+"{0,1}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{3}"+Fi),Vw=s(s(s(vr+"\\:")+"{0,2}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{2}"+Fi),Hw=s(s(s(vr+"\\:")+"{0,3}"+vr)+"?\\:\\:"+vr+"\\:"+Fi),Ff=s(s(s(vr+"\\:")+"{0,4}"+vr)+"?\\:\\:"+Fi),Gf=s(s(s(vr+"\\:")+"{0,5}"+vr)+"?\\:\\:"+vr),Wf=s(s(s(vr+"\\:")+"{0,6}"+vr)+"?\\:\\:"),Qu=s([bo,Tc,Yu,ja,Vw,Hw,Ff,Gf,Wf].join("|")),Vf=s(s(wr+"|"+zr)+"+"),Hf=s(Qu+"\\%25"+Vf),cz=s(Qu+s("\\%25|\\%(?!"+ze+"{2})")+Vf),dz=s("[vV]"+ze+"+\\."+n(wr,tr,"[\\:]")+"+"),uz=s("\\["+s(cz+"|"+Qu+"|"+dz)+"\\]"),QA=s(s(zr+"|"+n(wr,tr))+"*"),im=s(uz+"|"+Yo+"(?!"+QA+")|"+QA),om=s(ye+"*"),XA=s(s(Ns+"@")+"?"+im+s("\\:"+om)+"?"),am=s(zr+"|"+n(wr,tr,"[\\:\\@]")),lz=s(am+"*"),eR=s(am+"+"),fz=s(s(zr+"|"+n(wr,tr,"[\\@]"))+"+"),Ic=s(s("\\/"+lz)+"*"),Jf=s("\\/"+s(eR+Ic)+"?"),jP=s(fz+Ic),Jw=s(eR+Ic),Zf="(?!"+am+")",yue=s(Ic+"|"+Jf+"|"+jP+"|"+Jw+"|"+Zf),Yf=s(s(am+"|"+n("[\\/\\?]",sn))+"*"),cm=s(s(am+"|[\\/\\?]")+"*"),tR=s(s("\\/\\/"+XA+Ic)+"|"+Jf+"|"+Jw+"|"+Zf),pz=s(mr+"\\:"+tR+s("\\?"+Yf)+"?"+s("\\#"+cm)+"?"),hz=s(s("\\/\\/"+XA+Ic)+"|"+Jf+"|"+jP+"|"+Zf),mz=s(hz+s("\\?"+Yf)+"?"+s("\\#"+cm)+"?"),gue=s(pz+"|"+mz),wue=s(mr+"\\:"+tR+s("\\?"+Yf)+"?"),vue="^("+mr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+Jw+"|"+Zf+")")+s("\\?("+Yf+")")+"?"+s("\\#("+cm+")")+"?$",bue="^(){0}"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+jP+"|"+Zf+")")+s("\\?("+Yf+")")+"?"+s("\\#("+cm+")")+"?$",Pue="^("+mr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+Jw+"|"+Zf+")")+s("\\?("+Yf+")")+"?$",xue="^"+s("\\#("+cm+")")+"?$",Sue="^"+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",wr,tr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",wr,tr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",wr,tr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",wr,tr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",wr,tr,"[\\:\\@\\/\\?]",sn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",wr,tr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",wr,tr),"g"),UNRESERVED:new RegExp(wr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",wr,pn),"g"),PCT_ENCODED:new RegExp(zr,"g"),IPV4ADDRESS:new RegExp("^("+Yo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Qu+")"+s(s("\\%25|\\%(?!"+ze+"{2})")+"("+Vf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function J(ie,oe){var ye=[],be=!0,ze=!1,At=void 0;try{for(var ur=ie[Symbol.iterator](),zr;!(be=(zr=ur.next()).done)&&(ye.push(zr.value),!(oe&&ye.length===oe));be=!0);}catch(qr){ze=!0,At=qr}finally{try{!be&&ur.return&&ur.return()}finally{if(ze)throw At}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return J(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(J){if(Array.isArray(J)){for(var ie=0,oe=Array(J.length);ie<J.length;ie++)oe[ie]=J[ie];return oe}else return Array.from(J)},p=2147483647,m=36,y=1,S=26,v=38,E=700,_=72,I=128,R="-",N=/^xn--/,$=/[^\0-\x7E]/,F=/[\x2E\u3002\uFF0E\uFF61]/g,z={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,W=Math.floor,X=String.fromCharCode;function D(J){throw new RangeError(z[J])}function C(J,ie){for(var oe=[],ye=J.length;ye--;)oe[ye]=ie(J[ye]);return oe}function b(J,ie){var oe=J.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",J=oe[1]),J=J.replace(F,".");var be=J.split("."),ze=C(be,ie).join(".");return ye+ze}function x(J){for(var ie=[],oe=0,ye=J.length;oe<ye;){var be=J.charCodeAt(oe++);if(be>=55296&&be<=56319&&oe<ye){var ze=J.charCodeAt(oe++);(ze&64512)==56320?ie.push(((be&1023)<<10)+(ze&1023)+65536):(ie.push(be),oe--)}else ie.push(be)}return ie}var P=function(J){return String.fromCodePoint.apply(String,h(J))},k=function(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:m},A=function(J,ie){return J+22+75*(J<26)-((ie!=0)<<5)},O=function(J,ie,oe){var ye=0;for(J=oe?W(J/E):J>>1,J+=W(J/ie);J>B*S>>1;ye+=m)J=W(J/B);return W(ye+(B+1)*J/(J+v))},q=function(J){var ie=[],oe=J.length,ye=0,be=I,ze=_,At=J.lastIndexOf(R);At<0&&(At=0);for(var ur=0;ur<At;++ur)J.charCodeAt(ur)>=128&&D("not-basic"),ie.push(J.charCodeAt(ur));for(var zr=At>0?At+1:0;zr<oe;){for(var qr=ye,tr=1,pn=m;;pn+=m){zr>=oe&&D("invalid-input");var $n=k(J.charCodeAt(zr++));($n>=m||$n>W((p-ye)/tr))&&D("overflow"),ye+=$n*tr;var sn=pn<=ze?y:pn>=ze+S?S:pn-ze;if($n<sn)break;var wr=m-sn;tr>W(p/wr)&&D("overflow"),tr*=wr}var mr=ie.length+1;ze=O(ye-qr,mr,qr==0),W(ye/mr)>p-be&&D("overflow"),be+=W(ye/mr),ye%=mr,ie.splice(ye++,0,be)}return String.fromCodePoint.apply(String,ie)},G=function(J){var ie=[];J=x(J);var oe=J.length,ye=I,be=0,ze=_,At=!0,ur=!1,zr=void 0;try{for(var qr=J[Symbol.iterator](),tr;!(At=(tr=qr.next()).done);At=!0){var pn=tr.value;pn<128&&ie.push(X(pn))}}catch(Hf){ur=!0,zr=Hf}finally{try{!At&&qr.return&&qr.return()}finally{if(ur)throw zr}}var $n=ie.length,sn=$n;for($n&&ie.push(R);sn<oe;){var wr=p,mr=!0,Ns=!1,sm=void 0;try{for(var Ti=J[Symbol.iterator](),Yo;!(mr=(Yo=Ti.next()).done);mr=!0){var vr=Yo.value;vr>=ye&&vr<wr&&(wr=vr)}}catch(Hf){Ns=!0,sm=Hf}finally{try{!mr&&Ti.return&&Ti.return()}finally{if(Ns)throw sm}}var Fi=sn+1;wr-ye>W((p-be)/Fi)&&D("overflow"),be+=(wr-ye)*Fi,ye=wr;var bo=!0,Tc=!1,Yu=void 0;try{for(var ja=J[Symbol.iterator](),Vw;!(bo=(Vw=ja.next()).done);bo=!0){var Hw=Vw.value;if(Hw<ye&&++be>p&&D("overflow"),Hw==ye){for(var Ff=be,Gf=m;;Gf+=m){var Wf=Gf<=ze?y:Gf>=ze+S?S:Gf-ze;if(Ff<Wf)break;var Qu=Ff-Wf,Vf=m-Wf;ie.push(X(A(Wf+Qu%Vf,0))),Ff=W(Qu/Vf)}ie.push(X(A(Ff,0))),ze=O(be,Fi,sn==$n),be=0,++sn}}}catch(Hf){Tc=!0,Yu=Hf}finally{try{!bo&&ja.return&&ja.return()}finally{if(Tc)throw Yu}}++be,++ye}return ie.join("")},V=function(J){return b(J,function(ie){return N.test(ie)?q(ie.slice(4).toLowerCase()):ie})},H=function(J){return b(J,function(ie){return $.test(ie)?"xn--"+G(ie):ie})},Y={version:"2.1.0",ucs2:{decode:x,encode:P},decode:q,encode:G,toASCII:H,toUnicode:V},K={};function Q(J){var ie=J.charCodeAt(0),oe=void 0;return ie<16?oe="%0"+ie.toString(16).toUpperCase():ie<128?oe="%"+ie.toString(16).toUpperCase():ie<2048?oe="%"+(ie>>6|192).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase():oe="%"+(ie>>12|224).toString(16).toUpperCase()+"%"+(ie>>6&63|128).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase(),oe}function se(J){for(var ie="",oe=0,ye=J.length;oe<ye;){var be=parseInt(J.substr(oe+1,2),16);if(be<128)ie+=String.fromCharCode(be),oe+=3;else if(be>=194&&be<224){if(ye-oe>=6){var ze=parseInt(J.substr(oe+4,2),16);ie+=String.fromCharCode((be&31)<<6|ze&63)}else ie+=J.substr(oe,6);oe+=6}else if(be>=224){if(ye-oe>=9){var At=parseInt(J.substr(oe+4,2),16),ur=parseInt(J.substr(oe+7,2),16);ie+=String.fromCharCode((be&15)<<12|(At&63)<<6|ur&63)}else ie+=J.substr(oe,9);oe+=9}else ie+=J.substr(oe,3),oe+=3}return ie}function re(J,ie){function oe(ye){var be=se(ye);return be.match(ie.UNRESERVED)?be:ye}return J.scheme&&(J.scheme=String(J.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),J.userinfo!==void 0&&(J.userinfo=String(J.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Q).replace(ie.PCT_ENCODED,o)),J.host!==void 0&&(J.host=String(J.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Q).replace(ie.PCT_ENCODED,o)),J.path!==void 0&&(J.path=String(J.path).replace(ie.PCT_ENCODED,oe).replace(J.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Q).replace(ie.PCT_ENCODED,o)),J.query!==void 0&&(J.query=String(J.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Q).replace(ie.PCT_ENCODED,o)),J.fragment!==void 0&&(J.fragment=String(J.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Q).replace(ie.PCT_ENCODED,o)),J}function Z(J){return J.replace(/^0*(.*)/,"$1")||"0"}function de(J,ie){var oe=J.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),be=ye[1];return be?be.split(".").map(Z).join("."):J}function le(J,ie){var oe=J.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),be=ye[1],ze=ye[2];if(be){for(var At=be.toLowerCase().split("::").reverse(),ur=f(At,2),zr=ur[0],qr=ur[1],tr=qr?qr.split(":").map(Z):[],pn=zr.split(":").map(Z),$n=ie.IPV4ADDRESS.test(pn[pn.length-1]),sn=$n?7:8,wr=pn.length-sn,mr=Array(sn),Ns=0;Ns<sn;++Ns)mr[Ns]=tr[Ns]||pn[wr+Ns]||"";$n&&(mr[sn-1]=de(mr[sn-1],ie));var sm=mr.reduce(function(bo,Tc,Yu){if(!Tc||Tc==="0"){var ja=bo[bo.length-1];ja&&ja.index+ja.length===Yu?ja.length++:bo.push({index:Yu,length:1})}return bo},[]),Ti=sm.sort(function(bo,Tc){return Tc.length-bo.length})[0],Yo=void 0;if(Ti&&Ti.length>1){var vr=mr.slice(0,Ti.index),Fi=mr.slice(Ti.index+Ti.length);Yo=vr.join(":")+"::"+Fi.join(":")}else Yo=mr.join(":");return ze&&(Yo+="%"+ze),Yo}else return J}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ve="".match(/(){0}/)[1]===void 0;function ce(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(J=(ie.scheme?ie.scheme+":":"")+"//"+J);var be=J.match(pe);if(be){ve?(oe.scheme=be[1],oe.userinfo=be[3],oe.host=be[4],oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=be[7],oe.fragment=be[8],isNaN(oe.port)&&(oe.port=be[5])):(oe.scheme=be[1]||void 0,oe.userinfo=J.indexOf("@")!==-1?be[3]:void 0,oe.host=J.indexOf("//")!==-1?be[4]:void 0,oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=J.indexOf("?")!==-1?be[7]:void 0,oe.fragment=J.indexOf("#")!==-1?be[8]:void 0,isNaN(oe.port)&&(oe.port=J.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?be[4]:void 0)),oe.host&&(oe.host=le(de(oe.host,ye),ye)),oe.scheme===void 0&&oe.userinfo===void 0&&oe.host===void 0&&oe.port===void 0&&!oe.path&&oe.query===void 0?oe.reference="same-document":oe.scheme===void 0?oe.reference="relative":oe.fragment===void 0?oe.reference="absolute":oe.reference="uri",ie.reference&&ie.reference!=="suffix"&&ie.reference!==oe.reference&&(oe.error=oe.error||"URI is not a "+ie.reference+" reference.");var ze=K[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!ze||!ze.unicodeSupport)){if(oe.host&&(ie.domainHost||ze&&ze.domainHost))try{oe.host=Y.toASCII(oe.host.replace(ye.PCT_ENCODED,se).toLowerCase())}catch(At){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+At}re(oe,d)}else re(oe,ye);ze&&ze.parse&&ze.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function ge(J,ie){var oe=ie.iri!==!1?l:d,ye=[];return J.userinfo!==void 0&&(ye.push(J.userinfo),ye.push("@")),J.host!==void 0&&ye.push(le(de(String(J.host),oe),oe).replace(oe.IPV6ADDRESS,function(be,ze,At){return"["+ze+(At?"%25"+At:"")+"]"})),(typeof J.port=="number"||typeof J.port=="string")&&(ye.push(":"),ye.push(String(J.port))),ye.length?ye.join(""):void 0}var Me=/^\.\.?\//,Le=/^\/\.(\/|$)/,qe=/^\/\.\.(\/|$)/,Et=/^\/?(?:.|\n)*?(?=\/|$)/;function Se(J){for(var ie=[];J.length;)if(J.match(Me))J=J.replace(Me,"");else if(J.match(Le))J=J.replace(Le,"/");else if(J.match(qe))J=J.replace(qe,"/"),ie.pop();else if(J==="."||J==="..")J="";else{var oe=J.match(Et);if(oe){var ye=oe[0];J=J.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function et(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],be=K[(ie.scheme||J.scheme||"").toLowerCase()];if(be&&be.serialize&&be.serialize(J,ie),J.host&&!oe.IPV6ADDRESS.test(J.host)&&(ie.domainHost||be&&be.domainHost))try{J.host=ie.iri?Y.toUnicode(J.host):Y.toASCII(J.host.replace(oe.PCT_ENCODED,se).toLowerCase())}catch(ur){J.error=J.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+ur}re(J,oe),ie.reference!=="suffix"&&J.scheme&&(ye.push(J.scheme),ye.push(":"));var ze=ge(J,ie);if(ze!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(ze),J.path&&J.path.charAt(0)!=="/"&&ye.push("/")),J.path!==void 0){var At=J.path;!ie.absolutePath&&(!be||!be.absolutePath)&&(At=Se(At)),ze===void 0&&(At=At.replace(/^\/\//,"/%2F")),ye.push(At)}return J.query!==void 0&&(ye.push("?"),ye.push(J.query)),J.fragment!==void 0&&(ye.push("#"),ye.push(J.fragment)),ye.join("")}function wt(J,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],be={};return ye||(J=ce(et(J,oe),oe),ie=ce(et(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(be.scheme=ie.scheme,be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?be.path=Se(ie.path):((J.userinfo!==void 0||J.host!==void 0||J.port!==void 0)&&!J.path?be.path="/"+ie.path:J.path?be.path=J.path.slice(0,J.path.lastIndexOf("/")+1)+ie.path:be.path=ie.path,be.path=Se(be.path)),be.query=ie.query):(be.path=J.path,ie.query!==void 0?be.query=ie.query:be.query=J.query),be.userinfo=J.userinfo,be.host=J.host,be.port=J.port),be.scheme=J.scheme),be.fragment=ie.fragment,be}function St(J,ie,oe){var ye=c({scheme:"null"},oe);return et(wt(ce(J,ye),ce(ie,ye),ye,!0),ye)}function Mt(J,ie){return typeof J=="string"?J=et(ce(J,ie),ie):a(J)==="object"&&(J=ce(et(J,ie),ie)),J}function T(J,ie,oe){return typeof J=="string"?J=et(ce(J,oe),oe):a(J)==="object"&&(J=et(J,oe)),typeof ie=="string"?ie=et(ce(ie,oe),oe):a(ie)==="object"&&(ie=et(ie,oe)),J===ie}function M(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Q)}function L(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(J,ie){return J.host||(J.error=J.error||"HTTP URIs must have a host."),J},serialize:function(J,ie){var oe=String(J.scheme).toLowerCase()==="https";return(J.port===(oe?443:80)||J.port==="")&&(J.port=void 0),J.path||(J.path="/"),J}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(J){return typeof J.secure=="boolean"?J.secure:String(J.scheme).toLowerCase()==="wss"}var xe={scheme:"ws",domainHost:!0,parse:function(J,ie){var oe=J;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(J,ie){if((J.port===(he(J)?443:80)||J.port==="")&&(J.port=void 0),typeof J.secure=="boolean"&&(J.scheme=J.secure?"wss":"ws",J.secure=void 0),J.resourceName){var oe=J.resourceName.split("?"),ye=f(oe,2),be=ye[0],ze=ye[1];J.path=be&&be!=="/"?be:void 0,J.query=ze,J.resourceName=void 0}return J.fragment=void 0,J}},Ot={scheme:"wss",domainHost:xe.domainHost,parse:xe.parse,serialize:xe.serialize},Un={},Or=!0,hr="[A-Za-z0-9\\-\\.\\_\\~"+(Or?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",ir="[0-9A-Fa-f]",Q9=s(s("%[EFef]"+ir+"%"+ir+ir+"%"+ir+ir)+"|"+s("%[89A-Fa-f]"+ir+"%"+ir+ir)+"|"+s("%"+ir+ir)),X9="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",ez="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",tz=n(ez,'[\\"\\\\]'),rz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",nz=new RegExp(hr,"g"),qf=new RegExp(Q9,"g"),sz=new RegExp(n("[^]",X9,"[\\.]",'[\\"]',tz),"g"),HA=new RegExp(n("[^]",hr,rz),"g"),iz=HA;function CP(J){var ie=se(J);return ie.match(nz)?ie:J}var JA={scheme:"mailto",parse:function(J,ie){var oe=J,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var be=!1,ze={},At=oe.query.split("&"),ur=0,zr=At.length;ur<zr;++ur){var qr=At[ur].split("=");switch(qr[0]){case"to":for(var tr=qr[1].split(","),pn=0,$n=tr.length;pn<$n;++pn)ye.push(tr[pn]);break;case"subject":oe.subject=L(qr[1],ie);break;case"body":oe.body=L(qr[1],ie);break;default:be=!0,ze[L(qr[0],ie)]=L(qr[1],ie);break}}be&&(oe.headers=ze)}oe.query=void 0;for(var sn=0,wr=ye.length;sn<wr;++sn){var mr=ye[sn].split("@");if(mr[0]=L(mr[0]),ie.unicodeSupport)mr[1]=L(mr[1],ie).toLowerCase();else try{mr[1]=Y.toASCII(L(mr[1],ie).toLowerCase())}catch(Ns){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ns}ye[sn]=mr.join("@")}return oe},serialize:function(J,ie){var oe=J,ye=i(J.to);if(ye){for(var be=0,ze=ye.length;be<ze;++be){var At=String(ye[be]),ur=At.lastIndexOf("@"),zr=At.slice(0,ur).replace(qf,CP).replace(qf,o).replace(sz,Q),qr=At.slice(ur+1);try{qr=ie.iri?Y.toUnicode(qr):Y.toASCII(L(qr,ie).toLowerCase())}catch(sn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+sn}ye[be]=zr+"@"+qr}oe.path=ye.join(",")}var tr=J.headers=J.headers||{};J.subject&&(tr.subject=J.subject),J.body&&(tr.body=J.body);var pn=[];for(var $n in tr)tr[$n]!==Un[$n]&&pn.push($n.replace(qf,CP).replace(qf,o).replace(HA,Q)+"="+tr[$n].replace(qf,CP).replace(qf,o).replace(iz,Q));return pn.length&&(oe.query=pn.join("&")),oe}},oz=/^([^\:]+)\:(.*)/,ZA={scheme:"urn",parse:function(J,ie){var oe=J.path&&J.path.match(oz),ye=J;if(oe){var be=ie.scheme||ye.scheme||"urn",ze=oe[1].toLowerCase(),At=oe[2],ur=be+":"+(ie.nid||ze),zr=K[ur];ye.nid=ze,ye.nss=At,ye.path=void 0,zr&&(ye=zr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(J,ie){var oe=ie.scheme||J.scheme||"urn",ye=J.nid,be=oe+":"+(ie.nid||ye),ze=K[be];ze&&(J=ze.serialize(J,ie));var At=J,ur=J.nss;return At.path=(ye||ie.nid)+":"+ur,At}},az=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,YA={scheme:"urn:uuid",parse:function(J,ie){var oe=J;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(az))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(J,ie){var oe=J;return oe.nss=(J.uuid||"").toLowerCase(),oe}};K[te.scheme]=te,K[ae.scheme]=ae,K[xe.scheme]=xe,K[Ot.scheme]=Ot,K[JA.scheme]=JA,K[ZA.scheme]=ZA,K[YA.scheme]=YA,r.SCHEMES=K,r.pctEncChar=Q,r.pctDecChars=se,r.parse=ce,r.removeDotSegments=Se,r.serialize=et,r.resolveComponents=wt,r.resolve=St,r.normalize=Mt,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),Ine=zt((t,e)=>{"use strict";e.exports=function r(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?r(n.toJSON()):Array.isArray(n)?`[${n.reduce((s,a,o)=>`${s}${o===0?"":","}${r(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((s,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return s;let o=s.length===0?"":",";return`${s}${o}${r(a)}:${r(n[a])}`},"")}}`}}),HU=zt((t,e)=>{var r=1e3,n=r*60,s=n*60,a=s*24,o=a*7,i=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return c(f);if(p==="number"&&isFinite(f))return h.long?d(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var 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*i;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*s;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*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function u(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=s?Math.round(f/s)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function d(f){var h=Math.abs(f);return h>=a?l(f,h,a,"day"):h>=s?l(f,h,s,"hour"):h>=n?l(f,h,n,"minute"):h>=r?l(f,h,r,"second"):f+" ms"}function l(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),tP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(tP||{}),us={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Cs=class JU{constructor({method:e,id:r,path:n,query:s,fragment:a,params:o}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=s,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let r=JU.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:s,path:a,query:o,fragment:i}=r.groups,c={uri:`did:${n}:${s}`,method:n,id:s};if(a&&(c.path=a),o&&(c.query=o.slice(1)),i&&(c.fragment=i.slice(1)),o){let u={},d=o.slice(1).split("&");for(let l of d){let[f,h]=l.split("=");u[f]=h}c.params=u}return c}};Cs.METHOD_PATTERN="([a-z0-9]+)",Cs.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Cs.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Cs.PCT_ENCODED_PATTERN})`,Cs.METHOD_ID_PATTERN=`((?:${Cs.ID_CHAR_PATTERN}*:)*(${Cs.ID_CHAR_PATTERN}+))`,Cs.PATH_PATTERN="(/[^#?]*)?",Cs.QUERY_PATTERN="([?][^#]*)?",Cs.FRAGMENT_PATTERN="(#.*)?",Cs.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Cs.METHOD_PATTERN+"):(?<id>"+Cs.METHOD_ID_PATTERN+")(?<path>"+Cs.PATH_PATTERN+")(?<query>"+Cs.QUERY_PATTERN+")(?<fragment>"+Cs.FRAGMENT_PATTERN+")$");var ls=Cs,Ze=class ZU extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ZU)}},Ane=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType",t))(Ane||{}),Vo=class YU extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,YU)}},Ki;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Ki||(Ki={}));var Rne=Df(cne(),1);function Dne(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<t.length;s++){var a=t.charAt(s),o=a.charCodeAt(0);if(r[o]!==255)throw new TypeError(a+" is ambiguous");r[o]=s}var i=t.length,c=t.charAt(0),u=Math.log(i)/Math.log(256),d=Math.log(256)/Math.log(i);function l(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,S=0,v=p.length;S!==v&&p[S]===0;)S++,m++;for(var E=(v-S)*d+1>>>0,_=new Uint8Array(E);S!==v;){for(var I=p[S],R=0,N=E-1;(I!==0||R<y)&&N!==-1;N--,R++)I+=256*_[N]>>>0,_[N]=I%i>>>0,I=I/i>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,S++}for(var $=E-y;$!==E&&_[$]===0;)$++;for(var F=c.repeat(m);$<E;++$)F+=t.charAt(_[$]);return F}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,S=0;p[m]===c;)y++,m++;for(var v=(p.length-m)*u+1>>>0,E=new Uint8Array(v);p[m];){var _=r[p.charCodeAt(m)];if(_===255)return;for(var I=0,R=v-1;(_!==0||I<S)&&R!==-1;R--,I++)_+=i*E[R]>>>0,E[R]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");S=I,m++}if(p[m]!==" "){for(var N=v-S;N!==v&&E[N]===0;)N++;for(var $=new Uint8Array(y+(v-N)),F=y;N!==v;)$[F++]=E[N++];return $}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Cne=Dne,jne=Cne,$ne=jne,Lje=new Uint8Array(0),Mne=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},KI=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},One=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Bne=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return QU(this,t)}},Nne=class{constructor(t){this.decoders=t}or(t){return QU(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},QU=(t,e)=>new Nne({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Une=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new One(t,e,r),this.decoder=new Bne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},XU=({name:t,prefix:e,encode:r,decode:n})=>new Une(t,e,r,n),eL=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=$ne(r,e);return XU({prefix:t,name:e,encode:n,decode:a=>KI(s(a))})},Lne=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Kne=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},go=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>XU({prefix:e,name:t,encode(s){return Kne(s,n,r)},decode(s){return Lne(s,n,r,t)}}),x1=go({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Kje=go({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zje=go({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qje=go({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fje=go({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gje=go({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wje=go({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vje=go({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),SN=go({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Go=eL({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hje=eL({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Jje=go({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zje=go({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),md=go({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yje=go({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function zne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function qne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function yI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Hg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},EN=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(o){return new Promise(function(i,c){o=t[a](o),s(i,c,o.done,o.value)})}}function s(a,o,i,c){Promise.resolve(c).then(function(u){a({value:u,done:i})},o)}},h1=new TextEncoder,gf=new TextDecoder,Qe=class Ui{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ui(e,"ArrayBuffer")}static asyncIterable(e){if(!qne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ui(e,"AsyncIterable")}static base32Z(e){return new Ui(e,"Base32Z")}static base58Btc(e){return new Ui(e,"Base58Btc")}static base64Url(e){return new Ui(e,"Base64Url")}static bufferSource(e){return new Ui(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 Ui(e,"Hex")}static multibase(e){return new Ui(e,"Multibase")}static object(e){return new Ui(e,"Object")}static string(e){return new Ui(e,"String")}static uint8Array(e){return new Ui(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Go.baseDecode(this.data).buffer;case"Base64Url":return md.baseDecode(this.data).buffer;case"BufferSource":{if(yI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return zne(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 Hg(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 SN.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 Go.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Go.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 md.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return md.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=h1.encode(e);return md.baseEncode(r)}case"String":{let e=h1.encode(this.data);return md.baseEncode(e)}case"Uint8Array":return md.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Hg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=EN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;c.push(u)}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return Ui.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ui.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}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=md.baseDecode(this.data),r=gf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=gf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Hg(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 gf.decode(this.data);case"Base64Url":{let e=md.baseDecode(this.data);return gf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return gf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Hg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=EN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;typeof u=="string"?c+=u:c+=gf.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return c+=gf.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return SN.baseDecode(this.data);case"Base58Btc":return Go.baseDecode(this.data);case"Base64Url":return md.baseDecode(this.data);case"BufferSource":{let e=yI(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 r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return h1.encode(e)}case"String":return h1.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Hg(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.`)}})}},yw;(function(t){t.Debug="debug",t.Silent="silent"})(yw||(yw={}));var Fne=class{constructor(){this.logLevel=yw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==yw.Silent&&console.info(t)}error(t){this.logLevel!==yw.Silent&&console.error(t)}},Gne=new Fne;typeof window<"u"&&(window.enboxLogger=Gne);var tw={};NI(tw,{decode:()=>q1,encodeTo:()=>ww,encodingLength:()=>vw});var Wne=tL,kN=128,Vne=127,Hne=~Vne,Jne=Math.pow(2,31);function tL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Jne;)e[r++]=t&255|kN,t/=128;for(;t&Hne;)e[r++]=t&255|kN,t>>>=7;return e[r]=t|0,tL.bytes=r-n+1,e}var Zne=gI,Yne=128,_N=127;function gI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw gI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&_N)<<s:(o&_N)*Math.pow(2,s),s+=7}while(o>=Yne);return gI.bytes=a-n,r}var Qne=Math.pow(2,7),Xne=Math.pow(2,14),ese=Math.pow(2,21),tse=Math.pow(2,28),rse=Math.pow(2,35),nse=Math.pow(2,42),sse=Math.pow(2,49),ise=Math.pow(2,56),ose=Math.pow(2,63),ase=function(t){return t<Qne?1:t<Xne?2:t<ese?3:t<tse?4:t<rse?5:t<nse?6:t<sse?7:t<ise?8:t<ose?9:10},cse={encode:Wne,decode:Zne,encodingLength:ase},dse=cse,z1=dse,q1=(t,e=0)=>[z1.decode(t,e),z1.decode.bytes],ww=(t,e,r=0)=>(z1.encode(t,e,r),e),vw=t=>z1.encodingLength(t),use=(t,e)=>{let r=e.byteLength,n=vw(t),s=n+vw(r),a=new Uint8Array(s+r);return ww(t,a,0),ww(r,a,n),a.set(e,s),new zI(t,r,e,a)},lse=t=>{let e=KI(t),[r,n]=q1(e),[s,a]=q1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new zI(r,s,o,e)},fse=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Mne(t.bytes,r.bytes)}},zI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},TN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return hse(r,wI(t),e||Go.encoder);default:return mse(r,wI(t),e||x1.encoder)}},IN=new WeakMap,wI=t=>{let e=IN.get(t);if(e==null){let r=new Map;return IN.set(t,r),r}return e},Qje=class Xs{constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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:r}=this;if(e!==Jg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Xs.createV0(r)}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:r}=this.multihash,n=use(e,r);return Xs.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 Xs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&fse(e.multihash,n.multihash)}toString(e){return TN(this,e)}toJSON(){return{"/":TN(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 r=e;if(r instanceof Xs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Xs(n,s,a,o||AN(n,s,a.bytes))}else if(r[gse]===!0){let{version:n,multihash:s,code:a}=r,o=lse(s);return Xs.create(n,a,o)}else return null}static create(e,r,n){if(typeof r!="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(r!==Jg)throw new Error(`Version 0 CID must use dag-pb (code: ${Jg}) block encoding`);return new Xs(e,r,n,n.bytes)}case 1:{let s=AN(e,r,n.bytes);return new Xs(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Xs.create(0,Jg,e)}static createV1(e,r){return Xs.create(1,e,r)}static decode(e){let[r,n]=Xs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Xs.inspectBytes(e),n=r.size-r.multihashSize,s=KI(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=s.subarray(r.multihashSize-r.digestSize),o=new zI(r.multihashCode,r.digestSize,a,s);return[r.version===0?Xs.createV0(o):Xs.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=q1(e.subarray(r));return r+=f,l},s=n(),a=Jg;if(s===18?(s=0,r=0):a=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=r,i=n(),c=n(),u=r+c,d=u-o;return{version:s,codec:a,multihashCode:i,digestSize:c,multihashSize:d,size:u}}static parse(e,r){let[n,s]=pse(e,r),a=Xs.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return wI(a).set(n,e),a}},pse=(t,e)=>{switch(t[0]){case"Q":{let r=e||Go;return[Go.prefix,r.decode(`${Go.prefix}${t}`)]}case Go.prefix:{let r=e||Go;return[Go.prefix,r.decode(t)]}case x1.prefix:{let r=e||x1;return[x1.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},hse=(t,e,r)=>{let{prefix:n}=r;if(n!==Go.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return s},mse=(t,e,r)=>{let{prefix:n}=r,s=e.get(n);if(s==null){let a=r.encode(t);return e.set(n,a),a}else return s},Jg=112,yse=18,AN=(t,e,r)=>{let n=vw(t),s=n+vw(e),a=new Uint8Array(s+r.byteLength);return ww(t,a,0),ww(e,a,n),a.set(r,s),a},gse=Symbol.for("@ipld/js-cid/CID"),Jo=class Lu{static addPrefix(e){var r;let{code:n,data:s,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=Lu.codeToName.has(n)?n:Lu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=tw.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),tw.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=tw.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Lu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Lu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Lu.codeToName.set(e.code,e.name),Lu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=tw.decode(r),a=Lu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Jo.codeToName=new Map;Jo.nameToCode=new Map;Jo.registerCodec({code:237,name:"ed25519-pub"});Jo.registerCodec({code:4864,name:"ed25519-priv"});Jo.registerCodec({code:236,name:"x25519-pub"});Jo.registerCodec({code:4866,name:"x25519-priv"});Jo.registerCodec({code:231,name:"secp256k1-pub"});Jo.registerCodec({code:4865,name:"secp256k1-priv"});function rL(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&rL(t[e])})}var Xje=Df(VU(),1),Ru=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},wse=class{constructor(){this.store=new Map}clear(){return Ru(this,void 0,void 0,function*(){this.store.clear()})}open(){return Ru(this,void 0,void 0,function*(){})}close(){return Ru(this,void 0,void 0,function*(){})}delete(t){return Ru(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Ru(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Ru(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Ru(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Ru(this,void 0,void 0,function*(){this.store.set(t,e)})}},rP=class{},nL={};NI(nL,{bitGet:()=>kse,bitLen:()=>Ese,bitMask:()=>FI,bitSet:()=>_se,bytesToHex:()=>If,bytesToNumberBE:()=>kf,bytesToNumberLE:()=>Gu,concatBytes:()=>Af,createHmacDrbg:()=>oL,ensureBytes:()=>Cn,equalBytes:()=>xse,hexToBytes:()=>Fh,hexToNumber:()=>qI,isBytes:()=>Sc,numberToBytesBE:()=>Ec,numberToBytesLE:()=>Gh,numberToHexUnpadded:()=>iL,numberToVarBytesBE:()=>Pse,utf8ToBytes:()=>Sse,validateObject:()=>Cf});var sL=BigInt(0),nP=BigInt(1),vse=BigInt(2);function Sc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var bse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function If(t){if(!Sc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=bse[t[r]];return e}function iL(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function qI(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var yd={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function RN(t){if(t>=yd._0&&t<=yd._9)return t-yd._0;if(t>=yd._A&&t<=yd._F)return t-(yd._A-10);if(t>=yd._a&&t<=yd._f)return t-(yd._a-10)}function Fh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let s=0,a=0;s<r;s++,a+=2){let o=RN(t.charCodeAt(a)),i=RN(t.charCodeAt(a+1));if(o===void 0||i===void 0){let c=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[s]=o*16+i}return n}function kf(t){return qI(If(t))}function Gu(t){if(!Sc(t))throw new Error("Uint8Array expected");return qI(If(Uint8Array.from(t).reverse()))}function Ec(t,e){return Fh(t.toString(16).padStart(e*2,"0"))}function Gh(t,e){return Ec(t,e).reverse()}function Pse(t){return Fh(iL(t))}function Cn(t,e,r){let n;if(typeof e=="string")try{n=Fh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(Sc(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(`${t} expected ${r} bytes, got ${s}`);return n}function Af(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!Sc(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let s=0;s<t.length;s++){let a=t[s];r.set(a,n),n+=a.length}return r}function xse(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Sse(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Ese(t){let e;for(e=0;t>sL;t>>=nP,e+=1);return e}function kse(t,e){return t>>BigInt(e)&nP}var _se=(t,e,r)=>t|(r?nP:sL)<<BigInt(e),FI=t=>(vse<<BigInt(t-1))-nP,oI=t=>new Uint8Array(t),DN=t=>Uint8Array.from(t);function oL(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=oI(t),s=oI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=oI())=>{s=i(DN([0]),d),n=i(),d.length!==0&&(s=i(DN([1]),d),n=i())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,l=[];for(;d<e;){n=i();let f=n.slice();l.push(f),d+=n.length}return Af(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var Tse={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Sc(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Cf(t,e,r={}){let n=(s,a,o)=>{let i=Tse[a];if(typeof i!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=t[s];if(!(o&&c===void 0)&&!i(c,t))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${a}`)};for(let[s,a]of Object.entries(e))n(s,a,!1);for(let[s,a]of Object.entries(r))n(s,a,!0);return t}function CN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Ise(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function aL(t,...e){if(!Ise(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Ase(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");CN(t.outputLen),CN(t.blockLen)}function F1(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Rse(t,e){aL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var aI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function cL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var cI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,Dse=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Dse)throw new Error("Non little-endian hardware is not supported");function dL(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function GI(t){if(typeof t=="string"&&(t=dL(t)),!cL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function uL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!cL(s))throw new Error("Uint8Array expected");e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let a=t[n];r.set(a,s),s+=a.length}return r}var lL=class{clone(){return this._cloneInto()}},e$e={}.toString;function fL(t){let e=n=>t().update(GI(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function WI(t=32){if(aI&&typeof aI.getRandomValues=="function")return aI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Cse(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var pL=class extends lL{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=cI(this.buffer)}update(t){F1(this);let{view:e,buffer:r,blockLen:n}=this;t=GI(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=cI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){F1(this),Rse(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let d=a;d<n;d++)e[d]=0;Cse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=cI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},jse=(t,e,r)=>t&e^~t&r,$se=(t,e,r)=>t&e^t&r^e&r,Mse=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]),Du=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cu=new Uint32Array(64),Ose=class extends pL{constructor(){super(64,32,8,!1),this.A=Du[0]|0,this.B=Du[1]|0,this.C=Du[2]|0,this.D=Du[3]|0,this.E=Du[4]|0,this.F=Du[5]|0,this.G=Du[6]|0,this.H=Du[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)Cu[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Cu[d-15],f=Cu[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;Cu[d]=p+Cu[d-7]+h+Cu[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=mc(o,6)^mc(o,11)^mc(o,25),f=u+l+jse(o,i,c)+Mse[d]+Cu[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+$se(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){Cu.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},hL=fL(()=>new Ose),Yn=BigInt(0),nn=BigInt(1),bf=BigInt(2),Bse=BigInt(3),vI=BigInt(4),jN=BigInt(5),$N=BigInt(8),t$e=BigInt(9),Nse=BigInt(16);function Kr(t,e){let r=t%e;return r>=Yn?r:e+r}function mL(t,e,r){if(r<=Yn||e<Yn)throw new Error("Expected power/modulo > 0");if(r===nn)return Yn;let n=nn;for(;e>Yn;)e&nn&&(n=n*t%r),t=t*t%r,e>>=nn;return n}function un(t,e,r){let n=t;for(;e-- >Yn;)n*=n,n%=r;return n}function bI(t,e){if(t===Yn||e<=Yn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Kr(t,e),n=e,s=Yn,a=nn,o=nn,i=Yn;for(;r!==Yn;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}if(n!==nn)throw new Error("invert: does not exist");return Kr(s,e)}function Use(t){let e=(t-nn)/bf,r,n,s;for(r=t-nn,n=0;r%bf===Yn;r/=bf,n++);for(s=bf;s<t&&mL(s,e,t)!==t-nn;s++);if(n===1){let o=(t+nn)/vI;return function(i,c){let u=i.pow(c,o);if(!i.eql(i.sqr(u),c))throw new Error("Cannot find square root");return u}}let a=(r+nn)/bf;return function(o,i){if(o.pow(i,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,s),r),d=o.pow(i,a),l=o.pow(i,r);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(l);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(u,nn<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function Lse(t){if(t%vI===Bse){let e=(t+nn)/vI;return function(r,n){let s=r.pow(n,e);if(!r.eql(r.sqr(s),n))throw new Error("Cannot find square root");return s}}if(t%$N===jN){let e=(t-jN)/$N;return function(r,n){let s=r.mul(n,bf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,bf),a),c=r.mul(o,r.sub(i,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return t%Nse,Use(t)}var Kse=(t,e)=>(Kr(t,e)&nn)===nn,zse=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qse(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=zse.reduce((n,s)=>(n[s]="function",n),e);return Cf(t,r)}function Fse(t,e,r){if(r<Yn)throw new Error("Expected power > 0");if(r===Yn)return t.ONE;if(r===nn)return e;let n=t.ONE,s=e;for(;r>Yn;)r&nn&&(n=t.mul(n,s)),s=t.sqr(s),r>>=nn;return n}function Gse(t,e){let r=new Array(e.length),n=e.reduce((a,o,i)=>t.is0(o)?a:(r[i]=a,t.mul(a,o)),t.ONE),s=t.inv(n);return e.reduceRight((a,o,i)=>t.is0(o)?a:(r[i]=t.mul(a,r[i]),t.mul(a,o)),s),r}function yL(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function VI(t,e,r=!1,n={}){if(t<=Yn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=yL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Lse(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:FI(s),ZERO:Yn,ONE:nn,create:c=>Kr(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Yn<=c&&c<t},is0:c=>c===Yn,isOdd:c=>(c&nn)===nn,neg:c=>Kr(-c,t),eql:(c,u)=>c===u,sqr:c=>Kr(c*c,t),add:(c,u)=>Kr(c+u,t),sub:(c,u)=>Kr(c-u,t),mul:(c,u)=>Kr(c*u,t),pow:(c,u)=>Fse(i,c,u),div:(c,u)=>Kr(c*bI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>bI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>Gse(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Gh(c,a):Ec(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Gu(c):kf(c)}});return Object.freeze(i)}function Wse(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function gL(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function wL(t){let e=gL(t);return e+Math.ceil(e/2)}function Vse(t,e,r=!1){let n=t.length,s=gL(e),a=wL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?kf(t):Gu(t),i=Kr(o,e-nn)+nn;return r?Gh(i,s):Ec(i,s)}var Hse=BigInt(0),dI=BigInt(1);function vL(t,e){let r=(s,a)=>{let o=a.negate();return s?o:a},n=s=>{let a=Math.ceil(e/s)+1,o=2**(s-1);return{windows:a,windowSize:o}};return{constTimeNegate:r,unsafeLadder(s,a){let o=t.ZERO,i=s;for(;a>Hse;)a&dI&&(o=o.add(i)),i=i.double(),a>>=dI;return o},precomputeWindow(s,a){let{windows:o,windowSize:i}=n(a),c=[],u=s,d=u;for(let l=0;l<o;l++){d=u,c.push(d);for(let f=1;f<i;f++)d=d.add(u),c.push(d);u=d.double()}return c},wNAF(s,a,o){let{windows:i,windowSize:c}=n(s),u=t.ZERO,d=t.BASE,l=BigInt(2**s-1),f=2**s,h=BigInt(s);for(let p=0;p<i;p++){let m=p*c,y=Number(o&l);o>>=h,y>c&&(y-=f,o+=dI);let S=m,v=m+Math.abs(y)-1,E=p%2!==0,_=y<0;y===0?d=d.add(r(E,a[S])):u=u.add(r(_,a[v]))}return{p:u,f:d}},wNAFCached(s,a,o,i){let c=s._WINDOW_SIZE||1,u=a.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&a.set(s,i(u))),this.wNAF(c,u,o)}}}function HI(t){return qse(t.Fp),Cf(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Jse(t){let e=HI(t);Cf(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Zse,hexToBytes:Yse}=nL,Sf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=Sf;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:Zse(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=Sf,r=typeof t=="string"?Yse(t):t;if(!Sc(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:s,l:a}=Sf._parseInt(r.subarray(2)),{d:o,l:i}=Sf._parseInt(a);if(i.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),s=e(r(t.r)),a=n.length/2,o=s.length/2,i=r(a),c=r(o);return`30${r(o+a+4)}02${c}${s}02${i}${n}`}},xd=BigInt(0),Fo=BigInt(1),r$e=BigInt(2),MN=BigInt(3),n$e=BigInt(4);function Qse(t){let e=Jse(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return Af(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),s=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),S=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:S}});function a(p){let{a:m,b:y}=e,S=r.sqr(p),v=r.mul(S,p);return r.add(r.add(v,r.mul(p,m)),y)}if(!r.eql(r.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function o(p){return typeof p=="bigint"&&xd<p&&p<e.n}function i(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:S,n:v}=e;if(m&&typeof p!="bigint"){if(Sc(p)&&(p=If(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:kf(Cn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Kr(E,v)),i(E),E}let u=new Map;function d(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,S){if(this.px=m,this.py=y,this.pz=S,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(m){let{x:y,y:S}=m||{};if(!m||!r.isValid(y)||!r.isValid(S))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let v=E=>r.eql(E,r.ZERO);return v(y)&&v(S)?l.ZERO:new l(y,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(S=>S.pz));return m.map((S,v)=>S.toAffine(y[v])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(s(Cn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let S=r.sqr(y),v=a(m);if(!r.eql(S,v))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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:_,pz:I}=m,R=r.eql(r.mul(y,I),r.mul(E,v)),N=r.eql(r.mul(S,I),r.mul(_,v));return R&&N}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,MN),{px:v,py:E,pz:_}=this,I=r.ZERO,R=r.ZERO,N=r.ZERO,$=r.mul(v,v),F=r.mul(E,E),z=r.mul(_,_),B=r.mul(v,E);return B=r.add(B,B),N=r.mul(v,_),N=r.add(N,N),I=r.mul(m,N),R=r.mul(S,z),R=r.add(I,R),I=r.sub(F,R),R=r.add(F,R),R=r.mul(I,R),I=r.mul(B,I),N=r.mul(S,N),z=r.mul(m,z),B=r.sub($,z),B=r.mul(m,B),B=r.add(B,N),N=r.add($,$),$=r.add(N,$),$=r.add($,z),$=r.mul($,B),R=r.add(R,$),z=r.mul(E,_),z=r.add(z,z),$=r.mul(z,B),I=r.sub(I,$),N=r.mul(z,F),N=r.add(N,N),N=r.add(N,N),new l(I,R,N)}add(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:_,pz:I}=m,R=r.ZERO,N=r.ZERO,$=r.ZERO,F=e.a,z=r.mul(e.b,MN),B=r.mul(y,E),W=r.mul(S,_),X=r.mul(v,I),D=r.add(y,S),C=r.add(E,_);D=r.mul(D,C),C=r.add(B,W),D=r.sub(D,C),C=r.add(y,v);let b=r.add(E,I);return C=r.mul(C,b),b=r.add(B,X),C=r.sub(C,b),b=r.add(S,v),R=r.add(_,I),b=r.mul(b,R),R=r.add(W,X),b=r.sub(b,R),$=r.mul(F,C),R=r.mul(z,X),$=r.add(R,$),R=r.sub(W,$),$=r.add(W,$),N=r.mul(R,$),W=r.add(B,B),W=r.add(W,B),X=r.mul(F,X),C=r.mul(z,C),W=r.add(W,X),X=r.sub(B,X),X=r.mul(F,X),C=r.add(C,X),B=r.mul(W,C),N=r.add(N,B),B=r.mul(b,C),R=r.mul(D,R),R=r.sub(R,B),B=r.mul(D,W),$=r.mul(b,$),$=r.add($,B),new l(R,N,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let S=r.invertBatch(y.map(v=>v.pz));return y.map((v,E)=>v.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===xd)return y;if(i(m),m===Fo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:v,k1:E,k2neg:_,k2:I}=S.splitScalar(m),R=y,N=y,$=this;for(;E>xd||I>xd;)E&Fo&&(R=R.add($)),I&Fo&&(N=N.add($)),$=$.double(),E>>=Fo,I>>=Fo;return v&&(R=R.negate()),_&&(N=N.negate()),N=new l(r.mul(N.px,S.beta),N.py,N.pz),R.add(N)}multiply(m){i(m);let y=m,S,v,{endo:E}=e;if(E){let{k1neg:_,k1:I,k2neg:R,k2:N}=E.splitScalar(y),{p:$,f:F}=this.wNAF(I),{p:z,f:B}=this.wNAF(N);$=h.constTimeNegate(_,$),z=h.constTimeNegate(R,z),z=new l(r.mul(z.px,E.beta),z.py,z.pz),S=$.add(z),v=F.add(B)}else{let{p:_,f:I}=this.wNAF(y);S=_,v=I}return l.normalizeZ([S,v])[0]}multiplyAndAddUnsafe(m,y,S){let v=l.BASE,E=(I,R)=>R===xd||R===Fo||!I.equals(v)?I.multiplyUnsafe(R):I.multiply(R),_=E(this,y).add(E(m,S));return _.is0()?void 0:_}toAffine(m){let{px:y,py:S,pz:v}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(v));let _=r.mul(y,m),I=r.mul(S,m),R=r.mul(v,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(R,r.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Fo)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Fo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return If(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=vL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function Xse(t){let e=HI(t);return Cf(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function eie(t){let e=Xse(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o(C){return xd<C&&C<r.ORDER}function i(C){return Kr(C,n)}function c(C){return bI(C,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=Qse({...e,toBytes(C,b,x){let P=b.toAffine(),k=r.toBytes(P.x),A=Af;return x?A(Uint8Array.from([b.hasEvenY()?2:3]),k):A(Uint8Array.from([4]),k,r.toBytes(P.y))},fromBytes(C){let b=C.length,x=C[0],P=C.subarray(1);if(b===s&&(x===2||x===3)){let k=kf(P);if(!o(k))throw new Error("Point is not on curve");let A=l(k),O=r.sqrt(A),q=(O&Fo)===Fo;return(x&1)===1!==q&&(O=r.neg(O)),{x:k,y:O}}else if(b===a&&x===4){let k=r.fromBytes(P.subarray(0,r.BYTES)),A=r.fromBytes(P.subarray(r.BYTES,2*r.BYTES));return{x:k,y:A}}else throw new Error(`Point of length ${b} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=C=>If(Ec(C,e.nByteLength));function p(C){let b=n>>Fo;return C>b}function m(C){return p(C)?i(-C):C}let y=(C,b,x)=>kf(C.slice(b,x));class S{constructor(b,x,P){this.r=b,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(b){let x=e.nByteLength;return b=Cn("compactSignature",b,x*2),new S(y(b,0,x),y(b,x,2*x))}static fromDER(b){let{r:x,s:P}=Sf.toSig(Cn("DER",b));return new S(x,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(b){return new S(this.r,this.s,b)}recoverPublicKey(b){let{r:x,s:P,recovery:k}=this,A=N(Cn("msgHash",b));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let O=k===2||k===3?x+e.n:x;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=k&1?"03":"02",G=u.fromHex(q+h(O)),V=c(O),H=i(-A*V),Y=i(P*V),K=u.BASE.multiplyAndAddUnsafe(G,H,Y);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Fh(this.toDERHex())}toDERHex(){return Sf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Fh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let v={isValidPrivateKey(C){try{return d(C),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let C=wL(e.n);return Vse(e.randomBytes(C),e.n)},precompute(C=8,b=u.BASE){return b._setWindowSize(C),b.multiply(BigInt(3)),b}};function E(C,b=!0){return u.fromPrivateKey(C).toRawBytes(b)}function _(C){let b=Sc(C),x=typeof C=="string",P=(b||x)&&C.length;return b?P===s||P===a:x?P===2*s||P===2*a:C instanceof u}function I(C,b,x=!0){if(_(C))throw new Error("first arg must be private key");if(!_(b))throw new Error("second arg must be public key");return u.fromHex(b).multiply(d(C)).toRawBytes(x)}let R=e.bits2int||function(C){let b=kf(C),x=C.length*8-e.nBitLength;return x>0?b>>BigInt(x):b},N=e.bits2int_modN||function(C){return i(R(C))},$=FI(e.nBitLength);function F(C){if(typeof C!="bigint")throw new Error("bigint expected");if(!(xd<=C&&C<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ec(C,e.nByteLength)}function z(C,b,x=B){if(["recovered","canonical"].some(se=>se in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:k}=e,{lowS:A,prehash:O,extraEntropy:q}=x;A==null&&(A=!0),C=Cn("msgHash",C),O&&(C=Cn("prehashed msgHash",P(C)));let G=N(C),V=d(b),H=[F(V),F(G)];if(q!=null){let se=q===!0?k(r.BYTES):q;H.push(Cn("extraEntropy",se))}let Y=Af(...H),K=G;function Q(se){let re=R(se);if(!f(re))return;let Z=c(re),de=u.BASE.multiply(re).toAffine(),le=i(de.x);if(le===xd)return;let pe=i(Z*i(K+le*V));if(pe===xd)return;let ve=(de.x===le?0:2)|Number(de.y&Fo),ce=pe;return A&&p(pe)&&(ce=m(pe),ve^=1),new S(le,ce,ve)}return{seed:Y,k2sig:Q}}let B={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function X(C,b,x=B){let{seed:P,k2sig:k}=z(C,b,x),A=e;return oL(A.hash.outputLen,A.nByteLength,A.hmac)(P,k)}u.BASE._setWindowSize(8);function D(C,b,x,P=W){let k=C;if(b=Cn("msgHash",b),x=Cn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:O}=P,q,G;try{if(typeof k=="string"||Sc(k))try{q=S.fromDER(k)}catch(Z){if(!(Z instanceof Sf.Err))throw Z;q=S.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Z,s:de}=k;q=new S(Z,de)}else throw new Error("PARSE");G=u.fromHex(x)}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;O&&(b=e.hash(b));let{r:V,s:H}=q,Y=N(b),K=c(H),Q=i(Y*K),se=i(V*K),re=u.BASE.multiplyAndAddUnsafe(G,Q,se)?.toAffine();return re?i(re.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:I,sign:X,verify:D,ProjectivePoint:u,Signature:S,utils:v}}var bL=class extends lL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ase(t);let r=GI(e);if(this.iHash=t.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,s=new Uint8Array(n);s.set(r.length>n?t.create().update(r).digest():r);for(let a=0;a<s.length;a++)s[a]^=54;this.iHash.update(s),this.oHash=t.create();for(let a=0;a<s.length;a++)s[a]^=106;this.oHash.update(s),s.fill(0)}update(t){return F1(this),this.iHash.update(t),this}digestInto(t){F1(this),aL(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:r,finished:n,destroyed:s,blockLen:a,outputLen:o}=this;return t=t,t.finished=n,t.destroyed=s,t.blockLen=a,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},PL=(t,e,r)=>new bL(t,e).update(r).digest();PL.create=(t,e)=>new bL(t,e);function tie(t){return{hash:t,hmac:(e,...r)=>PL(t,e,uL(...r)),randomBytes:WI}}function xL(t,e){let r=n=>eie({...t,...tie(n)});return Object.freeze({...r(e),create:r})}var SL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ON=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),rie=BigInt(1),PI=BigInt(2),BN=(t,e)=>(t+e/PI)/e;function nie(t){let e=SL,r=BigInt(3),n=BigInt(6),s=BigInt(11),a=BigInt(22),o=BigInt(23),i=BigInt(44),c=BigInt(88),u=t*t*t%e,d=u*u*t%e,l=un(d,r,e)*d%e,f=un(l,r,e)*d%e,h=un(f,PI,e)*u%e,p=un(h,s,e)*h%e,m=un(p,a,e)*p%e,y=un(m,i,e)*m%e,S=un(y,c,e)*y%e,v=un(S,i,e)*m%e,E=un(v,r,e)*d%e,_=un(E,o,e)*p%e,I=un(_,n,e)*u%e,R=un(I,PI,e);if(!xI.eql(xI.sqr(R),t))throw new Error("Cannot find square root");return R}var xI=VI(SL,void 0,void 0,{sqrt:nie}),po=xL({a:BigInt(0),b:BigInt(7),Fp:xI,n:ON,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=ON,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-rie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=BN(a*t,e),c=BN(-n*t,e),u=Kr(t-i*r-c*s,e),d=Kr(-i*n-c*a,e),l=u>o,f=d>o;if(l&&(u=e-u),f&&(d=e-d),u>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:f,k2:d}}}},hL),s$e=BigInt(0),i$e=po.ProjectivePoint;function sie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function EL(t,...e){if(!sie(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function NN(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function iie(t,e){EL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var S1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,uI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),yc=(t,e)=>t<<32-e|t>>>e,o$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function oie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function kL(t){return typeof t=="string"&&(t=oie(t)),EL(t),t}var aie=class{clone(){return this._cloneInto()}},a$e={}.toString;function cie(t){let e=n=>t().update(kL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function die(t=32){if(S1&&typeof S1.getRandomValues=="function")return S1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function uie(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var lie=(t,e,r)=>t&e^~t&r,fie=(t,e,r)=>t&e^t&r^e&r,pie=class extends aie{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=uI(this.buffer)}update(t){NN(this);let{view:e,buffer:r,blockLen:n}=this;t=kL(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=uI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){NN(this),iie(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let d=a;d<n;d++)e[d]=0;uie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=uI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},hie=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]),ju=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$u=new Uint32Array(64),mie=class extends pie{constructor(){super(64,32,8,!1),this.A=ju[0]|0,this.B=ju[1]|0,this.C=ju[2]|0,this.D=ju[3]|0,this.E=ju[4]|0,this.F=ju[5]|0,this.G=ju[6]|0,this.H=ju[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)$u[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=$u[d-15],f=$u[d-2],h=yc(l,7)^yc(l,18)^l>>>3,p=yc(f,17)^yc(f,19)^f>>>10;$u[d]=p+$u[d-7]+h+$u[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=yc(o,6)^yc(o,11)^yc(o,25),f=u+l+lie(o,i,c)+hie[d]+$u[d]|0,h=(yc(r,2)^yc(r,13)^yc(r,22))+fie(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){$u.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},bw=cie(()=>new mie);function yie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort(),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var gie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},_L=class{static digest(t){return gie(this,arguments,void 0,function*({data:e}){return bw(e)})}},wie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},UN="urn:jwk:";function pr(t){return wie(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);rL(n);let s=yie(n),a=Qe.string(s).toUint8Array(),o=yield _L.digest({data:a});return Qe.uint8Array(o).toBase64Url()})}function _f(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function JI(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function kd(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function ZI(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function vie(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var Rs=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},bie=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},$s=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=po.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return po.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){let n=yield wc.privateKeyToBytes({privateKey:r}),s=yield wc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return po.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return po.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=po.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=bie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(this,arguments,void 0,function*({publicKey:r}){if(!(JI(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Rs(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield wc.privateKeyToBytes({privateKey:r}),a=yield wc.publicKeyToBytes({publicKey:n});return po.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Rs(this,arguments,void 0,function*({data:r,key:n}){let s=yield wc.privateKeyToBytes({privateKey:n}),a=bw(r);return po.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return po.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{po.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Rs(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield wc.publicKeyToBytes({publicKey:r}),o=bw(s);return po.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=po.getPublicKey(r));let n=po.ProjectivePoint.fromHex(r),s=Ec(n.x,32),a=Ec(n.y,32);return{x:s,y:a}})}},TL=VI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Pie=TL.create(BigInt("-3")),xie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Sie=xL({a:Pie,b:xie,Fp:TL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hL),Uo=Sie,Ds=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Eie=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},ei=class vc{static adjustSignatureToLowS(e){return Ds(this,arguments,void 0,function*({signature:r}){let n=Uo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ds(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield vc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield vc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static compressPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){return Uo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ds(this,arguments,void 0,function*({key:r}){let n=yield vc.privateKeyToBytes({privateKey:r}),s=yield vc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertDerToCompactSignature(e){return Ds(this,arguments,void 0,function*({derSignature:r}){return Uo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){return Uo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ds(this,void 0,void 0,function*(){let e=Uo.utils.randomPrivateKey(),r=yield vc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Ds(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=Eie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Ds(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ds(this,arguments,void 0,function*({publicKey:r}){if(!(JI(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Ds(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield vc.privateKeyToBytes({privateKey:r}),a=yield vc.publicKeyToBytes({publicKey:n});return Uo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Ds(this,arguments,void 0,function*({data:r,key:n}){let s=yield vc.privateKeyToBytes({privateKey:n}),a=bw(r);return Uo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Ds(this,arguments,void 0,function*({privateKeyBytes:r}){return Uo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){try{Uo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ds(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield vc.publicKeyToBytes({publicKey:r}),o=bw(s);return Uo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Ds(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Uo.getPublicKey(r));let n=Uo.ProjectivePoint.fromHex(r),s=Ec(n.x,32),a=Ec(n.y,32);return{x:s,y:a}})}},gd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},LN=class extends rP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ei.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ei.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield $s.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ei.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield $s.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield ei.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield $s.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ei.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield $s.sign({key:e,data:r});case"P-256":return yield ei.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return gd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!JI(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield $s.verify({key:e,signature:r,data:n});case"P-256":return yield ei.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return gd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield $s.privateKeyToBytes({privateKey:e});case"P-256":return yield ei.privateKeyToBytes({privateKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield $s.publicKeyToBytes({publicKey:e});case"P-256":return yield ei.publicKeyToBytes({publicKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m1=BigInt(4294967295),SI=BigInt(32);function IL(t,e=!1){return e?{h:Number(t&m1),l:Number(t>>SI&m1)}:{h:Number(t>>SI&m1)|0,l:Number(t&m1)|0}}function kie(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:a,l:o}=IL(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var _ie=(t,e)=>BigInt(t>>>0)<<SI|BigInt(e>>>0),Tie=(t,e,r)=>t>>>r,Iie=(t,e,r)=>t<<32-r|e>>>r,Aie=(t,e,r)=>t>>>r|e<<32-r,Rie=(t,e,r)=>t<<32-r|e>>>r,Die=(t,e,r)=>t<<64-r|e>>>r-32,Cie=(t,e,r)=>t>>>r-32|e<<64-r,jie=(t,e)=>e,$ie=(t,e)=>t,Mie=(t,e,r)=>t<<r|e>>>32-r,Oie=(t,e,r)=>e<<r|t>>>32-r,Bie=(t,e,r)=>e<<r-32|t>>>64-r,Nie=(t,e,r)=>t<<r-32|e>>>64-r;function Uie(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var Lie=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Kie=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,zie=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),qie=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,Fie=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),Gie=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,Wie={fromBig:IL,split:kie,toBig:_ie,shrSH:Tie,shrSL:Iie,rotrSH:Aie,rotrSL:Rie,rotrBH:Die,rotrBL:Cie,rotr32H:jie,rotr32L:$ie,rotlSH:Mie,rotlSL:Oie,rotlBH:Bie,rotlBL:Nie,add:Uie,add3L:Lie,add3H:Kie,add4L:zie,add4H:qie,add5H:Gie,add5L:Fie},Rt=Wie,[Vie,Hie]=Rt.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(t=>BigInt(t))),Mu=new Uint32Array(80),Ou=new Uint32Array(80),Jie=class extends pL{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:t,Al:e,Bh:r,Bl:n,Ch:s,Cl:a,Dh:o,Dl:i,Eh:c,El:u,Fh:d,Fl:l,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m]}set(t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=i|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let v=0;v<16;v++,e+=4)Mu[v]=t.getUint32(e),Ou[v]=t.getUint32(e+=4);for(let v=16;v<80;v++){let E=Mu[v-15]|0,_=Ou[v-15]|0,I=Rt.rotrSH(E,_,1)^Rt.rotrSH(E,_,8)^Rt.shrSH(E,_,7),R=Rt.rotrSL(E,_,1)^Rt.rotrSL(E,_,8)^Rt.shrSL(E,_,7),N=Mu[v-2]|0,$=Ou[v-2]|0,F=Rt.rotrSH(N,$,19)^Rt.rotrBH(N,$,61)^Rt.shrSH(N,$,6),z=Rt.rotrSL(N,$,19)^Rt.rotrBL(N,$,61)^Rt.shrSL(N,$,6),B=Rt.add4L(R,z,Ou[v-7],Ou[v-16]),W=Rt.add4H(B,I,F,Mu[v-7],Mu[v-16]);Mu[v]=W|0,Ou[v]=B|0}let{Ah:r,Al:n,Bh:s,Bl:a,Ch:o,Cl:i,Dh:c,Dl:u,Eh:d,El:l,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:S}=this;for(let v=0;v<80;v++){let E=Rt.rotrSH(d,l,14)^Rt.rotrSH(d,l,18)^Rt.rotrBH(d,l,41),_=Rt.rotrSL(d,l,14)^Rt.rotrSL(d,l,18)^Rt.rotrBL(d,l,41),I=d&f^~d&p,R=l&h^~l&m,N=Rt.add5L(S,_,R,Hie[v],Ou[v]),$=Rt.add5H(N,y,E,I,Vie[v],Mu[v]),F=N|0,z=Rt.rotrSH(r,n,28)^Rt.rotrBH(r,n,34)^Rt.rotrBH(r,n,39),B=Rt.rotrSL(r,n,28)^Rt.rotrBL(r,n,34)^Rt.rotrBL(r,n,39),W=r&s^r&o^s&o,X=n&a^n&i^a&i;y=p|0,S=m|0,p=f|0,m=h|0,f=d|0,h=l|0,{h:d,l}=Rt.add(c|0,u|0,$|0,F|0),c=o|0,u=i|0,o=s|0,i=a|0,s=r|0,a=n|0;let D=Rt.add3L(F,B,X);r=Rt.add3H(D,$,z,W),n=D|0}({h:r,l:n}=Rt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Rt.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Rt.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Rt.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Rt.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Rt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Rt.add(this.Hh|0,this.Hl|0,y|0,S|0),this.set(r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S)}roundClean(){Mu.fill(0),Ou.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)}},AL=fL(()=>new Jie),Ta=BigInt(0),lo=BigInt(1),y1=BigInt(2),Zie=BigInt(8),Yie={zip215:!0};function Qie(t){let e=HI(t);return Cf(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function YI(t){let e=Qie(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=y1<<BigInt(i*8)-lo,d=r.create,l=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:r.sqrt(x*r.inv(P))}}catch{return{isValid:!1,value:Ta}}}),f=e.adjustScalarBytes||(x=>x),h=e.domain||((x,P,k)=>{if(P.length||k)throw new Error("Contexts/pre-hash are not supported");return x}),p=x=>typeof x=="bigint"&&Ta<x,m=(x,P)=>p(x)&&p(P)&&x<P,y=x=>x===Ta||m(x,u);function S(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function v(x){return x===Ta?x:S(x,n)}let E=new Map;function _(x){if(!(x instanceof I))throw new Error("ExtendedPoint expected")}class I{constructor(P,k,A,O){if(this.ex=P,this.ey=k,this.ez=A,this.et=O,!y(P))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(A))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof I)throw new Error("extended point not allowed");let{x:k,y:A}=P||{};if(!y(k)||!y(A))throw new Error("invalid affine point");return new I(k,A,lo,d(k*A))}static normalizeZ(P){let k=r.invertBatch(P.map(A=>A.ez));return P.map((A,O)=>A.toAffine(k[O])).map(I.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:O,ez:q,et:G}=this,V=d(A*A),H=d(O*O),Y=d(q*q),K=d(Y*Y),Q=d(V*P),se=d(Y*d(Q+H)),re=d(K+d(k*d(V*H)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Z=d(A*O),de=d(q*G);if(Z!==de)throw new Error("bad point: equation left != right (2)")}equals(P){_(P);let{ex:k,ey:A,ez:O}=this,{ex:q,ey:G,ez:V}=P,H=d(k*V),Y=d(q*O),K=d(A*V),Q=d(G*O);return H===Y&&K===Q}is0(){return this.equals(I.ZERO)}negate(){return new I(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:k,ey:A,ez:O}=this,q=d(k*k),G=d(A*A),V=d(y1*d(O*O)),H=d(P*q),Y=k+A,K=d(d(Y*Y)-q-G),Q=H+G,se=Q-V,re=H-G,Z=d(K*se),de=d(Q*re),le=d(K*re),pe=d(se*Q);return new I(Z,de,pe,le)}add(P){_(P);let{a:k,d:A}=e,{ex:O,ey:q,ez:G,et:V}=this,{ex:H,ey:Y,ez:K,et:Q}=P;if(k===BigInt(-1)){let Et=d((q-O)*(Y+H)),Se=d((q+O)*(Y-H)),et=d(Se-Et);if(et===Ta)return this.double();let wt=d(G*y1*Q),St=d(V*y1*K),Mt=St+wt,T=Se+Et,M=St-wt,L=d(Mt*et),te=d(T*M),ae=d(Mt*M),he=d(et*T);return new I(L,te,he,ae)}let se=d(O*H),re=d(q*Y),Z=d(V*A*Q),de=d(G*K),le=d((O+q)*(H+Y)-se-re),pe=de-Z,ve=de+Z,ce=d(re-k*se),ge=d(le*pe),Me=d(ve*ce),Le=d(le*ce),qe=d(pe*ve);return new I(ge,Me,qe,Le)}subtract(P){return this.add(P.negate())}wNAF(P){return $.wNAFCached(this,E,P,I.normalizeZ)}multiply(P){let{p:k,f:A}=this.wNAF(S(P,n));return I.normalizeZ([k,A])[0]}multiplyUnsafe(P){let k=v(P);return k===Ta?N:this.equals(N)||k===lo?this:this.equals(R)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(P){let{ex:k,ey:A,ez:O}=this,q=this.is0();P==null&&(P=q?Zie:r.inv(O));let G=d(k*P),V=d(A*P),H=d(O*P);if(q)return{x:Ta,y:lo};if(H!==lo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:P}=e;return P===lo?this:this.multiplyUnsafe(P)}static fromHex(P,k=!1){let{d:A,a:O}=e,q=r.BYTES;P=Cn("pointHex",P,q);let G=P.slice(),V=P[q-1];G[q-1]=V&-129;let H=Gu(G);H===Ta||(k?S(H,u):S(H,r.ORDER));let Y=d(H*H),K=d(Y-lo),Q=d(A*Y-O),{isValid:se,value:re}=l(K,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Z=(re&lo)===lo,de=(V&128)!==0;if(!k&&re===Ta&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Z&&(re=d(-re)),I.fromAffine({x:re,y:H})}static fromPrivateKey(P){return B(P).point}toRawBytes(){let{x:P,y:k}=this.toAffine(),A=Gh(k,r.BYTES);return A[A.length-1]|=P&lo?128:0,A}toHex(){return If(this.toRawBytes())}}I.BASE=new I(e.Gx,e.Gy,lo,d(e.Gx*e.Gy)),I.ZERO=new I(Ta,lo,lo,Ta);let{BASE:R,ZERO:N}=I,$=vL(I,i*8);function F(x){return Kr(x,n)}function z(x){return F(Gu(x))}function B(x){let P=i;x=Cn("private key",x,P);let k=Cn("hashed private key",a(x),2*P),A=f(k.slice(0,P)),O=k.slice(P,2*P),q=z(A),G=R.multiply(q),V=G.toRawBytes();return{head:A,prefix:O,scalar:q,point:G,pointBytes:V}}function W(x){return B(x).pointBytes}function X(x=new Uint8Array,...P){let k=Af(...P);return z(a(h(k,Cn("context",x),!!s)))}function D(x,P,k={}){x=Cn("message",x),s&&(x=s(x));let{prefix:A,scalar:O,pointBytes:q}=B(P),G=X(k.context,A,x),V=R.multiply(G).toRawBytes(),H=X(k.context,V,q,x),Y=F(G+H*O);v(Y);let K=Af(V,Gh(Y,r.BYTES));return Cn("result",K,i*2)}let C=Yie;function b(x,P,k,A=C){let{context:O,zip215:q}=A,G=r.BYTES;x=Cn("signature",x,2*G),P=Cn("message",P),s&&(P=s(P));let V=Gu(x.slice(G,2*G)),H,Y,K;try{H=I.fromHex(k,q),Y=I.fromHex(x.slice(0,G),q),K=R.multiplyUnsafe(V)}catch{return!1}if(!q&&H.isSmallOrder())return!1;let Q=X(O,Y.toRawBytes(),H.toRawBytes(),P);return Y.add(H.multiplyUnsafe(Q)).subtract(K).clearCofactor().equals(I.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:D,verify:b,ExtendedPoint:I,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(r.BYTES),precompute(x=8,P=I.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}var Zg=BigInt(0),lI=BigInt(1);function Xie(t){return Cf(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function eoe(t){let e=Xie(t),{P:r}=e,n=E=>Kr(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>mL(E,r-BigInt(2),r));function u(E,_,I){let R=n(E*(_-I));return _=n(_-R),I=n(I+R),[_,I]}function d(E){if(typeof E=="bigint"&&Zg<=E&&E<r)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(e.a-BigInt(2))/BigInt(4);function f(E,_){let I=d(E),R=d(_),N=I,$=lI,F=Zg,z=I,B=lI,W=Zg,X;for(let C=BigInt(s-1);C>=Zg;C--){let b=R>>C&lI;W^=b,X=u(W,$,z),$=X[0],z=X[1],X=u(W,F,B),F=X[0],B=X[1],W=b;let x=$+F,P=n(x*x),k=$-F,A=n(k*k),O=P-A,q=z+B,G=z-B,V=n(G*x),H=n(q*k),Y=V+H,K=V-H;z=n(Y*Y),B=n(N*n(K*K)),$=n(P*A),F=n(O*(P+n(l*O)))}X=u(W,$,z),$=X[0],z=X[1],X=u(W,F,B),F=X[0],B=X[1];let D=c(F);return n($*D)}function h(E){return Gh(n(E),a)}function p(E){let _=Cn("u coordinate",E,a);return o===32&&(_[31]&=127),Gu(_)}function m(E){let _=Cn("scalar",E),I=_.length;if(I!==a&&I!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${I}`);return Gu(i(_))}function y(E,_){let I=p(_),R=m(E),N=f(I,R);if(N===Zg)throw new Error("Invalid private or public key received");return h(N)}let S=h(e.Gu);function v(E){return y(E,S)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>v(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Pw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),KN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c$e=BigInt(0),toe=BigInt(1),EI=BigInt(2),roe=BigInt(5),zN=BigInt(10),noe=BigInt(20),soe=BigInt(40),qN=BigInt(80);function RL(t){let e=Pw,r=t*t%e*t%e,n=un(r,EI,e)*r%e,s=un(n,toe,e)*t%e,a=un(s,roe,e)*s%e,o=un(a,zN,e)*a%e,i=un(o,noe,e)*o%e,c=un(i,soe,e)*i%e,u=un(c,qN,e)*c%e,d=un(u,qN,e)*c%e,l=un(d,zN,e)*a%e;return{pow_p_5_8:un(l,EI,e)*t%e,b2:r}}function DL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ioe(t,e){let r=Pw,n=Kr(e*e*e,r),s=Kr(n*n*e,r),a=RL(t*s).pow_p_5_8,o=Kr(t*n*a,r),i=Kr(e*o*o,r),c=o,u=Kr(o*KN,r),d=i===t,l=i===Kr(-t,r),f=i===Kr(-t*KN,r);return d&&(o=c),(l||f)&&(o=u),Kse(o,r)&&(o=Kr(-o,r)),{isValid:d||l,value:o}}var Ho=VI(Pw,void 0,!0),xw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ho,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:AL,randomBytes:WI,adjustScalarBytes:DL,uvRatio:ioe},wf=YI(xw);function CL(t,e,r){if(e.length>255)throw new Error("Context is too big");return uL(dL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var d$e=YI({...xw,domain:CL}),u$e=YI({...xw,domain:CL,prehash:AL}),rw=eoe({P:Pw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Pw,{pow_p_5_8:r,b2:n}=RL(t);return Kr(un(r,BigInt(3),e)*n,e)},adjustScalarBytes:DL,randomBytes:WI});function ooe(t){let{y:e}=wf.ExtendedPoint.fromHex(t),r=BigInt(1);return Ho.toBytes(Ho.create((r+e)*Ho.inv(r-e)))}function aoe(t){let e=xw.hash(t.subarray(0,32));return xw.adjustScalarBytes(e).subarray(0,32)}var coe=(Ho.ORDER+BigInt(3))/BigInt(8),l$e=Ho.pow(EI,coe),f$e=Ho.sqrt(Ho.neg(Ho.ONE)),p$e=(Ho.ORDER-BigInt(5))/BigInt(8),h$e=BigInt(486662),m$e=Wse(Ho,Ho.neg(BigInt(486664))),y$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),g$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),w$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),v$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),b$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Lo=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},doe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Ms=class Ku{static bytesToPrivateKey(e){return Lo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=wf.getPublicKey(r),s={crv:"Ed25519",d:Qe.uint8Array(r).toBase64Url(),kty:"OKP",x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Lo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield pr({jwk:n}),n})}static computePublicKey(e){return Lo(this,arguments,void 0,function*({key:r}){let n=yield Ku.privateKeyToBytes({privateKey:r}),s=wf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Lo(this,arguments,void 0,function*({privateKey:r}){let n=yield Ku.privateKeyToBytes({privateKey:r}),s=aoe(n),a=rw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Qe.uint8Array(s).toBase64Url(),x:Qe.uint8Array(a).toBase64Url()};return o.kid=yield pr({jwk:o}),o})}static convertPublicKeyToX25519(e){return Lo(this,arguments,void 0,function*({publicKey:r}){let n=yield Ku.publicKeyToBytes({publicKey:r});if(!(yield Ku.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=ooe(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static generateKey(){return Lo(this,void 0,void 0,function*(){let e=wf.utils.randomPrivateKey(),r=yield Ku.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Lo(this,arguments,void 0,function*({key:r}){var n;if(!(kd(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=doe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Lo(this,arguments,void 0,function*({privateKey:r}){if(!kd(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Lo(this,arguments,void 0,function*({publicKey:r}){if(!ZI(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sign(e){return Lo(this,arguments,void 0,function*({key:r,data:n}){let s=yield Ku.privateKeyToBytes({privateKey:r});return wf.sign(n,s)})}static validatePublicKey(e){return Lo(this,arguments,void 0,function*({publicKeyBytes:r}){try{wf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Lo(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Ku.publicKeyToBytes({publicKey:r});return wf.verify(n,s,a)})}},wd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},uoe=class extends rP{bytesToPrivateKey(t){return wd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Ms.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return wd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Ms.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return wd(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Ms.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return wd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield Ms.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return wd(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Ms.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return wd(this,arguments,void 0,function*({key:e,data:r}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield Ms.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return wd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!ZI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield Ms.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return wd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield Ms.privateKeyToBytes({privateKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return wd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield Ms.publicKeyToBytes({publicKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},loe=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},foe=class extends rP{digest(t){return loe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield _L.digest({data:r})}})}},Bu=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},poe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},jh=class nw{static bytesToPrivateKey(e){return Bu(this,arguments,void 0,function*({privateKeyBytes:r}){let n=rw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Bu(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield pr({jwk:n}),n})}static computePublicKey(e){return Bu(this,arguments,void 0,function*({key:r}){let n=yield nw.privateKeyToBytes({privateKey:r}),s=rw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static generateKey(){return Bu(this,void 0,void 0,function*(){let e=rw.utils.randomPrivateKey(),r=yield nw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Bu(this,arguments,void 0,function*({key:r}){var n;if(!(kd(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=poe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Bu(this,arguments,void 0,function*({privateKey:r}){if(!kd(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Bu(this,arguments,void 0,function*({publicKey:r}){if(!ZI(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Bu(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield nw.privateKeyToBytes({privateKey:r}),a=yield nw.publicKeyToBytes({publicKey:n});return rw.getSharedSecret(s,a)})}},Yg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},hoe=class extends rP{bytesToPrivateKey(t){return Yg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return jh.bytesToPrivateKey({privateKeyBytes:r});default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Yg(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return jh.computePublicKey({key:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Yg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return jh.generateKey();default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Yg(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return jh.getPublicKey({key:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Yg(this,arguments,void 0,function*({privateKey:e}){return jh.privateKeyToBytes({privateKey:e})})}},vd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},fI={Ed25519:{implementation:uoe,names:["Ed25519"]},secp256k1:{implementation:LN,names:["ES256K","secp256k1"]},secp256r1:{implementation:LN,names:["ES256","secp256r1"]},"SHA-256":{implementation:foe,names:["SHA-256"]},X25519:{implementation:hoe,names:["X25519"]}},Ra=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new wse}digest(t){return vd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return vd(this,arguments,void 0,function*({algorithm:e}){let r=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(r?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${UN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return vd(this,arguments,void 0,function*({key:e}){let r=yield pr({jwk:e});return`${UN}${r}`})}getPublicKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){let r=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:r})})}importKey(t){return vd(this,arguments,void 0,function*({key:e}){var r;if(!vie(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(r=n.kid)!==null&&r!==void 0||(n.kid=yield pr({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return vd(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),s=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:s}).sign({data:r,key:n})})}verify(t){return vd(this,arguments,void 0,function*({key:e,signature:r,data:n}){let s=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:s}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=fI[t])===null||e===void 0?void 0:e.implementation;if(!r)throw new Error(`Algorithm not supported: ${t}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:t}){let e=t.alg,r=t.crv;for(let n in fI){let s=fI[n];if(e&&s.names.includes(e)||r&&s.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){let r=yield this._keyStore.get(e);if(!r)throw new Error(`Key not found: ${e}`);return r})}},moe=class kI{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return die(e)}static randomUuid(){return S1.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 r=Math.pow(10,e)-1,n;if(e<=6){let s=Math.pow(10,e);do{let a=kI.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%s}while(n>r)}else{let s=Math.pow(10,10);do{let a=kI.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%s}while(n>r)}return n.toString().padStart(e,"0")}},yoe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function goe(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(t)?"Array":t instanceof Uint8Array?"Uint8Array":t.constructor===Object?"Object":woe(t)||"Object"}function woe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(yoe.includes(e))return e}var Pe=class{constructor(t,e,r){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,e){return t===e||t.major===e.major&&t.name===e.name}};Pe.uint=new Pe(0,"uint",!0);Pe.negint=new Pe(1,"negint",!0);Pe.bytes=new Pe(2,"bytes",!0);Pe.string=new Pe(3,"string",!0);Pe.array=new Pe(4,"array",!1);Pe.map=new Pe(5,"map",!1);Pe.tag=new Pe(6,"tag",!1);Pe.float=new Pe(7,"float",!0);Pe.false=new Pe(7,"false",!0);Pe.true=new Pe(7,"true",!0);Pe.null=new Pe(7,"null",!0);Pe.undefined=new Pe(7,"undefined",!0);Pe.break=new Pe(7,"break",!0);var Je=class{constructor(t,e,r){this.type=t,this.value=e,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},Iw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",voe=new TextEncoder;function G1(t){return Iw&&globalThis.Buffer.isBuffer(t)}function jL(t){return t instanceof Uint8Array?G1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var boe=24,Poe=200,xoe=Iw?t=>t.length>=boe?globalThis.Buffer.from(t):FN(t):t=>t.length>=Poe?voe.encode(t):FN(t),bd=t=>Uint8Array.from(t),Soe=Iw?(t,e,r)=>G1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Eoe=Iw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),jL(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let s of t)n+s.length>r.length&&(s=s.subarray(0,r.length-n)),r.set(s,n),n+=s.length;return r},koe=Iw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function $L(t,e){if(G1(t)&&G1(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function FN(t){let e=[],r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=s&63|128):(s&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}return e}var _oe=256,ML=class{constructor(t=_oe){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let r=e.length-(this.maxCursor-this.cursor)-1;e.set(t,r)}else{if(e){let r=e.length-(this.maxCursor-this.cursor)-1;r<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,r),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=koe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=Soe(r,0,this.cursor)}else e=Eoe(this.chunks,this.cursor);return t&&this.reset(),e}},Toe=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let e=this.dest.subarray(0,this.cursor);return t&&this.reset(),e}},ln="CBOR decode error:",OL="CBOR encode error:",Aw=[];Aw[23]=1;Aw[24]=2;Aw[25]=3;Aw[26]=5;Aw[27]=9;function Zh(t,e,r){if(t.length-e<r)throw new Error(`${ln} not enough data for type`)}var Os=[24,256,65536,4294967296,BigInt("18446744073709551616")];function jf(t,e,r){Zh(t,e,1);let n=t[e];if(r.strict===!0&&n<Os[0])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Zh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Os[1])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function Mf(t,e,r){Zh(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Os[2])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function Of(t,e,r){Zh(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],s=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(s);if(r.strict===!0&&a<Os[3])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(r.allowBigInt===!0)return a;throw new Error(`${ln} integers outside of the safe integer range are not supported`)}function Ioe(t,e,r,n){return new Je(Pe.uint,jf(t,e+1,n),2)}function Aoe(t,e,r,n){return new Je(Pe.uint,$f(t,e+1,n),3)}function Roe(t,e,r,n){return new Je(Pe.uint,Mf(t,e+1,n),5)}function Doe(t,e,r,n){return new Je(Pe.uint,Of(t,e+1,n),9)}function Bf(t,e){return Zo(t,0,e.value)}function Zo(t,e,r){if(r<Os[0]){let n=Number(r);t.push([e|n])}else if(r<Os[1]){let n=Number(r);t.push([e|24,n])}else if(r<Os[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Os[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<Os[4]){let s=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=a&255,a=a>>8,s[7]=a&255,a=a>>8,s[6]=a&255,a=a>>8,s[5]=a&255,s[4]=o&255,o=o>>8,s[3]=o&255,o=o>>8,s[2]=o&255,o=o>>8,s[1]=o&255,t.push(s)}else throw new Error(`${ln} encountered BigInt larger than allowable range`)}}Bf.encodedSize=function(t){return Zo.encodedSize(t.value)};Zo.encodedSize=function(t){return t<Os[0]?1:t<Os[1]?2:t<Os[2]?3:t<Os[3]?5:9};Bf.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Coe(t,e,r,n){return new Je(Pe.negint,-1-jf(t,e+1,n),2)}function joe(t,e,r,n){return new Je(Pe.negint,-1-$f(t,e+1,n),3)}function $oe(t,e,r,n){return new Je(Pe.negint,-1-Mf(t,e+1,n),5)}var QI=BigInt(-1),BL=BigInt(1);function Moe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s!="bigint"){let a=-1-s;if(a>=Number.MIN_SAFE_INTEGER)return new Je(Pe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${ln} integers outside of the safe integer range are not supported`);return new Je(Pe.negint,QI-BigInt(s),9)}function XI(t,e){let r=e.value,n=typeof r=="bigint"?r*QI-BL:r*-1-1;Zo(t,e.type.majorEncoded,n)}XI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*QI-BL:e*-1-1;return r<Os[0]?1:r<Os[1]?2:r<Os[2]?3:r<Os[3]?5:9};XI.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Rw(t,e,r,n){Zh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Je(Pe.bytes,s,r+n)}function Ooe(t,e,r,n){return Rw(t,e,1,r)}function Boe(t,e,r,n){return Rw(t,e,2,jf(t,e+1,n))}function Noe(t,e,r,n){return Rw(t,e,3,$f(t,e+1,n))}function Uoe(t,e,r,n){return Rw(t,e,5,Mf(t,e+1,n))}function Loe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer bytes lengths not supported`);return Rw(t,e,9,s)}function W1(t){return t.encodedBytes===void 0&&(t.encodedBytes=Pe.equals(t.type,Pe.string)?xoe(t.value):t.value),t.encodedBytes}function sP(t,e){let r=W1(e);Zo(t,e.type.majorEncoded,r.length),t.push(r)}sP.encodedSize=function(t){let e=W1(t);return Zo.encodedSize(e.length)+e.length};sP.compareTokens=function(t,e){return Koe(W1(t),W1(e))};function Koe(t,e){return t.length<e.length?-1:t.length>e.length?1:$L(t,e)}var GN=new TextDecoder,zoe=32;function qoe(t,e,r){if(r-e<zoe){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return GN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return GN.decode(t.subarray(e,r))}function Dw(t,e,r,n,s){let a=r+n;Zh(t,e,a);let o=new Je(Pe.string,qoe(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function Foe(t,e,r,n){return Dw(t,e,1,r,n)}function Goe(t,e,r,n){return Dw(t,e,2,jf(t,e+1,n),n)}function Woe(t,e,r,n){return Dw(t,e,3,$f(t,e+1,n),n)}function Voe(t,e,r,n){return Dw(t,e,5,Mf(t,e+1,n),n)}function Hoe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer string lengths not supported`);return Dw(t,e,9,s,n)}var Joe=sP;function Yh(t,e,r,n){return new Je(Pe.array,n,r)}function Zoe(t,e,r,n){return Yh(t,e,1,r)}function Yoe(t,e,r,n){return Yh(t,e,2,jf(t,e+1,n))}function Qoe(t,e,r,n){return Yh(t,e,3,$f(t,e+1,n))}function Xoe(t,e,r,n){return Yh(t,e,5,Mf(t,e+1,n))}function eae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer array lengths not supported`);return Yh(t,e,9,s)}function tae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function eA(t,e){Zo(t,Pe.array.majorEncoded,e.value)}eA.compareTokens=Bf.compareTokens;eA.encodedSize=function(t){return Zo.encodedSize(t.value)};function Qh(t,e,r,n){return new Je(Pe.map,n,r)}function rae(t,e,r,n){return Qh(t,e,1,r)}function nae(t,e,r,n){return Qh(t,e,2,jf(t,e+1,n))}function sae(t,e,r,n){return Qh(t,e,3,$f(t,e+1,n))}function iae(t,e,r,n){return Qh(t,e,5,Mf(t,e+1,n))}function oae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer map lengths not supported`);return Qh(t,e,9,s)}function aae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return Qh(t,e,1,1/0)}function tA(t,e){Zo(t,Pe.map.majorEncoded,e.value)}tA.compareTokens=Bf.compareTokens;tA.encodedSize=function(t){return Zo.encodedSize(t.value)};function cae(t,e,r,n){return new Je(Pe.tag,r,1)}function dae(t,e,r,n){return new Je(Pe.tag,jf(t,e+1,n),2)}function uae(t,e,r,n){return new Je(Pe.tag,$f(t,e+1,n),3)}function lae(t,e,r,n){return new Je(Pe.tag,Mf(t,e+1,n),5)}function fae(t,e,r,n){return new Je(Pe.tag,Of(t,e+1,n),9)}function rA(t,e){Zo(t,Pe.tag.majorEncoded,e.value)}rA.compareTokens=Bf.compareTokens;rA.encodedSize=function(t){return Zo.encodedSize(t.value)};var NL=20,UL=21,LL=22,KL=23;function pae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${ln} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Je(Pe.null,null,1):new Je(Pe.undefined,void 0,1)}function hae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return new Je(Pe.break,void 0,1)}function nA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${ln} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${ln} Infinity values are not supported`)}return new Je(Pe.float,t,e)}function mae(t,e,r,n){return nA(iA(t,e+1),3,n)}function yae(t,e,r,n){return nA(oA(t,e+1),5,n)}function gae(t,e,r,n){return nA(GL(t,e+1),9,n)}function sA(t,e,r){let n=e.value;if(n===!1)t.push([Pe.float.majorEncoded|NL]);else if(n===!0)t.push([Pe.float.majorEncoded|UL]);else if(n===null)t.push([Pe.float.majorEncoded|LL]);else if(n===void 0)t.push([Pe.float.majorEncoded|KL]);else{let s,a=!1;(!r||r.float64!==!0)&&(qL(n),s=iA(Ia,1),n===s||Number.isNaN(n)?(Ia[0]=249,t.push(Ia.slice(0,3)),a=!0):(FL(n),s=oA(Ia,1),n===s&&(Ia[0]=250,t.push(Ia.slice(0,5)),a=!0))),a||(wae(n),s=GL(Ia,1),Ia[0]=251,t.push(Ia.slice(0,9)))}}sA.encodedSize=function(t,e){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!e||e.float64!==!0){qL(r);let n=iA(Ia,1);if(r===n||Number.isNaN(r))return 3;if(FL(r),n=oA(Ia,1),r===n)return 5}return 9};var zL=new ArrayBuffer(9),zo=new DataView(zL,1),Ia=new Uint8Array(zL,0);function qL(t){if(t===1/0)zo.setUint16(0,31744,!1);else if(t===-1/0)zo.setUint16(0,64512,!1);else if(Number.isNaN(t))zo.setUint16(0,32256,!1);else{zo.setFloat32(0,t);let e=zo.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)zo.setUint16(0,31744,!1);else if(r===0)zo.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?zo.setUint16(0,0):s<-14?zo.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):zo.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function iA(t,e){if(t.length-e<2)throw new Error(`${ln} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,s=r&1023,a;return n===0?a=s*2**-24:n!==31?a=(s+1024)*2**(n-25):a=s===0?1/0:NaN,r&32768?-a:a}function FL(t){zo.setFloat32(0,t,!1)}function oA(t,e){if(t.length-e<4)throw new Error(`${ln} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function wae(t){zo.setFloat64(0,t,!1)}function GL(t,e){if(t.length-e<8)throw new Error(`${ln} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}sA.compareTokens=Bf.compareTokens;function sr(t,e,r){throw new Error(`${ln} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function iP(t){return()=>{throw new Error(`${ln} ${t}`)}}var Ce=[];for(let t=0;t<=23;t++)Ce[t]=sr;Ce[24]=Ioe;Ce[25]=Aoe;Ce[26]=Roe;Ce[27]=Doe;Ce[28]=sr;Ce[29]=sr;Ce[30]=sr;Ce[31]=sr;for(let t=32;t<=55;t++)Ce[t]=sr;Ce[56]=Coe;Ce[57]=joe;Ce[58]=$oe;Ce[59]=Moe;Ce[60]=sr;Ce[61]=sr;Ce[62]=sr;Ce[63]=sr;for(let t=64;t<=87;t++)Ce[t]=Ooe;Ce[88]=Boe;Ce[89]=Noe;Ce[90]=Uoe;Ce[91]=Loe;Ce[92]=sr;Ce[93]=sr;Ce[94]=sr;Ce[95]=iP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)Ce[t]=Foe;Ce[120]=Goe;Ce[121]=Woe;Ce[122]=Voe;Ce[123]=Hoe;Ce[124]=sr;Ce[125]=sr;Ce[126]=sr;Ce[127]=iP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)Ce[t]=Zoe;Ce[152]=Yoe;Ce[153]=Qoe;Ce[154]=Xoe;Ce[155]=eae;Ce[156]=sr;Ce[157]=sr;Ce[158]=sr;Ce[159]=tae;for(let t=160;t<=183;t++)Ce[t]=rae;Ce[184]=nae;Ce[185]=sae;Ce[186]=iae;Ce[187]=oae;Ce[188]=sr;Ce[189]=sr;Ce[190]=sr;Ce[191]=aae;for(let t=192;t<=215;t++)Ce[t]=cae;Ce[216]=dae;Ce[217]=uae;Ce[218]=lae;Ce[219]=fae;Ce[220]=sr;Ce[221]=sr;Ce[222]=sr;Ce[223]=sr;for(let t=224;t<=243;t++)Ce[t]=iP("simple values are not supported");Ce[244]=sr;Ce[245]=sr;Ce[246]=sr;Ce[247]=pae;Ce[248]=iP("simple values are not supported");Ce[249]=mae;Ce[250]=yae;Ce[251]=gae;Ce[252]=sr;Ce[253]=sr;Ce[254]=sr;Ce[255]=hae;var Td=[];for(let t=0;t<24;t++)Td[t]=new Je(Pe.uint,t,1);for(let t=-1;t>=-24;t--)Td[31-t]=new Je(Pe.negint,t,1);Td[64]=new Je(Pe.bytes,new Uint8Array(0),1);Td[96]=new Je(Pe.string,"",1);Td[128]=new Je(Pe.array,0,1);Td[160]=new Je(Pe.map,0,1);Td[244]=new Je(Pe.false,!1,1);Td[245]=new Je(Pe.true,!0,1);Td[246]=new Je(Pe.null,null,1);function vae(t){switch(t.type){case Pe.false:return bd([244]);case Pe.true:return bd([245]);case Pe.null:return bd([246]);case Pe.bytes:return t.value.length?void 0:bd([64]);case Pe.string:return t.value===""?bd([96]):void 0;case Pe.array:return t.value===0?bd([128]):void 0;case Pe.map:return t.value===0?bd([160]):void 0;case Pe.uint:return t.value<24?bd([Number(t.value)]):void 0;case Pe.negint:if(t.value>=-24)return bd([31-Number(t.value)])}}var bae=Object.freeze({float64:!0,mapSorter:kae,quickEncodeToken:vae});function Pae(){let t=[];return t[Pe.uint.major]=Bf,t[Pe.negint.major]=XI,t[Pe.bytes.major]=sP,t[Pe.string.major]=Joe,t[Pe.array.major]=eA,t[Pe.map.major]=tA,t[Pe.tag.major]=rA,t[Pe.float.major]=sA,t}var xae=Pae(),Sae=new ML,WN=class WL{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${OL} object contains circular references`);return new WL(r,e)}},Nu={null:new Je(Pe.null,null),undefined:new Je(Pe.undefined,void 0),true:new Je(Pe.true,!0),false:new Je(Pe.false,!1),emptyArray:new Je(Pe.array,0),emptyMap:new Je(Pe.map,0)},Vu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Je(Pe.float,t):t>=0?new Je(Pe.uint,t):new Je(Pe.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Je(Pe.uint,t):new Je(Pe.negint,t)},Uint8Array(t,e,r,n){return new Je(Pe.bytes,t)},string(t,e,r,n){return new Je(Pe.string,t)},boolean(t,e,r,n){return t?Nu.true:Nu.false},null(t,e,r,n){return Nu.null},undefined(t,e,r,n){return Nu.undefined},ArrayBuffer(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Nu.emptyArray,new Je(Pe.break)]:Nu.emptyArray;n=WN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=E1(o,r,n);return r.addBreakTokens?[new Je(Pe.array,t.length),s,new Je(Pe.break)]:[new Je(Pe.array,t.length),s]},Object(t,e,r,n){let s=e!=="Object",a=s?t.keys():Object.keys(t),o=s?t.size:a.length,i;if(o){i=new Array(o),n=WN.createCheck(n,t);let c=!s&&r.ignoreUndefinedProperties,u=0;for(let d of a){let l=s?t.get(d):t[d];c&&l===void 0||(i[u++]=[E1(d,r,n),E1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(Eae(i,r),r.addBreakTokens?[new Je(Pe.map,i.length),i,new Je(Pe.break)]:[new Je(Pe.map,i.length),i]):r.addBreakTokens===!0?[Nu.emptyMap,new Je(Pe.break)]:Nu.emptyMap}};Vu.Map=Vu.Object;Vu.Buffer=Vu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Vu[`${t}Array`]=Vu.DataView;function E1(t,e={},r){let n=goe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Vu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Vu[n];if(!a)throw new Error(`${OL} unsupported type: ${n}`);return a(t,n,e,r)}function Eae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function kae(t,e){if(t[0]instanceof Je&&e[0]instanceof Je){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=VN(r.value)),n._keyBytes||(n._keyBytes=VN(n.value)),$L(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function VN(t){return _ae(t,xae,bae)}function VL(t,e,r,n){if(Array.isArray(e))for(let s of e)VL(t,s,r,n);else r[e.type.major](t,e,n)}var P$e=Pe.uint.majorEncoded,x$e=Pe.negint.majorEncoded,S$e=Pe.bytes.majorEncoded,E$e=Pe.string.majorEncoded,k$e=Pe.array.majorEncoded,_$e=Pe.float.majorEncoded|NL,T$e=Pe.float.majorEncoded|UL,I$e=Pe.float.majorEncoded|LL,A$e=Pe.float.majorEncoded|KL,R$e=BigInt(-1),D$e=BigInt(1);function _ae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new Toe(n):Sae,o=E1(t,r);if(!Array.isArray(o)&&r.quickEncodeToken){let i=r.quickEncodeToken(o);if(i)return s?(a.push(i),a.toBytes()):i;let c=e[o.type.major];if(c.encodedSize){let u=c.encodedSize(o,r);if(s||(a=new ML(u)),c(a,o,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return s?a.toBytes():jL(a.chunks[0])}}return a.reset(),VL(a,o,e,r),a.toBytes(!0)}var C$e=Symbol.for("DONE"),j$e=Symbol.for("BREAK"),HN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(HN||(HN={}));var ti;(function(t){t[t.P256=1]="P256",t[t.P384=2]="P384",t[t.P521=3]="P521",t[t.X25519=4]="X25519",t[t.X448=5]="X448",t[t.Ed25519=6]="Ed25519",t[t.Ed448=7]="Ed448",t[t.Secp256k1=8]="Secp256k1"})(ti||(ti={}));var Wo;(function(t){t[t.EdDSA=-8]="EdDSA",t[t.ES256=-7]="ES256",t[t.ES384=-35]="ES384",t[t.ES512=-36]="ES512",t[t.ES256K=-47]="ES256K"})(Wo||(Wo={}));var JN;(function(t){t[t.Kty=1]="Kty",t[t.Kid=2]="Kid",t[t.Alg=3]="Alg",t[t.KeyOps=4]="KeyOps",t[t.BaseIv=5]="BaseIv"})(JN||(JN={}));var ZN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(ZN||(ZN={}));var $$e={"P-256":ti.P256,"P-384":ti.P384,"P-521":ti.P521,X25519:ti.X25519,Ed25519:ti.Ed25519,Ed448:ti.Ed448,secp256k1:ti.Secp256k1},M$e={[ti.P256]:"P-256",[ti.P384]:"P-384",[ti.P521]:"P-521",[ti.X25519]:"X25519",[ti.Ed25519]:"Ed25519",[ti.Ed448]:"Ed448",[ti.Secp256k1]:"secp256k1"},O$e={EdDSA:Wo.EdDSA,ES256:Wo.ES256,ES384:Wo.ES384,ES512:Wo.ES512,ES256K:Wo.ES256K},B$e={[Wo.EdDSA]:"EdDSA",[Wo.ES256]:"ES256",[Wo.ES384]:"ES384",[Wo.ES512]:"ES512",[Wo.ES256K]:"ES256K"},YN;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(YN||(YN={}));var QN;(function(t){t[t.Iss=1]="Iss",t[t.Sub=2]="Sub",t[t.Aud=3]="Aud",t[t.Exp=4]="Exp",t[t.Nbf=5]="Nbf",t[t.Iat=6]="Iat",t[t.Cti=7]="Cti",t[t.Nonce=10]="Nonce",t[t.Ueid=256]="Ueid",t[t.Sueids=257]="Sueids",t[t.Oemid=258]="Oemid",t[t.Hwmodel=259]="Hwmodel",t[t.Hwversion=260]="Hwversion",t[t.Secboot=262]="Secboot",t[t.Dbgstat=263]="Dbgstat",t[t.Location=264]="Location",t[t.Profile=265]="Profile",t[t.Submods=266]="Submods",t[t.Measres=272]="Measres",t[t.Intuse=268]="Intuse"})(QN||(QN={}));var XN;(function(t){t[t.Enabled=0]="Enabled",t[t.Disabled=1]="Disabled",t[t.DisabledSinceBoot=2]="DisabledSinceBoot",t[t.DisabledPermanently=3]="DisabledPermanently",t[t.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(XN||(XN={}));var eU;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(eU||(eU={}));var Tae={};NI(Tae,{extractDidFragment:()=>ki,getServices:()=>Iae,getVerificationMethodByKey:()=>Aae,getVerificationMethodTypes:()=>HL,getVerificationMethods:()=>oP,getVerificationRelationshipsById:()=>JL,isDidService:()=>ZL,isDidVerificationMethod:()=>V1,isDwnDidService:()=>Rae,isPortableDid:()=>Dae,keyBytesToMultibaseId:()=>YL,multibaseIdToKeyBytes:()=>QL});function ki(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Iae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Aae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=oP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await pr({jwk:e})===await pr({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function oP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(V1)??[]),Object.keys(tP).forEach(r=>{e.push(...t[r]?.filter(V1)??[])}),e}function HL({didDocument:t}){let e=oP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function JL({didDocument:t,methodId:e}){let r=[];return Object.keys(tP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=ki(e);s.some(o=>{let i=ki(o)===a,c=V1(o)&&ki(o.id)===a;return i||c})&&r.push(n)}}),r}function ZL(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Rae(t){return!(!ZL(t)||t.type!=="DecentralizedWebNode")}function V1(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Dae(t){return!(!t||typeof t!="object"||t===null)&&"uri"in t&&"document"in t&&"metadata"in t&&(!("keyManager"in t)||t.keyManager===void 0)}function YL({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Jo.addPrefix({code:e,data:t,name:r}),s=Qe.uint8Array(n).toBase58Btc();return Qe.base58Btc(s).toMultibase()}function QL({multibaseKeyId:t}){try{let e=Qe.multibase(t).toBase58Btc(),r=Qe.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Jo.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new Ze("invalidDid",`Invalid multibase identifier: ${t}`)}}var kc=class XL{constructor({uri:e,document:r,metadata:n,keyManager:s}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=s}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 r=[];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 s=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:s});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(o=>ki(o.id)===(ki(e?.methodId)??ki(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),s=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:moe.getJoseSignatureAlgorithmFromPublicKey(s),keyId:r.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:i}){return await a.verify({data:o,key:s,signature:i})}}}static async import({portableDid:e,keyManager:r=new Ra}){let n=oP({didDocument:e.document});if(n.length===0)throw new Ze("invalidDidDocument","At least one verification method is required but 0 were given");for(let s of e.privateKeys??[]){let a=await r.getKeyUri({key:s});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.importKey({key:s})}for(let s of n){if(!s.publicKeyJwk)throw new Error(`Verification method '${s.id}' does not contain a public key in JWK format`);let a=await r.getKeyUri({key:s.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new XL({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Cw=class{static async getSigningMethod(t){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(t,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},eK=(t=>(t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution",t))(eK||{}),aA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(aA||{}),tK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(tK||{}),tU="0123456789abcdef",rK=[],rU=[];for(let t=0;t<256;t++)rK[t]=tU[t>>4&15]+tU[t&15],t<16&&(t<10?rU[48+t]=t:rU[87+t]=t);var Cae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=rK[t[n++]];return r},jae=(t,e=0)=>{let r=t.length||0;if(!e){let o=r;for(;o--;)e+=t[o].length}let n=new Uint8Array(e),s=e,a=r;for(;a--;)s-=t[a].length,n.set(t[a],s);return n},nU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$ae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Qg=0;Qg<nU.length;Qg++)$ae[nU.charCodeAt(Qg)]=Qg;var Qg,Mae=new TextDecoder,nK=(t,e)=>e?new TextDecoder(e).decode(t):Mae.decode(t),Oae=new TextEncoder,_d=t=>Oae.encode(t),sU=typeof window<"u"?window:self,iU=sU.crypto||sU.msCrypto||{},N$e=iU.subtle||iU.webkitSubtle;function jw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function sK(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function dr(t,e,r){let n=[],s=null;return dr._encode(n,t),s=jae(n),dr.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}dr.bytes=-1;dr._floatConversionDetected=!1;dr._encode=function(t,e){if(e!=null)switch(sK(e)){case"object":dr.dict(t,e);break;case"map":dr.dictMap(t,e);break;case"array":dr.list(t,e);break;case"set":dr.listSet(t,e);break;case"string":dr.string(t,e);break;case"number":dr.number(t,e);break;case"boolean":dr.number(t,e);break;case"arraybufferview":dr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":dr.buffer(t,new Uint8Array(e));break}};var aP=new Uint8Array([101]),iK=new Uint8Array([100]),oK=new Uint8Array([108]);dr.buffer=function(t,e){t.push(_d(e.length+":"),e)};dr.string=function(t,e){t.push(_d(_d(e).byteLength+":"+e))};dr.number=function(t,e){if(Number.isInteger(e))return t.push(_d("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(_d("i"+a+"e")),a!==e&&!dr._floatConversionDetected&&(dr._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};dr.dict=function(t,e){t.push(iK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(dr.string(t,n),dr._encode(t,e[n]));t.push(aP)};dr.dictMap=function(t,e){t.push(iK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?dr._encode(t,n):dr.string(t,String(n)),dr._encode(t,e.get(n)));t.push(aP)};dr.list=function(t,e){let r=0,n=e.length;for(t.push(oK);r<n;r++)e[r]!=null&&dr._encode(t,e[r]);t.push(aP)};dr.listSet=function(t,e){t.push(oK);for(let r of e)r!=null&&dr._encode(t,r);t.push(aP)};var Bae=dr,Nae=105,Uae=58,Lae=100,Kae=108,cA=101;function aK(t,e,r){let n=0,s=1;for(let a=e;a<r;a++){let o=t[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){s=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*s}function lt(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),lt.position=0,lt.encoding=n||null,lt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):_d(t),lt.bytes=lt.data.length,lt.next())}lt.bytes=0;lt.position=0;lt.data=null;lt.encoding=null;lt.next=function(){switch(lt.data[lt.position]){case Lae:return lt.dictionary();case Kae:return lt.list();case Nae:return lt.integer();default:return lt.buffer()}};lt.find=function(t){let e=lt.position,r=lt.data.length,n=lt.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};lt.dictionary=function(){lt.position++;let t={};for(;lt.data[lt.position]!==cA;){let e=lt.buffer(),r=nK(e);r.includes("\uFFFD")&&(r=Cae(e)),t[r]=lt.next()}return lt.position++,t};lt.list=function(){lt.position++;let t=[];for(;lt.data[lt.position]!==cA;)t.push(lt.next());return lt.position++,t};lt.integer=function(){let t=lt.find(cA),e=aK(lt.data,lt.position+1,t);return lt.position+=t+1-lt.position,e};lt.buffer=function(){let t=lt.find(Uae),e=aK(lt.data,lt.position,t),r=++t+e;return lt.position=r,lt.encoding?nK(lt.data.slice(t,r)):lt.data.slice(t,r)};var zae=lt;function qae(t){let e=2;for(let r of t)e+=cP(r);return e}function Fae(t){let e=2;for(let[r,n]of t){let s=_d(r).byteLength;e+=jw(s)+1+s,e+=cP(n)}return e}function Gae(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=_d(r[n]).byteLength;e+=jw(s)+1+s,e+=cP(t[r[n]])}return e}function Wae(t){let e=_d(t).byteLength;return jw(e)+1+e}function Vae(t){let e=t.byteLength-t.byteOffset;return jw(e)+1+e}function cP(t){if(t==null)return 0;let e=sK(t);switch(e){case"arraybufferview":return Vae(t);case"string":return Wae(t);case"array":case"set":return qae(t);case"number":return 1+jw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return Gae(t);case"map":return Fae(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var cK=cP,Hae=cK,dK={encode:Bae,decode:zae,byteLength:cK,encodingLength:Hae},Jae=/^(\d{1,3}\.){3,3}\d{1,3}$/,Zae=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,xc={name:"v4",size:4,isFormat:t=>Jae.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,s=0;for(let a=0;a<n;){let o=t.charCodeAt(a++);o===46?(e[r++]=s,s=0):s=s*10+(o-48)}return e[r]=s,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},Wu={name:"v6",size:16,isFormat:t=>t.length>0&&Zae.test(t),encode(t,e,r){r=~~r;let n=r+16,s=-1,a=0,o=0,i=!0,c=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(i?s!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(s=r):(c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,o=0),i=!0,c=!1):d===46?(r<n&&(e[r]=o),r++,o=0,a=0,i=!1,c=!0):(i=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(i===!1)c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(s===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(s!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=s+2;u--)e[u]=e[u-2];e[s]=0,e[s+1]=0,s=r}if(s!==r&&s!==-1)for(r>n-2&&(r=n-2);n>s;)e[--n]=r<n&&r>s?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function uK(t){if(xc.isFormat(t))return xc.size;if(Wu.isFormat(t))return Wu.size;throw Error(`Invalid ip address: ${t}`)}function Yae(t){return uK(t)===xc.size?1:2}function Qae(t,e,r){r=~~r;let n=uK(t);return typeof e=="function"&&(e=e(r+n)),n===xc.size?xc.encode(t,e,r):Wu.encode(t,e,r)}function Xae(t,e,r){if(e=~~e,r=r||t.length-e,r===xc.size)return xc.decode(t,e,r);if(r===Wu.size)return Wu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${xc.size} for v4 or ${Wu.size} for v6.`)}function dP(t){switch(t){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_"+t}function Sw(t){switch(t.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 t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}function ece(t){switch(t){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_"+t}function tce(t){switch(t){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_"+t}function lK(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function fK(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function rce(t){switch(t){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 t<0?null:`OPTION_${t}`}function oU(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.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=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function pK(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let s=t.charCodeAt(n);if(s<=127)e+=1;else if(s<=2047)e+=2;else if((s&63488)!==55296)e+=3;else{let a=n+1;a===r||s>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Ew(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(pK(t)+r));let s=r;for(let a=0;a<n;a+=1){let o=t.charCodeAt(a);if(o<=127)e[s++]=o;else if(o<=2047)e[s++]=192|(o&1984)>>6,e[s++]=128|o&63;else if((o&63488)!==55296)e[s++]=224|(o&61440)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63;else{let i=a+1;if(i===n||o>=56320)e[s++]=239,e[s++]=191,e[s++]=189;else{let c=t.charCodeAt(i);(c&64512)!==56320?(e[s++]=239,e[s++]=191,e[s++]=189):(a=i,o=65536|(o&1023)<<10|c&1023,e[s++]=240|(o&1835008)>>18,e[s++]=128|(o&258048)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63)}}}return Ew.bytes=s-r,e}Ew.bytes=0;function $w(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let s=e;s<r;){let a=t[s++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|t[s++]&63;else if(a>239&&a<365){o=((a&7)<<18|(t[s++]&63)<<12|(t[s++]&63)<<6|t[s++]&63)-65536;let i=55296|o>>10&1023;n+=String.fromCharCode(i),o=56320|o&1023}else o=(a&15)<<12|(t[s++]&63)<<6|t[s++]&63;n+=String.fromCharCode(o)}return $w.bytes=r-e,n}$w.bytes=0;var Rf=t=>t instanceof Uint8Array;function Hu(t){return typeof t=="string"?pK(t):t.byteLength}function dA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Ew(t)}function uA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Ew(e,t,r),Ew.bytes}var sw={},hK=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let s=n.toString(16),a=s.toUpperCase(),o=t<<4|n,i=`${e}${s}`;hK[o]=i,sw[i]=o,sw[`${r}${s}`]=o,sw[`${e}${a}`]=o,sw[`${r}${a}`]=o}}function nce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=hK[a]}return n}function aU(t){return t.length>>>1}function sce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=sw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var ice=Math.pow(2,24),oce=Math.pow(2,16),ace=Math.pow(2,8),Sd=(t,e)=>t[e]*ice+t[e+1]*oce+t[e+2]*ace+t[e+3],Dt=(t,e)=>t[e]<<8|t[e+1],Ed=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),Xe=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function yo(t,e,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=e.length||n>=s?0:cce(t,e,r,n,s)}function cce(t,e,r,n,s){s-n>e.length-r&&(s=n+e.length-r);let a=s-n,o=t.length-n;return a>o&&(a=o),(n!==0||s<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}var dce=0,cU=32768,_I=32768,uce=~_I,mK=32768,lce=~mK;function Mr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Fe=Mr({encode(t,e,r){e||(e=new Uint8Array(Fe.encodingLength(t))),r||(r=0);let n=r,s=t.replace(/^\.|\.$/gm,"");if(s.length){let a=s.split(".");for(let o=0;o<a.length;o++){let i=uA(e,a[o],r+1);e[r]=i,r+=i+1}}return e[r++]=0,Fe.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,s=0,a=0,o=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let i=t[e++];if(a+=o?0:1,i===0)break;if(i&192)if((i&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let c=Dt(t,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+i>t.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=i+1,s>254)throw new Error("Cannot decode name (name too long)");r.push($w(t,e,e+i)),e+=i,a+=o?0:i}}return Fe.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Hu(t.replace(/^\.|\.$/gm,""))+2}}),Zn=Mr({encode(t,e,r){e||(e=new Uint8Array(Zn.encodingLength(t))),r||(r=0);let n=uA(e,t,r+1);return e[r]=n,Zn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=$w(t,e+1,e+1+r);return Zn.decode.bytes=r+1,n},encodingLength(t){return Hu(t)+1}}),$h=Mr({bytes:12,encode(t,e,r){e||(e=new Uint8Array($h.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?cU:dce;return Xe(e,t.id||0,r),Xe(e,n|s,r+2),Xe(e,t.questions.length,r+4),Xe(e,t.answers.length,r+6),Xe(e,t.authorities.length,r+8),Xe(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=Dt(t,e+2);return{id:Dt(t,e),type:r&cU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:tce(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:ece(r&15),questions:new Array(Dt(t,e+4)),answers:new Array(Dt(t,e+6)),authorities:new Array(Dt(t,e+8)),additionals:new Array(Dt(t,e+10))}},encodingLength(){return 12}}),k1=Mr({encode(t,e,r){e||(e=new Uint8Array(k1.encodingLength(t))),r||(r=0);let n=t.length;return Xe(e,n,r),yo(t,e,r+2,0,n),k1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=t.slice(e+2,e+2+r);return k1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),_1=Mr({encode(t,e,r){return e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),_1.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=Fe.decode(t,e+2);return _1.decode.bytes=r+2,n},encodingLength(t){return Fe.encodingLength(t)+2}}),T1=Mr({encode(t,e,r){e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mname,e,r),r+=Fe.encode.bytes,Fe.encode(t.rname,e,r),r+=Fe.encode.bytes,Ed(e,t.serial||0,r),r+=4,Ed(e,t.refresh||0,r),r+=4,Ed(e,t.retry||0,r),r+=4,Ed(e,t.expire||0,r),r+=4,Ed(e,t.minimum||0,r),r+=4,Xe(e,r-n-2,n),T1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Fe.decode(t,e),e+=Fe.decode.bytes,n.rname=Fe.decode(t,e),e+=Fe.decode.bytes,n.serial=Sd(t,e),e+=4,n.refresh=Sd(t,e),e+=4,n.retry=Sd(t,e),e+=4,n.expire=Sd(t,e),e+=4,n.minimum=Sd(t,e),e+=4,T1.decode.bytes=e-r,n},encodingLength(t){return 22+Fe.encodingLength(t.mname)+Fe.encodingLength(t.rname)}}),I1=Mr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let s=0;s<t.length;s++)if(typeof t[s]=="string"&&(t[s]=dA(t[s])),!Rf(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,yo(s,e,r,0,s.length),r+=s.length}),Xe(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");s.push(t.slice(e,e+a)),e+=a,n-=a}return I1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Hu(r)+1:e+=r.length+1}),e}}),A1=Mr({encode(t,e,r){e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=dA(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let s=t.length;return yo(t,e,r,0,s),r+=s,Xe(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,A1.decode.bytes=e-r,s},encodingLength(t){return t?(Rf(t)?t.length:Hu(t))+2:2}}),R1=Mr({encode(t,e,r){e||(e=new Uint8Array(R1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Zn.encode(t.cpu,e,r),r+=Zn.encode.bytes,Zn.encode(t.os,e,r),r+=Zn.encode.bytes,Xe(e,r-n-2,n),R1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Zn.decode(t,e),e+=Zn.decode.bytes,n.os=Zn.decode(t,e),e+=Zn.decode.bytes,R1.decode.bytes=e-r,n},encodingLength(t){return Zn.encodingLength(t.cpu)+Zn.encodingLength(t.os)+2}}),Kh=Mr({encode(t,e,r){return e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),Kh.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Fe.decode(t,e+2);return Kh.decode.bytes=Fe.decode.bytes+2,r},encodingLength(t){return Fe.encodingLength(t)+2}}),D1=Mr({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0),Xe(e,t.priority||0,r+2),Xe(e,t.weight||0,r+4),Xe(e,t.port||0,r+6),Fe.encode(t.target,e,r+8);let n=Fe.encode.bytes+6;return Xe(e,n,r),D1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n={};return n.priority=Dt(t,e+2),n.weight=Dt(t,e+4),n.port=Dt(t,e+6),n.target=Fe.decode(t,e+8),D1.decode.bytes=r+2,n},encodingLength(t){return 8+Fe.encodingLength(t.target)}}),qu=Mr({encode(t,e,r){let n=qu.encodingLength(t);return e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=qu.ISSUER_CRITICAL),Xe(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Zn.encode(t.tag,e,r),r+=Zn.encode.bytes,uA(e,t.value,r),r+=Hu(t.value),qu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Dt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Zn.decode(t,e),e+=Zn.decode.bytes,s.value=$w(t,e,n+r),s.issuerCritical=!!(s.flags&qu.ISSUER_CRITICAL),qu.decode.bytes=r+2,s},encodingLength(t){return Zn.encodingLength(t.tag)+Zn.encodingLength(t.value)+2}});qu.ISSUER_CRITICAL=128;var C1=Mr({encode(t,e,r){e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Xe(e,t.preference||0,r),r+=2,Fe.encode(t.exchange,e,r),r+=Fe.encode.bytes,Xe(e,r-n-2,n),C1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Dt(t,e),e+=2,n.exchange=Fe.decode(t,e),e+=Fe.decode.bytes,C1.decode.bytes=e-r,n},encodingLength(t){return 4+Fe.encodingLength(t.exchange)}}),yK=Mr({encode(t,e,r){return e||(e=new Uint8Array(yK.encodingLength(t))),r||(r=0),Xe(e,4,r),r+=2,xc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,xc.decode(t,e)},bytes:6}),j1=Mr({encode(t,e,r){return e||(e=new Uint8Array(j1.encodingLength(t))),r||(r=0),Xe(e,16,r),r+=2,Wu.encode(t,e,r),j1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Wu.decode(t,e);return j1.decode.bytes=18,r},bytes:18}),dU=t=>new Uint8Array(t),Pd=Mr({encode(t,e,r){e||(e=new Uint8Array(Pd.encodingLength(t))),r||(r=0);let n=r,s=oU(t.code);if(Xe(e,s,r),r+=2,t.data)Xe(e,t.data.length,r),r+=2,yo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||Yae(t.ip,dU),i=Qae(t.ip,dU),c=Math.ceil(a/8);Xe(e,c+4,r),r+=2,Xe(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,yo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Xe(e,2,r),r+=2,Xe(e,t.timeout,r),r+=2):(Xe(e,0,r),r+=2);break;case 12:{let a=t.length||0;Xe(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Xe(e,a,r),r+=2;for(let o of t.tags)Xe(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Pd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Dt(t,e),r.type=rce(r.code),e+=2;let n=Dt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Dt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);yo(t,s,0,e,e+n-4),r.ip=Xae(s)}break;case 11:n>0&&(r.timeout=Dt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(Dt(t,e)),e+=2}return Pd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(oU(t.code)){case 8:{let e=t.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),Fu=Mr({encode(t,e,r){e||(e=new Uint8Array(Fu.encodingLength(t))),r||(r=0);let n=r,s=Uh(t,Pd);return Xe(e,s,r),r=uw(t,Pd,e,r+2),Fu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=Dt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=Pd.decode(t,e),e+=Pd.decode.bytes,s-=Pd.decode.bytes;return Fu.decode.bytes=e-r,n},encodingLength(t){return 2+Uh(t||[],Pd)}}),Pc=Mr({encode(t,e,r){e||(e=new Uint8Array(Pc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Rf(s))throw new Error("Key must be a Buffer");return r+=2,Xe(e,t.flags,r),r+=2,e[r]=Pc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,yo(s,e,r,0,s.length),r+=s.length,Pc.encode.bytes=r-n,Xe(e,Pc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);if(e+=2,n.flags=Dt(t,e),e+=2,t[e]!==Pc.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+s+2),e+=n.key.length,Pc.decode.bytes=e-r,n},encodingLength(t){return 6+Hu(t.key)}});Pc.PROTOCOL_DNSSEC=3;Pc.ZONE_KEY=128;Pc.SECURE_ENTRYPOINT=32768;var iw=Mr({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Rf(s))throw new Error("Signature must be a Buffer");return r+=2,Xe(e,Sw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Ed(e,t.originalTTL,r),r+=4,Ed(e,t.expiration,r),r+=4,Ed(e,t.inception,r),r+=4,Xe(e,t.keyTag,r),r+=2,Fe.encode(t.signersName,e,r),r+=Fe.encode.bytes,yo(s,e,r,0,s.length),r+=s.length,iw.encode.bytes=r-n,Xe(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.typeCovered=dP(Dt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=Sd(t,e),e+=4,n.expiration=Sd(t,e),e+=4,n.inception=Sd(t,e),e+=4,n.keyTag=Dt(t,e),e+=2,n.signersName=Fe.decode(t,e),e+=Fe.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,iw.decode.bytes=e-r,n},encodingLength(t){return 20+Fe.encodingLength(t.signersName)+Hu(t.signature)}}),ow=Mr({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mbox||".",e,r),r+=Fe.encode.bytes,Fe.encode(t.txt||".",e,r),r+=Fe.encode.bytes,ow.encode.bytes=r-n,Xe(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Fe.decode(t,e)||".",e+=Fe.decode.bytes,n.txt=Fe.decode(t,e)||".",e+=Fe.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.mbox||".")+Fe.encodingLength(t.txt||".")}}),mo=Mr({encode(t,e,r){e||(e=new Uint8Array(mo.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=Sw(t[a]);s[o>>8]===void 0&&(s[o>>8]=[]),s[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<s.length;a++)if(s[a]!==void 0){let o=dA(s[a]);e[r]=a,r+=1,e[r]=o.length,r+=1,yo(o,e,r,0,o.length),r+=o.length}return mo.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,s=[];for(;e-n<r;){let a=t[e];e+=1;let o=t[e];e+=1;for(let i=0;i<o;i++){let c=t[e+i];for(let u=0;u<8;u++)if(c&1<<7-u){let d=dP(a<<8|i<<3|u);s.push(d)}}e+=o}return mo.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=Sw(t[n]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),aw=Mr({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.nextDomain,e,r),r+=Fe.encode.bytes,mo.encode(t.rrtypes,e,r),r+=mo.encode.bytes,aw.encode.bytes=r-n,Xe(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.nextDomain=Fe.decode(t,e),e+=Fe.decode.bytes,n.rrtypes=mo.decode(t,e,s-(e-r)),e+=mo.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.nextDomain)+mo.encodingLength(t.rrtypes)}}),cw=Mr({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Rf(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Rf(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Xe(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,yo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,yo(a,e,r,0,a.length),r+=a.length,mo.encode(t.rrtypes,e,r),r+=mo.encode.bytes,cw.encode.bytes=r-n,Xe(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Dt(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let o=t[e];return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=mo.decode(t,e,s-(e-r)),e+=mo.decode.bytes,cw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+mo.encodingLength(t.rrtypes)}}),dw=Mr({encode(t,e,r){e||(e=new Uint8Array(dw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Rf(s))throw new Error("Digest must be a Buffer");return r+=2,Xe(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,yo(s,e,r,0,s.length),r+=s.length,dw.encode.bytes=r-n,Xe(e,dw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.keyTag=Dt(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+s+2),e+=n.digest.length,dw.decode.bytes=e-r,n},encodingLength(t){return 6+Hu(t.digest)}}),Nh=Mr({encode(t,e,r){e||(e=new Uint8Array(Nh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=aU(t.fingerprint),a=TI(t.hash);if(s!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${s} != ${a}`);return sce(e,t.fingerprint,r,r+=s),Nh.encode.bytes=r-n,Xe(e,Nh.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let s=TI(n.hash);return n.fingerprint=nce(t,e,e+s),e+=s,Nh.decode.bytes=e-r,n},encodingLength(t){return 4+aU(t.fingerprint)}});function TI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Nh.getFingerprintLengthForHashType=TI;function pI(t){switch(t.toUpperCase()){case"A":return yK;case"PTR":return Kh;case"CNAME":return Kh;case"DNAME":return Kh;case"TXT":return I1;case"NULL":return A1;case"AAAA":return j1;case"SRV":return D1;case"HINFO":return R1;case"CAA":return qu;case"NS":return _1;case"SOA":return T1;case"MX":return C1;case"OPT":return Fu;case"DNSKEY":return Pc;case"RRSIG":return iw;case"RP":return ow;case"NSEC":return aw;case"NSEC3":return cw;case"SSHFP":return Nh;case"DS":return dw}return k1}var qo=Mr({encode(t,e,r){e||(e=new Uint8Array(qo.encodingLength(t))),r||(r=0);let n=r;if(Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,Sw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Xe(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Xe(e,t.flags||0,r+6),r+=8,Fu.encode(t.options||[],e,r),r+=Fu.encode.bytes}else{let s=fK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Xe(e,s,r+2),Ed(e,t.ttl||0,r+4),r+=8;let a=pI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return qo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Fe.decode(t,e),e+=Fe.decode.bytes,r.type=dP(Dt(t,e)),r.type==="OPT")r.udpPayloadSize=Dt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Dt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=Fu.decode(t,e+8),e+=8+Fu.decode.bytes;else{let s=Dt(t,e+2);r.ttl=Sd(t,e+4),r.class=lK(s&uce),r.flush=!!(s&_I);let a=pI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return qo.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Fe.encodingLength(t.name)+8+pI(t.type).encodingLength(e)}}),zh=Mr({encode(t,e,r){e||(e=new Uint8Array(zh.encodingLength(t))),r||(r=0);let n=r;return Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,Sw(t.type),r),r+=2,Xe(e,fK(t.class===void 0?"IN":t.class),r),r+=2,zh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Fe.decode(t,e),e+=Fe.decode.bytes,n.type=dP(Dt(t,e)),e+=2,n.class=lK(Dt(t,e)),e+=2,n.class&mK&&(n.class&=lce),zh.decode.bytes=e-r,n},encodingLength(t){return Fe.encodingLength(t.name)+4}}),fce=1024,Bs={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(pce(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),$h.encode(t,e,r),r+=$h.encode.bytes,r=uw(t.questions,zh,e,r),r=uw(t.answers,qo,e,r),r=uw(t.authorities,qo,e,r),r=uw(t.additionals,qo,e,r),Bs.encode.bytes=r-s,n&&Y1.bytes!==e.length?e.slice(0,Y1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=$h.decode(t,e);return e+=$h.decode.bytes,e=g1(n.questions,zh,t,e),e=g1(n.answers,qo,t,e),e=g1(n.authorities,qo,t,e),e=g1(n.additionals,qo,t,e),Bs.decode.bytes=e-r,n},encodingLength:function(t){return $h.encodingLength(t)+Uh(t.questions||[],zh)+Uh(t.answers||[],qo)+Uh(t.authorities||[],qo)+Uh(t.additionals||[],qo)}};Bs.encode.bytes=0;Bs.decode.bytes=0;function H1(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var J1={encode:function(t,e,r){return e=Bs.encode(H1(t,"query"),e,r),J1.encode.bytes=Bs.encode.bytes,e},decode:function(t,e){let r=Bs.decode(t,e);return J1.decode.bytes=Bs.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Bs.encodingLength(H1(t,"query"))}};J1.encode.bytes=0;J1.decode.bytes=0;var Z1={encode:function(t,e,r){return e=Bs.encode(H1(t,"response"),e,r),Z1.encode.bytes=Bs.encode.bytes,e},decode:function(t,e){let r=Bs.decode(t,e);return Z1.decode.bytes=Bs.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Bs.encodingLength(H1(t,"response"))}};Z1.encode.bytes=0;Z1.decode.bytes=0;var Y1=Bs.encode,II=Bs.decode,pce=Bs.encodingLength;function gK(t){let e=Y1(t),r=new Uint8Array(2+e.byteLength);return Xe(r,e.byteLength),yo(e,r,2,0,e.length),gK.bytes=r.byteLength,r}gK.bytes=0;function wK(t){let e=Dt(t,0);if(t.byteLength<e+2)return null;let r=II(t.slice(2));return wK.bytes=II.bytes,r}wK.bytes=0;function Uh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function uw(t,e,r,n){for(let s=0;s<t.length;s++)e.encode(t[s],r,n),n+=e.encode.bytes;return n}function g1(t,e,r,n){for(let s=0;s<t.length;s++)t[s]=e.decode(r,n),n+=e.decode.bytes;return n}function vK(t,e){let r=Qe.uint8Array(t).toBase32Z();return new URL(r,e).href}async function hce({gatewayUri:t,publicKeyBytes:e}){let r=Qe.uint8Array(e).toBase32Z(),n=vK(e,t),s;try{if(s=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!s.ok)throw new Ze("notFound",`Pkarr record not found for: ${r}`)}catch(o){throw o instanceof Ze?o:new Ze("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await s.arrayBuffer();if(!a)throw new Ze("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new Ze("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new Ze("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function mce({gatewayUri:t,bep44Message:e}){let r=Qe.uint8Array(e.k).toBase32Z(),n=vK(e.k,t),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 a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)})}catch(o){throw new Ze("internalError",`Failed to put Pkarr record for identifier ${r}: ${o.message}`)}return a.ok}async function yce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Y1(t),a=dK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new Ze("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:s}}async function gce({bep44Message:t}){let e=await Ms.bytesToPublicKey({publicKeyBytes:t.k}),r=dK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await Ms.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new Ze("invalidSignature","Invalid signature for DHT BEP44 message");return II(t.v)}var bK="dht";async function PK({didUri:t}){let e=lA({didUri:t});return await Ms.bytesToPublicKey({publicKeyBytes:e})}function lA({didUri:t}){let e=ls.parse(t);if(!e)throw new Ze("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==bK)throw new Ze("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Qe.base32Z(e.id).toUint8Array()}catch{throw new Ze("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new Ze("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function wce({identityKey:t}){let e=await Ms.publicKeyToBytes({publicKey:t}),r=Qe.uint8Array(e).toBase32Z();return`did:${bK}:${r}`}function fA(t){let e={Ed25519:Ms,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await ei.publicKeyToBytes({publicKey:r});return await ei.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ei.bytesToPublicKey,privateKeyToBytes:ei.privateKeyToBytes,bytesToPrivateKey:ei.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await $s.publicKeyToBytes({publicKey:r});return await $s.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:$s.bytesToPublicKey,privateKeyToBytes:$s.privateKeyToBytes,bytesToPrivateKey:$s.bytesToPrivateKey},X25519:jh}[t];if(!e)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function xK({newDid:t,previousDidProof:e}){let r=await PK({didUri:e.previousDid}),n=lA({didUri:t}),s=Qe.base64Url(e.signature).toUint8Array();if(!await Ms.verify({key:r,data:n,signature:s}))throw new Ze("invalidPreviousDidProof","The previous DID proof is invalid.")}var vce=0,Uu=7200,$1=";",Ei=",",SK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},EK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function kw(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Qe.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>kw(e)).join("");throw new Ze("internalError","Pkarr returned DNS TXT record with invalid data type")}function lw(t){return kw(t).split($1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function kK(t){if(t.length<=255)return t;let e=[];for(let r=0;r<t.length;r+=255)e.push(t.slice(r,r+255));return e}async function bce({didUri:t,dnsPacket:e}){let r={id:t},n={published:!0},s=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let i=kw(a.data);r.alsoKnownAs=i.split(Ei);break}case o.startsWith("cnt"):{let i=kw(a.data);r.controller=i.includes(Ei)?i.split(Ei):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=lw(a.data),f=Qe.base64Url(u).toUint8Array(),h=aA[Number(c)],p=await fA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||EK[Number(c)];let m=o==="k0"?"0":i!==void 0?i:await pr({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??t,publicKeyJwk:p}),s.set(o,y);break}case o.startsWith("s"):{let{id:i,t:c,se:u,...d}=lw(a.data),l=u.includes(Ei)?u.split(Ei):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(Ei)?p.split(Ei):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=lw(a.data);n.types=i.split(Ei).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(Ei).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=lw(a.data);c&&(r.authentication=i(c)),u&&(r.assertionMethod=i(u)),d&&(r.capabilityDelegation=i(d)),l&&(r.capabilityInvocation=i(l)),f&&(r.keyAgreement=i(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function Pce({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let s=[],a=[],o=new Map,i=[],c=[];if(n!==void 0){let{signature:d,previousDid:l}=n;await xK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Uu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Uu,data:t.alsoKnownAs.join(Ei)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(Ei):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Uu,data:d})}for(let[d,l]of t.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let h=l.id.split("#").pop();o.set(h,f);let p=l.publicKeyJwk;if(!(p?.crv&&p.crv in SK))throw new Ze("invalidPublicKeyType",`Verification method '${l.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=aA[p.crv],y=await fA(p.crv).publicKeyToBytes({publicKey:p}),S=Qe.uint8Array(y).toBase64Url(),v=[`t=${m}`,`k=${S}`];h!=="0"&&await pr({jwk:p})!==h&&v.unshift(`id=${h}`),p.alg!==EK[m]&&v.push(`a=${p.alg}`),l.controller!==t.id&&v.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Uu,data:v.join($1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=ki(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,_])=>`${E}=${_}`).join($1),v=kK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Uu,data:v})});let u=[`v=${vce}`];if(c.length&&u.push(`vm=${c.join(Ei)}`),Object.keys(tP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=tK[d];u.push(`${f}=${l.join(Ei)}`)}}),i.length&&u.push(`svc=${i.join(Ei)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?eK[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Uu,data:`id=${d.join(Ei)}`})}s.push({type:"TXT",name:"_did."+uU(t.id)+".",ttl:Uu,data:u.join($1)});for(let d of r||[])a.push({type:"NS",name:"_did."+uU(t.id)+".",ttl:Uu,data:d+"."});return{id:0,type:"response",flags:fce,answers:[...s,...a]}}function uU(t){return t.split(":")[2]}var lU=U.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",_K=class AI extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in SK)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let s=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:s}),o=await Lh.identityKeyToIdentifier({identityKey:a}),i={id:o,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},c=[...r.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let l=d.id&&d.id.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await pr({jwk:f});h=`${o}#${ki(h)}`,i.verificationMethod??=[],i.verificationMethod.push({id:h,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let p of d.purposes??[])i[p]??=[],i[p].push(h)}r.services?.forEach(d=>{i.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,i.service.push(d)});let u=new kc({uri:o,document:i,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let d=await AI.publish({did:u,gatewayUri:r.gatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==AI.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new Ze("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>ki(a.id)===(ki(r)??ki(e.assertionMethod?.[0])));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r=lU}){return await fU.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??lU;try{await Lh.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:a}=await fU.get({didUri:e,gatewayUri:n});return{...us,didDocument:s,didDocumentMetadata:a}}catch(s){if(!(s instanceof Ze))throw new Error(s);return{...us,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};_K.methodName="dht";var TK=_K,fU=class fw{static async get({didUri:e,gatewayUri:r}){let n=Lh.identifierToIdentityKeyBytes({didUri:e}),s=await fw.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await Lh.parseBep44GetMessage({bep44Message:s}),o=await fw.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=s.seq.toString(),o}static async put({did:e,gatewayUri:r}){let n=await fw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),s=await Lh.createBep44PutMessage({dnsPacket:n,publicKeyBytes:Lh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await fw.pkarrPut({gatewayUri:r,bep44Message:s});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return hce(e)}static async pkarrPut(e){return mce(e)}static async fromDnsPacket(e){return bce(e)}static async toDnsPacket(e){return Pce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Lh=class{static async createBep44PutMessage(t){return yce(t)}static async identifierToIdentityKey(t){return PK(t)}static identifierToIdentityKeyBytes(t){return lA(t)}static async identityKeyToIdentifier(t){return wce(t)}static keyConverter(t){return fA(t)}static async parseBep44GetMessage(t){return gce(t)}static parseTxtDataToObject(t){return lw(t)}static parseTxtDataToString(t){return kw(t)}static async validatePreviousDidProof(t){return xK(t)}static chunkDataIfNeeded(t){return kK(t)}},Rn={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"},Dn=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},U$e=new Uint8Array(0),xce=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Sce=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ece=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return IK(this,t)}},kce=class{constructor(t){this.decoders=t}or(t){return IK(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},IK=(t,e)=>new kce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),_ce=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Sce(t,e,r),this.decoder=new Ece(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},Tce=({name:t,prefix:e,encode:r,decode:n})=>new _ce(t,e,r,n),Ice=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Ace=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},uP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Tce({prefix:e,name:t,encode(s){return Ace(s,n,r)},decode(s){return Ice(s,n,r,t)}}),L$e=uP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),K$e=uP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pU=uP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),z$e=uP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Wh=class M1{static encode(e){return pU.baseEncode(e)}static decodeAsBytes(e,r){if(!M1.isBase64UrlString(e))throw new Dn(Rn.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return pU.baseDecode(e)}static decodeAsString(e,r){let n=M1.decodeAsBytes(e,r);return M1.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)}},Rce=Df(Tne(),1),RI;(function(t){t.Public="public",t.Private="private"})(RI||(RI={}));var bc=RI,fo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===bc.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new Dn(Rn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new Dn(Rn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new Dn(Rn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===bc.Private&&(t.d===void 0||t.d.length!==43))throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new Dn(Rn.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!Wh.isBase64UrlString(t))throw new Dn(Rn.IdNotUsingBase64UrlCharacterSet,`Key ID '${t}' is not a Base64URL string.`)}static validatePublicKeyPurposes(t){if(t===void 0)return;let e=new Set;for(let r of t){if(e.has(r))throw new Dn(Rn.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},pA=class{};pA.hashAlgorithmInMultihashCode=18;pA.maxCanonicalizedDeltaSizeInBytes=1e3;var Aa=pA,Dce=Df(Ine(),1),_w=class DI{static canonicalizeAsBytes(e){let r=DI.removeAllUndefinedProperties(e),n=Dce.default(r);return Wh.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?DI.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},Cce=AK,hU=128,jce=127,$ce=~jce,Mce=Math.pow(2,31);function AK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Mce;)e[r++]=t&255|hU,t/=128;for(;t&$ce;)e[r++]=t&255|hU,t>>>=7;return e[r]=t|0,AK.bytes=r-n+1,e}var Oce=CI,Bce=128,mU=127;function CI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&mU)<<s:(o&mU)*Math.pow(2,s),s+=7}while(o>=Bce);return CI.bytes=a-n,r}var Nce=Math.pow(2,7),Uce=Math.pow(2,14),Lce=Math.pow(2,21),Kce=Math.pow(2,28),zce=Math.pow(2,35),qce=Math.pow(2,42),Fce=Math.pow(2,49),Gce=Math.pow(2,56),Wce=Math.pow(2,63),Vce=function(t){return t<Nce?1:t<Uce?2:t<Lce?3:t<Kce?4:t<zce?5:t<qce?6:t<Fce?7:t<Gce?8:t<Wce?9:10},Hce={encode:Cce,decode:Oce,encodingLength:Vce},Jce=Hce,Q1=Jce,yU=(t,e=0)=>[Q1.decode(t,e),Q1.decode.bytes],gU=(t,e,r=0)=>(Q1.encode(t,e,r),e),wU=t=>Q1.encodingLength(t),vU=(t,e)=>{let r=e.byteLength,n=wU(t),s=n+wU(r),a=new Uint8Array(s+r);return gU(t,a,0),gU(r,a,n),a.set(e,s),new RK(t,r,e,a)},Zce=t=>{let e=xce(t),[r,n]=yU(e),[s,a]=yU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new RK(r,s,o,e)},RK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},DK=({name:t,code:e,encode:r})=>new Yce(t,e,r),Yce=class{constructor(t,e,r){this.name=t,this.code=e,this.encode=r}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?vU(this.code,e):e.then(r=>vU(this.code,r))}else throw Error("Unknown type, must be binary type")}},CK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),bU=DK({name:"sha2-256",code:18,encode:CK("SHA-256")}),q$e=DK({name:"sha2-512",code:19,encode:CK("SHA-512")}),Xg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},ho=class pw{static hash(e,r){return Xg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield bU.digest(e)).bytes;break;default:throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Xg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield bU.encode(e);break;default:throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e);return yield pw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e),s=yield pw.hashAsNonMultihashBytes(n,r);return yield pw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=yield pw.hash(e,r);return Wh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Wh.decodeAsBytes(e,r);try{n=Zce(s)}catch{throw new Dn(Rn.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Aa.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}},jI;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(jI||(jI={}));var w1=jI,$I;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})($I||($I={}));var Ch=$I,v1=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},jK=class Ko{static createCreateRequest(e){return v1(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,s=e.document.publicKeys,a=e.document.services;fo.validateEs256kOperationKey(r,bc.Public),fo.validateEs256kOperationKey(n,bc.Public),Ko.validateDidDocumentKeys(s),Ko.validateServices(a);let o=Aa.hashAlgorithmInMultihashCode,i=[{action:Ch.Replace,document:e.document}],c={updateCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Ko.validateDeltaSize(c);let u={deltaHash:yield ho.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:w1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return v1(this,void 0,void 0,function*(){Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.recoveryPublicKey,bc.Public);let r=Aa.hashAlgorithmInMultihashCode,n=yield ho.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},s);return{type:w1.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return v1(this,void 0,void 0,function*(){Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.recoveryPublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextRecoveryPublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextUpdatePublicKey,bc.Public),Ko.validateDidDocumentKeys(e.document.publicKeys),Ko.validateServices(e.document.services);let r=Aa.hashAlgorithmInMultihashCode,n=yield ho.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Ch.Replace,document:e.document}],a=yield ho.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield ho.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:i},u=yield e.signer.sign({alg:"ES256K"},c);return{type:w1.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:u}})}static createUpdateRequest(e){return v1(this,void 0,void 0,function*(){if(Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.updatePublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextUpdatePublicKey,bc.Public),Ko.validateServices(e.servicesToAdd),Ko.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)fo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)fo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Ch.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Ch.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Ch.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Ch.RemovePublicKeys,ids:o};r.push(p)}let i=Aa.hashAlgorithmInMultihashCode,c=yield ho.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield ho.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield ho.canonicalizeThenHashThenEncode(d,i),f={updateKey:e.updatePublicKey,deltaHash:l},h=yield e.signer.sign({alg:"ES256K"},f);return{type:w1.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:h}})}static validateDidSuffix(e){ho.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Dn(Rn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(fo.validateId(n.id),r.has(n.id))throw new Dn(Rn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),fo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Ko.validateService(n),r.has(n.id))throw new Dn(Rn.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){fo.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Dn(Rn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Dn(Rn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Rce.parse(e.serviceEndpoint).error!==void 0)throw new Dn(Rn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=_w.canonicalizeAsBytes(e);if(r.length>Aa.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Aa.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Dn(Rn.DeltaExceedsMaximumSize,n)}}},PU=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Qce=class $K{static createLongFormDid(e){return PU(this,void 0,void 0,function*(){let r=yield jK.createCreateRequest(e),n=yield $K.computeDidUniqueSuffix(r.suffixData),s;Aa.network===void 0||Aa.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Aa.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=_w.canonicalizeAsBytes(a),i=Wh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return PU(this,void 0,void 0,function*(){let r=_w.canonicalizeAsBytes(e),n=yield ho.hash(r,Aa.hashAlgorithmInMultihashCode);return Wh.encode(n)})}},js=2n**255n-19n,O1=2n**252n+27742317777372353535851937790883648493n,MI=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,OI=0x6666666666666666666666666666666666666666666666666666666666666658n,b1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:js,n:O1,h:8,Gx:MI,Gy:OI},Li=(t="")=>{throw new Error(t)},MK=t=>typeof t=="string",hA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Li("Uint8Array expected"):t,Vh=t=>new Uint8Array(t),Xce=(t,e)=>hA(MK(t)?yA(t):Vh(t),e),nt=(t,e=js)=>{let r=t%e;return r>=0n?r:e+r},xU=t=>t instanceof Hh?t:Li("Point expected"),SU,Hh=class Mh{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new Mh(e.x,e.y,1n,nt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=b1;e=Xce(e,32);let s=e.slice();s[31]=e[31]&-129;let a=tde(s);a===0n||(r&&!(0n<a&&a<js)&&Li("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Li("bad y coord 2"));let o=nt(a*a),i=nt(o-1n),c=nt(n*o+1n),{isValid:u,value:d}=nde(i,c);u||Li("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=nt(-d)),new Mh(d,a,1n,nt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:s}=this,{ex:a,ey:o,ez:i}=xU(e),c=nt(r*i),u=nt(a*s),d=nt(n*i),l=nt(o*s);return c===u&&d===l}is0(){return this.equals(B1)}negate(){return new Mh(nt(-this.ex),this.ey,this.ez,nt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=b1,a=nt(e*e),o=nt(r*r),i=nt(2n*nt(n*n)),c=nt(s*a),u=e+r,d=nt(nt(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=nt(d*f),m=nt(l*h),y=nt(d*h),S=nt(f*l);return new Mh(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=xU(e),{a:d,d:l}=b1,f=nt(r*o),h=nt(n*i),p=nt(a*l*u),m=nt(s*c),y=nt((r+n)*(o+i)-f-h),S=nt(m-p),v=nt(m+p),E=nt(h-d*f),_=nt(y*S),I=nt(v*E),R=nt(y*E),N=nt(S*v);return new Mh(_,I,N,R)}mul(e,r=!0){if(e===0n)return r===!0?Li("cannot multiply by 0"):B1;if(typeof e=="bigint"&&0n<e&&e<O1||Li("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(X1))return ode(e).p;let n=B1,s=X1;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(b1.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(O1/2n,!1).double();return O1%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:r,ez:n}=this;if(this.is0())return{x:0n,y:0n};let s=BK(n);return nt(n*s)!==1n&&Li("invalid inverse"),{x:nt(e*s),y:nt(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=ede(r);return n[31]|=e&1n?128:0,n}toHex(){return mA(this.toRawBytes())}};Hh.BASE=new Hh(MI,OI,1n,nt(MI*OI));Hh.ZERO=new Hh(0n,1n,1n,0n);var{BASE:X1,ZERO:B1}=Hh,OK=(t,e)=>t.toString(16).padStart(e,"0"),mA=t=>Array.from(t).map(e=>OK(e,2)).join(""),yA=t=>{let e=t.length;(!MK(t)||e%2)&&Li("hex invalid 1");let r=Vh(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Li("hex invalid 2"),r[n]=o}return r},ede=t=>yA(OK(t,32*2)).reverse(),tde=t=>BigInt("0x"+mA(Vh(hA(t)).reverse())),EU=(...t)=>{let e=Vh(t.reduce((n,s)=>n+hA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},BK=(t,e=js)=>{(t===0n||e<=0n)&&Li("no inverse n="+t+" mod="+e);let r=nt(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?nt(s,e):Li("no inverse")},gc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=js;return r},rde=t=>{let e=t*t%js*t%js,r=gc(e,2n)*e%js,n=gc(r,1n)*t%js,s=gc(n,5n)*n%js,a=gc(s,10n)*s%js,o=gc(a,20n)*a%js,i=gc(o,40n)*o%js,c=gc(i,80n)*i%js,u=gc(c,80n)*i%js,d=gc(u,10n)*s%js;return{pow_p_5_8:gc(d,2n)*t%js,b2:e}},kU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,nde=(t,e)=>{let r=nt(e*e*e),n=nt(r*r*e),s=rde(t*n).pow_p_5_8,a=nt(t*r*s),o=nt(e*a*a),i=a,c=nt(a*kU),u=o===t,d=o===nt(-t),l=o===nt(-t*kU);return u&&(a=i),(d||l)&&(a=c),(nt(a)&1n)===1n&&(a=nt(-a)),{isValid:u||d,value:a}},hI,_U=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,sde={bytesToHex:mA,hexToBytes:yA,concatBytes:EU,mod:nt,invert:BK,randomBytes:t=>{let e=_U();return e||Li("crypto.getRandomValues must be defined"),e.getRandomValues(Vh(t))},sha512Async:async(...t)=>{let e=_U();e||Li("crypto.subtle or etc.sha512Async must be defined");let r=EU(...t);return Vh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(sde,{sha512Sync:{configurable:!1,get(){return hI},set(t){hI||(hI=t)}}});var Pf=8,ide=()=>{let t=[],e=256/Pf+1,r=X1,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(Pf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},ode=t=>{let e=SU||(SU=ide()),r=(d,l)=>{let f=l.negate();return d?f:l},n=B1,s=X1,a=1+256/Pf,o=2**(Pf-1),i=BigInt(2**Pf-1),c=2**Pf,u=BigInt(Pf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},gA=2n**256n,Tf=gA-0x1000003d1n,wA=gA-0x14551231950b75fc4402da1732fc9bebfn,NK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,UK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,LK={p:Tf,n:wA,a:0n,b:7n,Gx:NK,Gy:UK},qh=32,TU=t=>He(He(t*t)*t+LK.b),ds=(t="")=>{throw new Error(t)},lP=t=>typeof t=="bigint",KK=t=>typeof t=="string",mI=t=>lP(t)&&0n<t&&t<Tf,zK=t=>lP(t)&&0n<t&&t<wA,qK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?ds("Uint8Array expected"):t,Tw=t=>new Uint8Array(t),vA=(t,e)=>qK(KK(t)?fP(t):Tw(t),e),He=(t,e=Tf)=>{let r=t%e;return r>=0n?r:e+r},IU=t=>t instanceof Jh?t:ds("Point expected"),AU,Jh=class Oh{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new Oh(e.x,e.y,1n)}static fromHex(e){e=vA(e);let r,n=e[0],s=e.subarray(1),a=RU(s,0,qh),o=e.length;if(o===33&&[2,3].includes(n)){mI(a)||ds("Point hex invalid: x not FE");let i=ade(TU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=He(-i)),r=new Oh(a,i,1n)}return o===65&&n===4&&(r=new Oh(a,RU(s,qh,2*qh),1n)),r?r.ok():ds("Point is not on curve")}static fromPrivateKey(e){return gw.mul(cde(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=IU(e),c=He(r*i),u=He(a*s),d=He(n*i),l=He(o*s);return c===u&&d===l}negate(){return new Oh(this.px,He(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=IU(e),{a:c,b:u}=LK,d=0n,l=0n,f=0n,h=He(u*3n),p=He(r*a),m=He(n*o),y=He(s*i),S=He(r+n),v=He(a+o);S=He(S*v),v=He(p+m),S=He(S-v),v=He(r+s);let E=He(a+i);return v=He(v*E),E=He(p+y),v=He(v-E),E=He(n+s),d=He(o+i),E=He(E*d),d=He(m+y),E=He(E-d),f=He(c*v),d=He(h*y),f=He(d+f),d=He(m-f),f=He(m+f),l=He(d*f),m=He(p+p),m=He(m+p),y=He(c*y),v=He(h*v),m=He(m+y),y=He(p-y),y=He(c*y),v=He(v+y),p=He(m*v),l=He(l+p),p=He(E*v),d=He(S*d),d=He(d-p),p=He(S*m),f=He(E*f),f=He(f+p),new Oh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return N1;if(zK(e)||ds("invalid scalar"),this.equals(gw))return fde(e).p;let n=N1,s=gw;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}mulAddQUns(e,r,n){return this.mul(r,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:r,pz:n}=this;if(this.equals(N1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=GK(n);return He(n*s)!==1n&&ds("invalid inverse"),{x:He(e*s),y:He(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!mI(e)||!mI(r))&&ds("Point invalid: x or y"),He(r*r)===TU(e)?this:ds("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:r,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+DU(r)+(e?"":DU(n))}toRawBytes(e=!0){return fP(this.toHex(e))}};Jh.BASE=new Jh(NK,UK,1n);Jh.ZERO=new Jh(0n,1n,0n);var{BASE:gw,ZERO:N1}=Jh,FK=(t,e)=>t.toString(16).padStart(e,"0"),bA=t=>Array.from(t).map(e=>FK(e,2)).join(""),fP=t=>{let e=t.length;(!KK(t)||e%2)&&ds("hex invalid 1");let r=Tw(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&ds("hex invalid 2"),r[n]=o}return r},pP=t=>BigInt("0x"+(bA(t)||"0")),RU=(t,e,r)=>pP(t.slice(e,r)),PA=t=>lP(t)&&t>=0n&&t<gA?fP(FK(t,2*qh)):ds("bigint expected"),DU=t=>bA(PA(t)),CU=(...t)=>{let e=Tw(t.reduce((n,s)=>n+qK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},GK=(t,e=Tf)=>{(t===0n||e<=0n)&&ds("no inverse n="+t+" mod="+e);let r=He(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?He(s,e):ds("no inverse")},ade=t=>{let e=1n;for(let r=t,n=(Tf+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%Tf),r=r*r%Tf;return He(e*e)===t?e:ds("sqrt invalid")},cde=t=>(lP(t)||(t=pP(vA(t,qh))),zK(t)?t:ds("private key out of range")),jU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,U1;function dde(t){t=vA(t);let e=qh+8;(t.length<e||t.length>1024)&&ds("expected proper params");let r=He(pP(t),wA-1n)+1n;return PA(r)}var ude={hexToBytes:fP,bytesToHex:bA,concatBytes:CU,bytesToNumberBE:pP,numberToBytesBE:PA,mod:He,invert:GK,hmacSha256Async:async(t,...e)=>{let r=jU();if(!r)return ds("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Tw(await n.sign("HMAC",s,CU(...e)))},hmacSha256Sync:U1,hashToPrivateKey:dde,randomBytes:t=>{let e=jU();return e||ds("crypto.getRandomValues must be defined"),e.getRandomValues(Tw(t))}};Object.defineProperties(ude,{hmacSha256Sync:{configurable:!1,get(){return U1},set(t){U1||(U1=t)}}});var xf=8,lde=()=>{let t=[],e=256/xf+1,r=gw,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(xf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},fde=t=>{let e=AU||(AU=lde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=N1,s=gw,a=1+256/xf,o=2**(xf-1),i=BigInt(2**xf-1),c=2**xf,u=BigInt(xf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},$U;(function(t){t.Mainnet="mainnet",t.Testnet="test"})($U||($U={}));var MU;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(MU||(MU={}));var ew=class vf{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:r,services:n,verificationMethods:s}){let a=await vf.createIonDocument({services:n,verificationMethods:s}),o=vf.normalizeJwk(e),i=vf.normalizeJwk(r);return await Qce.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await jK.createCreateRequest({document:e,recoveryKey:vf.normalizeJwk(r),updateKey:vf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await pr({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:vf.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(i)}let s=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:s}}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}},pde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(pde||{}),hde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},OU="https://ion.tbd.engineering",mde=class hw extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in hde)))throw new Error("One or more verification method algorithms are not supported");let n=r.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(r.services?.some(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let s={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[s]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),i=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),u=await e.getPublicKey({keyUri:c}),d=await ew.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await hw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new kc({uri:d,document:l,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:i,updateKey:u},keyManager:e});if(r.publish??!0){let p=await hw.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==hw.methodName)throw new Ze("methodNotSupported","Method not supported");return await kc.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=OU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:JL({didDocument:e.document,methodId:o.id})}))??[],s=await ew.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await ew.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=ew.appendPathToUrl({baseUrl:r,path:"/operations"}),i=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:i.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,r={}){let n=ls.parse(e);if(!n)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??OU;try{let a=ew.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new Ze("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...us,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Ze))throw new Error(a);return{...us,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};mde.methodName="ion";var WK=class mw extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=Qe.object(a).toBase64Url(),i=`did:${mw.methodName}:${o}`,c=(await mw.resolve(i)).didDocument;return new kc({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=ls.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==mw.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=ls.parse(e),s;try{s=n?Qe.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==mw.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:s}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],s.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...us,didDocument:a}}};WK.methodName="jwk";var VK=WK,yde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},L1=class Bh{static async jwkToMulticodec({jwk:e}){let r=[];e.crv&&(r.push(e.crv),e.d?r.push("private"):r.push("public"));let n=r.join(":"),s=Bh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Jo.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":ei.compressPublicKey,secp256k1:$s.compressPublicKey}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:Ms,"P-256":ei,secp256k1:$s}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static async multicodecToJwk({code:e,name:r}){if(!(r?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");r=r===void 0?Jo.getNameFromCode({code:e}):r;let n=r,s=Bh.MULTICODEC_TO_JWK[n];if(s===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...s}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in yde))throw new Ze("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Bh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Bh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Bh.jwkToMulticodec({jwk:e});return YL({keyBytes:r,multicodecName:n})}};L1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},L1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},L1.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:""}};var P1=L1,gde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(gde||{}),BU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},HK=class zu extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=await P1.publicKeyToMultibaseId({publicKey:a}),i=`did:${zu.methodName}:${o}`,c=(await zu.resolve(i,r)).didDocument;return new kc({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=ls.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==zu.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await zu.createDocument({didUri:e,options:r});return{...us,didDocument:n}}catch(n){if(!(n instanceof Ze))throw new Error(n);return{...us,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:r={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:a="JsonWebKey2020"}=r,o={id:""},i=ls.parse(e);if(!i)throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==zu.methodName)throw new Ze("methodNotSupported",`Method not supported: ${i.method}`);if(!zu.validateIdentifier(i))throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let u=await zu.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}});o.id=i.uri,o.verificationMethod=[u],o.authentication=[u.id],o.assertionMethod=[u.id],o.capabilityInvocation=[u.id],o.capabilityDelegation=[u.id];let d=[n];return HL({didDocument:o}).forEach(l=>{let f=BU[l];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:i,multicodecCode:c,multicodecName:u}=QL({multibaseKeyId:r}),d=i.byteLength,l=P1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new Ze("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await Ms.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new Ze("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new Ze("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in BU))throw new Ze("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Ze("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await P1.multicodecToJwk({code:c});o.publicKeyJwk=await P1.keyConverter(h).bytesToPublicKey({publicKeyBytes:i})}return o}static validateIdentifier(e){let{method:r,id:n}=e,[s]=e.uri.split(":",1);return s==="did"&&r==="key"&&!0&&yI(n)==="String"&&n.startsWith("z")}};HK.methodName="key";var Mw=HK,wde=3e4;function vde(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let s=r.map(Number);if(s.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=s;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var JK=class K1 extends Cw{static async create({keyManager:e=new Ra,options:r}){if(!r.domain)throw new Ze("invalidDid","The 'domain' option is required for did:web creation");if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=r.path?`${r.domain}:${r.path}`:r.domain,s=`did:${K1.methodName}:${n}`;if(!ls.parse(s))throw new Ze("invalidDid",`The constructed DID URI is invalid: ${s}`);let a=r.verificationMethods??[{algorithm:r.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:s};for(let i=0;i<a.length;i++){let c=a[i],u=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:u}),l=c.id?.split("#").pop()??`key-${i}`,f=`${s}#${l}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:d});for(let h of c.purposes??[])o[h]??=[],o[h].push(f)}return r.services&&(o.service=r.services.map(i=>({...i,id:`${s}#${i.id.split("#").pop()}`}))),new kc({uri:s,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=ki(r)??ki(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>ki(o.id)===s):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==K1.methodName)throw new Ze("methodNotSupported","Method not supported");return await kc.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=ls.parse(e);if(!n)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==K1.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let s=`https://${n.id.replace(/:/g,"/")}`;s=decodeURIComponent(s);let a=n.id.includes(":")?`${s}/did.json`:`${s}/.well-known/did.json`;try{let o=new URL(a);if(vde(o.hostname))return{...us,didResolutionMetadata:{error:"notFound"}};let i=await fetch(a,{signal:AbortSignal.timeout(wde)});if(!i.ok)throw new Error("HTTP error status code returned");let c=await i.json();return{...us,didDocument:c}}catch{return{...us,didResolutionMetadata:{error:"notFound"}}}}};JK.methodName="web";var ZK=JK,F$e=Df(VU(),1),G$e=Df(HU(),1);var bde=Df(HU(),1),YK=class{constructor({ttl:t="15m"}={}){this.cache=new Rne.default({ttl:(0,bde.default)(t)})}async open(){}async get(t){if(!t)throw new Error("Key cannot be null or undefined");return this.cache.get(t)}async set(t,e){this.cache.set(t,e)}async delete(t){this.cache.delete(t)}async clear(){this.cache.clear()}async close(){}},Pde={open(){return Promise.resolve()},get(t){return Promise.resolve(void 0)},set(t,e){return Promise.resolve()},delete(t){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},QK=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||Pde;for(let r of e)this.didResolvers.set(r.methodName,r)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(t,e){let r=ls.parse(t);if(!r)return{...us,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...us,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let s=await this.cache.get(r.uri);if(s)return s;{let a=await n.resolve(r.uri,e);return a.didResolutionMetadata.error||await this.cache.set(r.uri,a),a}}async dereference(t,e){let r=ls.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:s,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:s.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:i=[]}=n,c=new Set([t,r.fragment,`#${r.fragment}`]),u;for(let d of i)if(c.has(d.id)){u=d;break}for(let d of o)if(c.has(d.id)){u=d;break}return u?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:u,contentMetadata:s}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};Xt();var xA=class t{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 Dh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new c1(e.resumableTaskStore,this.storageController),this._coreProtocols=new cg,this._coreProtocols.register(new Ir);let r={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={["MessagesRead"]:new bb(r),["MessagesSubscribe"]:new xb(r),["MessagesSync"]:new Sb(r),["ProtocolsConfigure"]:new i1(r),["ProtocolsQuery"]:new o1(r),["RecordsCount"]:new a1(r),["RecordsDelete"]:new d1(r),["RecordsQuery"]:new u1(r),["RecordsRead"]:new l1(r),["RecordsSubscribe"]:new f1(r),["RecordsWrite"]:new p1(r)}}static async create(e){e.didResolver||(e.didResolver=new QK({didResolvers:[TK,VK,Mw,ZK],cache:new YK}),e.ownsResolver=!0),e.tenantGate??=new dg;let r=new t(e);return await r.open(),r}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,r,n={}){let s=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(s!==void 0)return s;let{dataStream:a,subscriptionHandler:o}=n,i=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[i].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:o})}async validateTenant(e){let r=await this.tenantGate.isActiveTenant(e);if(!r.isActiveTenant)return{status:{code:401,detail:r.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let r=e?.descriptor?.interface,n=e?.descriptor?.method;if(r===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${r}, method: ${n}`}};try{we.validateJsonSchema(e)}catch(s){return ut(s,400)}}};ht();Xt();hn();Cy();bi();w();function xde(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function Nn(t,e){return e?Promise.race([t,xde(e)]):t}Na();or();pa();T0();On();d0();t2();Ya();Hs();qE();Al();w();ey();w();import{Level as Sde}from"level";async function zi(t,e){return new Sde(t,{...e,keyEncoding:"utf8"})}var Da=class t{config;db;constructor(e,r){this.config={createLevelDatabase:zi,...e},this.db=r}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,r)=>{let n=()=>{this.db.open().then(e).catch(r)};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,r)=>{let n=()=>{this.db.close().then(e).catch(r)};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 t(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,r){r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal);try{return await Nn(this.db.get(String(e)),r?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,r){return!!await this.get(e,r)}async*keys(e){e?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),e?.signal);for await(let r of this.db.keys())e?.signal?.throwIfAborted(),yield r}async*iterator(e,r){r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal);for await(let n of this.db.iterator(e))r?.signal?.throwIfAborted(),yield n}async put(e,r,n){return n?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),n?.signal),Nn(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal),Nn(this.db.del(String(e)),r?.signal)}async isEmpty(e){for await(let r of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,r){return r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal),Nn(this.db.batch(e),r?.signal)}createPartitionOperation(e,r){return{...r,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Nn(n.db.compactRange?.(...r),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let r=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,r]}get root(){let e=this.db;for(let r=e.db;r&&r!==e;)e=r;return new t(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}};var Nf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:zi,...e},this.db=r??new Da({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let r=await this.db.partition(e);return new t({...this.config,location:""},r)}async put(e,r,n){return await this.db.put(String(e),r,n),qt.parse(e.toString())}async get(e,r){return await this.db.get(String(e),r)}async has(e,r){return this.db.has(String(e),r)}async delete(e,r){return this.db.delete(String(e),r)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,r){for await(let n of e)await this.put(n.cid,n.block,r),yield n.cid}async*getMany(e,r){for await(let n of e)yield{cid:n,block:await this.get(n,r)}}async*getAll(e){let r=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,s]of r)yield{cid:qt.decode(n),block:s}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}};w();Hd();w();var TP=Ln(To(),1);w();function Ede(t){return t[Symbol.asyncIterator]!=null}function kde(t){if(Ede(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var XK=kde;Gc();w();Ip();Io();var M9=Ln(To(),1);py();w();Xu();np();var e9=0,_de="identity",t9=Qo,Tde=t=>il(e9,t9(t)),r9={code:e9,name:_de,encode:t9,digest:Tde};w();Ip();var n9=Ln(To(),1);Gc();var Ide=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=F2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=qt.asCID(d[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}},next:{cid:h,name:f,path:l,toResolve:n}};d=d[f]}else throw(0,n9.default)(new Error(`No property named ${f} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}}}},s9=Ide;w();var i9=Ln(To(),1);np();Vc();w();function Ade(t,e,r,n){let s=BigInt(t.length),a=BigInt(e+s);return r>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(t=t.subarray(0,Number(n-e))),r>=e&&r<a&&(t=t.subarray(Number(r-e))),t)}var Uf=Ade;w();var Ow=Ln(To(),1),Rde=(t,e=0,r=t)=>{let n=BigInt(t),s=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=s+a),a>n&&(a=n),s<0n)throw(0,Ow.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,Ow.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,Ow.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,Ow.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:s,end:a}},Xh=Rde;var Dde=t=>{async function*e(r={}){let{start:n,end:s}=Xh(t.length,r.offset,r.length),a=Uf(t,0n,n,s);r.onProgress?.(new gn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Cde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,i9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=c0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Dde(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},o9=Cde;w();var a9=Ln(To(),1);Vc();var jde=t=>{async function*e(r={}){let{start:n,end:s}=Xh(t.length,r.offset,r.length),a=Uf(t,0n,n,s);r.onProgress?.(new gn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},$de=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,a9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=await o.get(t,i);return{entry:{type:"raw",name:e,path:r,cid:t,content:jde(c),depth:a,size:BigInt(c.length),node:c}}},c9=$de;w();Io();var Fw=Ln(To(),1);Yd();w();Io();FS();GS();var Mde=async function(t){return(await uv.encode(t)).slice(0,8).reverse()},Ode=async(t,e,r)=>{await Promise.all(t.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let s=parseInt(n.Name,16);e._putObjectAt(s,new Wa({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},d9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Bde=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},u9=async(t,e,r,n,s)=>{if(n==null){let d=pv({hashFn:Mde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await Ode(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=d9(a.pos),i=Bde(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=d9(n.lastBucket._posAtParent));let c=t.Links.find(d=>{if(d.Name==null)return!1;let l=d.Name.substring(0,2),f=d.Name.substring(2);return!(l!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await r.get(c.Hash,s);return t=Wc(u),u9(t,e,r,n,s)},l9=u9;w();w();w();function Nde(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var hP=Nde;function Ude(t){return t[Symbol.asyncIterator]!=null}function Lde(t,e){let r=0;if(Ude(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=hP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){await o&&(yield s);for(let c of n)await e(c,r++)&&(yield c)}();let i=e;return function*(){o===!0&&(yield s);for(let c of n)i(c,r++)&&(yield c)}()}var f9=Lde;w();function Kde(t){return t[Symbol.asyncIterator]!=null}function zde(t,e){let r=0;if(Kde(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=hP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,r++)}();let i=e;return function*(){yield o;for(let c of n)yield i(c,r++)}()}var em=zde;w();w();function qi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var mP=globalThis.CustomEvent??Event;async function*Lf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=qi(),i=qi(),c=!1,u,d=!1;s.addEventListener("task-complete",()=>{i.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(o=qi(),await o.promise),d)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,s.dispatchEvent(new mP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new mP("task-complete"))})}c=!0,s.dispatchEvent(new mP("task-complete"))}catch(p){u=p,s.dispatchEvent(new mP("task-complete"))}});function l(){return n?a[0]?.done:!!a.find(p=>p.done)}function*f(){for(;a.length>0&&a[0].done;){let p=a[0];if(a.shift(),p.ok)yield p.value;else throw d=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;l();)for(let p=0;p<a.length;p++)if(a[p].done){let m=a[p];if(a.splice(p,1),p--,m.ok)yield m.value;else throw d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(l()||(i=qi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}w();w();w();var yP=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}},tm=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yP(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 r=this.head;this.head=r.next=new yP(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var SA=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function gP(t={}){return qde(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function qde(t,e){e=e??{};let r=e.onEnd,n=new tm,s,a,o,i=qi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=v=>{a=null,n.push(v);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=qi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new tm,a!=null?a({error:y}):(n.push({error:y}),s)),l=y=>{if(o)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},f=y=>o?s:(o=!0,y!=null?d(y):u({done:!0})),h=()=>(n=new tm,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async y=>{let S=y?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let v,E;S!=null&&(v=new Promise((_,I)=>{E=()=>{I(new SA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,v])}finally{E!=null&&S!=null&&S?.removeEventListener("abort",E)}}},r==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(y){return m.end(y),r!=null&&(r(y),r=void 0),s},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},s}w();w();w();function Fde(t){return t.reason}async function p9(t,e,r){if(e==null)return t;let n=r?.translateError??Fde;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([t,new Promise((a,o)=>{s=()=>{o(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var EA=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=qi(),this.haveNext=qi()}[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=qi(),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,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){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=qi(),await p9(this.readNext.promise,r?.signal,r)}};function h9(){return new EA}function Gde(t){return t[Symbol.asyncIterator]!=null}async function Wde(t,e,r){try{await Promise.all(t.map(async n=>{for await(let s of n)await e.push(s,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Vde(t){let e=new AbortController,r=h9();Wde(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Hde(t){for(let e of t)yield*e}function Jde(...t){let e=[];for(let r of t)Gde(r)||e.push(r);return e.length===t.length?Hde(e):Vde(t)}var m9=Jde;function rm(t,...e){if(t==null)throw new Error("Empty pipeline");if(kA(t)){let n=t;t=()=>n.source}else if(g9(t)||y9(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&kA(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)kA(r[n])&&(r[n]=Yde(r[n]));return Zde(...r)}var Zde=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},y9=t=>t?.[Symbol.asyncIterator]!=null,g9=t=>t?.[Symbol.iterator]!=null,kA=t=>t==null?!1:t.sink!=null&&t.source!=null,Yde=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=gP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(y9(a))s=async function*(){yield*a,n.end()};else if(g9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return m9(n,s())}return t.source};Vc();var Qde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=c.offset??0,d=c.length??e.Links.length,l=e.Links.slice(u,d);c.onProgress?.(new gn("unixfs:exporter:walk:directory",{cid:t})),yield*rm(l,f=>em(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Lf(f,{ordered:!0}),f=>f9(f,h=>h!=null))}return i},w9=Qde;w();Io();var zf=Ln(To(),1);Yd();py();w();w();var TA=Ln(b9(),1);w();var Nw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},IA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},P9=t=>globalThis.DOMException===void 0?new IA(t):new DOMException(t),x9=t=>{let e=t.reason===void 0?P9("This operation was aborted."):t.reason;return e instanceof Error?e:P9(e)};function AA(t,e,r,n){let s,a=new Promise((o,i)=>{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(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&i(x9(c)),c.addEventListener("abort",()=>{i(x9(c))})}s=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(d){i(d)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new Nw(c);typeof t.cancel=="function"&&t.cancel(),i(u)},e),(async()=>{try{o(await t)}catch(c){i(c)}finally{n.customTimers.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{clearTimeout(s),s=void 0},a}w();w();function RA(t,e,r){let n=0,s=t.length;for(;s>0;){let a=Math.trunc(s/2),o=n+a;r(t[o],e)<=0?(n=++o,s-=a+1):s=a}return n}var Kf=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Id,DA=class{constructor(){Id.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Kf(this,Id,"f")[this.size-1].priority>=r.priority){Kf(this,Id,"f").push(n);return}let s=RA(Kf(this,Id,"f"),n,(a,o)=>o.priority-a.priority);Kf(this,Id,"f").splice(s,0,n)}dequeue(){let e=Kf(this,Id,"f").shift();return e?.run}filter(e){return Kf(this,Id,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Kf(this,Id,"f").length}};Id=new WeakMap;var S9=DA;var fn=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Ge=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},jn,Lw,Kw,Zu,EP,zw,vP,Ca,Uw,wo,bP,vo,qw,Ju,PP,E9,k9,I9,_9,T9,xP,CA,jA,kP,A9,SP,_P=class extends Error{},$A=class extends TA.default{constructor(e){var r,n,s,a;if(super(),jn.add(this),Lw.set(this,void 0),Kw.set(this,void 0),Zu.set(this,0),EP.set(this,void 0),zw.set(this,void 0),vP.set(this,0),Ca.set(this,void 0),Uw.set(this,void 0),wo.set(this,void 0),bP.set(this,void 0),vo.set(this,0),qw.set(this,void 0),Ju.set(this,void 0),PP.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:S9,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);fn(this,Lw,e.carryoverConcurrencyCount,"f"),fn(this,Kw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),fn(this,EP,e.intervalCap,"f"),fn(this,zw,e.interval,"f"),fn(this,wo,new e.queueClass,"f"),fn(this,bP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,fn(this,PP,e.throwOnTimeout===!0,"f"),fn(this,Ju,e.autoStart===!1,"f")}get concurrency(){return Ge(this,qw,"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})`);fn(this,qw,e,"f"),Ge(this,jn,"m",kP).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ge(this,PP,"f"),...r},new Promise((n,s)=>{Ge(this,wo,"f").enqueue(async()=>{var a,o,i;fn(this,vo,(o=Ge(this,vo,"f"),o++,o),"f"),fn(this,Zu,(i=Ge(this,Zu,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new _P("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=AA(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,Ge(this,jn,"m",A9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ge(this,jn,"m",I9).call(this)}},r),this.emit("add"),Ge(this,jn,"m",xP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ge(this,Ju,"f")?(fn(this,Ju,!1,"f"),Ge(this,jn,"m",kP).call(this),this):this}pause(){fn(this,Ju,!0,"f")}clear(){fn(this,wo,new(Ge(this,bP,"f")),"f")}async onEmpty(){Ge(this,wo,"f").size!==0&&await Ge(this,jn,"m",SP).call(this,"empty")}async onSizeLessThan(e){Ge(this,wo,"f").size<e||await Ge(this,jn,"m",SP).call(this,"next",()=>Ge(this,wo,"f").size<e)}async onIdle(){Ge(this,vo,"f")===0&&Ge(this,wo,"f").size===0||await Ge(this,jn,"m",SP).call(this,"idle")}get size(){return Ge(this,wo,"f").size}sizeBy(e){return Ge(this,wo,"f").filter(e).length}get pending(){return Ge(this,vo,"f")}get isPaused(){return Ge(this,Ju,"f")}};Lw=new WeakMap,Kw=new WeakMap,Zu=new WeakMap,EP=new WeakMap,zw=new WeakMap,vP=new WeakMap,Ca=new WeakMap,Uw=new WeakMap,wo=new WeakMap,bP=new WeakMap,vo=new WeakMap,qw=new WeakMap,Ju=new WeakMap,PP=new WeakMap,jn=new WeakSet,E9=function(){return Ge(this,Kw,"f")||Ge(this,Zu,"f")<Ge(this,EP,"f")},k9=function(){return Ge(this,vo,"f")<Ge(this,qw,"f")},I9=function(){var e;fn(this,vo,(e=Ge(this,vo,"f"),e--,e),"f"),Ge(this,jn,"m",xP).call(this),this.emit("next")},_9=function(){Ge(this,jn,"m",jA).call(this),Ge(this,jn,"m",CA).call(this),fn(this,Uw,void 0,"f")},T9=function(){let e=Date.now();if(Ge(this,Ca,"f")===void 0){let r=Ge(this,vP,"f")-e;if(r<0)fn(this,Zu,Ge(this,Lw,"f")?Ge(this,vo,"f"):0,"f");else return Ge(this,Uw,"f")===void 0&&fn(this,Uw,setTimeout(()=>{Ge(this,jn,"m",_9).call(this)},r),"f"),!0}return!1},xP=function(){if(Ge(this,wo,"f").size===0)return Ge(this,Ca,"f")&&clearInterval(Ge(this,Ca,"f")),fn(this,Ca,void 0,"f"),this.emit("empty"),Ge(this,vo,"f")===0&&this.emit("idle"),!1;if(!Ge(this,Ju,"f")){let e=!Ge(this,jn,"a",T9);if(Ge(this,jn,"a",E9)&&Ge(this,jn,"a",k9)){let r=Ge(this,wo,"f").dequeue();return r?(this.emit("active"),r(),e&&Ge(this,jn,"m",CA).call(this),!0):!1}}return!1},CA=function(){Ge(this,Kw,"f")||Ge(this,Ca,"f")!==void 0||(fn(this,Ca,setInterval(()=>{Ge(this,jn,"m",jA).call(this)},Ge(this,zw,"f")),"f"),fn(this,vP,Date.now()+Ge(this,zw,"f"),"f"))},jA=function(){Ge(this,Zu,"f")===0&&Ge(this,vo,"f")===0&&Ge(this,Ca,"f")&&(clearInterval(Ge(this,Ca,"f")),fn(this,Ca,void 0,"f")),fn(this,Zu,Ge(this,Lw,"f")?Ge(this,vo,"f"):0,"f"),Ge(this,jn,"m",kP).call(this)},kP=function(){for(;Ge(this,jn,"m",xP).call(this););},A9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new _P("The task was aborted."))},{once:!0})})},SP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var R9=$A;Vc();async function D9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Uf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,zf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=ns.unmarshal(e.Data)}catch(u){throw(0,zf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Uf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,zf.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let d=e.Links[u],l=n,f=l+i.blockSizes[u];if((s>=l&&s<f||a>=l&&a<=f||s<l&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await rm(c,u=>em(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Lf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case iy:h=Wc(l);break;case Qd:h=l;break;default:r.end((0,zf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new R9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new gn("unixfs:exporter:walk:file",{cid:d.Hash})),await D9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var tue=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:d,end:l}=Xh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=gP();c.onProgress?.(new gn("unixfs:exporter:walk:file",{cid:t})),D9(o,e,p,0n,d,l,c).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,zf.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(),c.onProgress?.(new gn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,zf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},MA=tue;w();Io();Vc();var rue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new gn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),C9(e,n,s,a,o,c)}return i};async function*C9(t,e,r,n,s,a){let o=t.Links,i=rm(o,c=>em(c,u=>async()=>{let d=u.Name!=null?u.Name.substring(2):null;if(d!=null&&d!==""){let l=await r(u.Hash,d,`${e}/${d}`,[],n+1,s,a);return{entries:l.entry==null?[]:[l.entry]}}else{let l=await s.get(u.Hash,a);return t=Wc(l),a.onProgress?.(new gn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:C9(t,e,r,n,s,a)}}}),c=>Lf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var j9=rue;var nue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,sue={raw:MA,file:MA,directory:w9,"hamt-sharded-directory":j9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},iue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Wc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,Fw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=ns.unmarshal(u.Data)}catch(h){throw(0,Fw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await l9(u,n[0],o):h=nue(u,n[0]),h==null)throw(0,Fw.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;l={cid:h,toResolve:n,name:p??"",path:m}}let f=sue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,Fw.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}},$9=iue;var oue={[iy]:$9,[Qd]:c9,[Vd]:s9,[r9.code]:o9},O9=async(t,e,r,n,s,a,o)=>{let i=oue[t.code];if(i==null)throw(0,M9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,O9,s,a,o)},B9=O9;var aue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),cue=t=>{if(t instanceof Uint8Array)return{cid:qt.decode(t),toResolve:[]};let e=qt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=aue(t);return{cid:qt.parse(r[0]),toResolve:r.slice(1)}}throw(0,TP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*due(t,e,r={}){let{cid:n,toResolve:s}=cue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await B9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,TP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function N9(t,e,r={}){let n=await XK(due(t,e,r));if(n==null)throw(0,TP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}HS();var OA=new TextEncoder,IP=new TextDecoder,BA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:zi,...e},this.blockstore=new Nf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,r,n,s){let a=await this.getRefsPartition(e,r),o=await a.get(n);if(o){await s.cancel();let{dataSize:l}=JSON.parse(IP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(IP.decode(c)):{count:0,dataSize:0},d;if(u.count>0)await s.cancel(),d=u.dataSize;else{let l=await this.getBlocksPartition(n),f=yy([{content:rs.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,OA.encode(JSON.stringify({dataSize:d}))),await i.put(n,OA.encode(JSON.stringify({count:u.count+1,dataSize:d}))),{dataSize:d}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(IP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await N9(n,i)).content(),l=new ReadableStream({async pull(f){let h=await d.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:o,dataStream:l}}async delete(e,r,n){let s=await this.getRefsPartition(e,r);if(!await s.get(n))return;await s.delete(n);let o=await this.getRefcountsPartition(),i=await o.get(n);if(!i)return;let c=JSON.parse(IP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,OA.encode(JSON.stringify({count:u,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,r){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(r)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}};w();ms();ZS();Ya();w();wa();Ya();var AP="";async function U9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function L9(t,e,r,n,s){let a=[];for(let u of r.properties){let d=e[u];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[r.sortProperty];if(o===void 0||Array.isArray(o))return;let i=a.join(AP),c=n(o);return i+AP+c+s+t}function K9(t,e,r){let n=[];for(let s of e.properties){let a=t[s];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join(AP)+AP}function z9(t,e,r,n,s,a){let o=L9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return F9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function q9(t,e,r,n,s,a,o){let i=L9(r,n,s,a,o);if(i!==void 0)return F9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function F9(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function NA(t,e,r){let n,s=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let i of a.properties){let c=t[i];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>s&&(n=a,s=a.properties.length)}return n}async function G9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=K9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await U9(t,e,s),p={};if(d!==void 0){let E=a(d.value),_=f+E+o+d.messageCid;u===1?(p.gt=_,p.lt=f+"\xFF"):(p.lt=_,p.gt=f,p.reverse=!0)}else u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let v=[];for await(let[E,_]of h.iterator(p,c)){if(l!==void 0&&v.length===l)break;let I=JSON.parse(_);S&&!Gt.matchFilter(I.indexes,y)||v.push(I)}return v}async function W9(t,e,r,n,s,a,o){let i=K9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await U9(t,e,n),u=new Set(n.properties),d=!1,l={};for(let p in r)u.has(p)||(l[p]=r[p],d=!0);let f={gt:i,lt:i+"\xFF"},h=0;if(d)for await(let[p,m]of c.iterator(f,o)){let y=JSON.parse(m);Gt.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ht();wa();var V9="index",nm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:zi,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Da({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,r,n,s){if(Il(n))throw new ne("IndexMissingIndexableProperty","Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},o=[];for(let d in n){let l=n[d];if(Array.isArray(l))for(let f of l){let h=this.createPutIndexedItemOperation(e,a,d,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,d,l);o.push(f)}}for(let d of this._compoundIndexes){let l=z9(this.db,e,a,d,t.encodeValue,t.delimiter);l!==void 0&&o.push(l)}let i=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});o.push(i);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,s)}async delete(e,r,n){let s=[],a=await this.getIndexes(e,r);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});s.push(o);for(let u in a){let d=a[u];if(Array.isArray(d))for(let l of d){let f=this.createDeleteIndexedItemOperation(e,r,u,l);s.push(f)}else{let l=this.createDeleteIndexedItemOperation(e,r,u,d);s.push(l)}}for(let u of this._compoundIndexes){let d=q9(this.db,e,r,a,u,t.encodeValue,t.delimiter);d!==void 0&&s.push(d)}let i=await Promise.all(s);await(await this.db.partition(e)).batch(i,n)}async createPutIndexedItemOperation(e,r,n,s){let{messageCid:a}=r,o=t.keySegmentJoin(t.encodeValue(s),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(s),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let s=await this.db.partition(e),a=t.getIndexPartitionName(r);return s.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(V9,r)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,r){let n=t.getIndexPartitionName(r);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(V9)}async query(e,r,n,s){if(r.length===1&&!Il(r[0])){let a=NA(r[0],n,this._compoundIndexes);if(a!==void 0)return G9(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),s)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,s):this.queryWithIteratorPaging(e,r,n,s)}async count(e,r,n,s){if(r.length===1&&!Il(r[0])){let o=NA(r[0],{...n},this._compoundIndexes);if(o!==void 0)return W9(this.db,e,r[0],o,t.encodeValue,this.query.bind(this),s)}return(await this.query(e,r,{...n},s)).length}async queryWithIteratorPaging(e,r,n,s){let{cursor:a,limit:o}=n,i=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let u of this.getIndexIterator(e,i,n,s)){if(o!==void 0&&o===c.length)break;let{indexes:d}=u;Gt.matchAnyFilter(d,r)&&c.push(u)}return c}async*getIndexIterator(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i}=n,c={gt:r};o===-1&&(c.reverse=!0,i!==void 0&&(c.lt=r,delete c.gt));let u=await this.getIndexPartition(e,a);for await(let[d,l]of u.iterator(c,s)){let{indexes:f,messageCid:h}=JSON.parse(l);yield{indexes:f,messageCid:h}}}createStartingKeyFromCursor(e){let{messageCid:r,value:n}=e;return t.keySegmentJoin(t.encodeValue(n),r)}static createCursorFromLastArrayItem(e,r){if(e.length>0)return this.createCursorFromItem(e.at(-1),r)}static createCursorFromItem(e,r){let{messageCid:n,indexes:s}=e,a=s[r];if(a===void 0)throw new ne("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ne("IndexInvalidCursorValueType",`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i,limit:c}=n,u=i?this.createStartingKeyFromCursor(i):void 0,d=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,d,s)}catch(p){if(p.code==="IndexInvalidSortPropertyInMemory")return[]}let l=[...d.values()].sort((p,m)=>this.sortItems(p,m,a,o)),f=u!==void 0?this.findCursorStartingIndex(l,o,a,u):0;if(f<0)return[];let h=c!==void 0?f+c:void 0;return l.slice(f,h)}async executeSingleFilterQuery(e,r,n,s,a){let o=c=>{for(let u of c)if(!(s.has(u.messageCid)||!Gt.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new ne("IndexInvalidSortPropertyInMemory",`invalid sort property ${n}`);s.set(u.messageCid,u)}};if(Il(r)){let c=await this.getAllItems(e,n);o(c);return}let i=$v.reduceFilter(r);for(let c in i){let u=i[c];if(Gt.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Gt.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Gt.isRangeFilter(u)){let d=await this.filterRangeMatches(e,c,u,a);o(d)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),s=[];for await(let[a,o]of n.iterator())s.push(JSON.parse(o));return s}async filterExactMatches(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(n)),o={gt:a},i=await this.getIndexPartition(e,r),c=[];for await(let[u,d]of i.iterator(o,s)){if(!u.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,r,n,s){let a={};for(let c in n){let u=c,d=t.encodeValue(n[u]);u==="lte"?a[u]=d+"\xFF":a[u]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],i=await this.getIndexPartition(e,r);for await(let[c,u]of i.iterator(a,s))"gt"in n&&this.extractIndexValueFromKey(c)===t.encodeValue(n.gt)||o.push(JSON.parse(u));return o}sortItems(e,r,n,s){let a=e.indexes[n],o=r.indexes[n],i=t.encodeValue(a)+e.messageCid,c=t.encodeValue(o)+r.messageCid;return s===1?gy(i,c):gy(c,i)}findCursorStartingIndex(e,r,n,s){let a=c=>{let{messageCid:u,indexes:d}=c,l=d[n],f=t.keySegmentJoin(t.encodeValue(l),u);return r===1?f>s:f<s},o=0,i=e.length;for(;o<i;){let c=o+i>>>1;a(e[c])?i=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,r){let s=await(await this.getIndexesLookupPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}extractIndexValueFromKey(e){let[r]=e.split(t.delimiter);return r}static delimiter="\0";static keySegmentJoin(...e){return e.join(t.delimiter)}static encodeNumberValue(e){let r=Number.MAX_SAFE_INTEGER,n="!",s=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?r:0;return a+String(e+o).padStart(s,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,r){for(let n of e)if(!t.isFilterConcise(n,r))return!1;return!0}static isFilterConcise(e,r){return e.recordId!==void 0?!0:r.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}};w();w();ey();Z2();function RP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*uue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=qt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*UA(n,s))}else{let r=qt.asCID(e);r?yield[t.join("/"),r]:yield*UA(e,t)}}function*UA(t,e){if(t==null||t instanceof Uint8Array)return;let r=qt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*uue(a,s)}}function*lue(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!qt.asCID(n)&&(yield*LA(n,s))}else yield*LA(e,t)}function*LA(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let s=[...e,r];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!qt.asCID(n)&&(yield*lue(s,n))}}function fue(t,e){let r=t;for(let[n,s]of e.entries()){if(r=r[s],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=qt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var DP=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:RP(),bytes:RP(),value:RP(),asBlock:RP()})}links(){return UA(this.value,[])}tree(){return LA(this.value,[])}get(e="/"){return fue(this.value,e.split("/").filter(Boolean))}};async function H9({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),s=await r.digest(n),a=qt.create(1,e.code,s);return new DP({value:t,bytes:n,cid:a})}async function J9({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),s=await r.digest(t),a=qt.create(1,e.code,s);return new DP({value:n,bytes:t,cid:a})}Ip();Hc();Gc();or();Dd();Ya();var hue=[{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"}],KA=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:zi,...e},this.blockstore=new Nf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new nm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??hue})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,r,n){n?.signal?.throwIfAborted();let s=await Nn(this.blockstore.partition(e),n?.signal),a=qt.parse(r),o=await s.get(a,n);return o?(await Nn(J9({bytes:o,codec:Fc,hasher:Sn}),n?.signal)).value:void 0}async query(e,r,n,s,a){a?.signal?.throwIfAborted();let o=t.buildQueryOptions(n,s),i=await this.index.query(e,r,o,a),c;s?.limit!==void 0&&s.limit<i.length&&(i.splice(-1),c=nm.createCursorFromLastArrayItem(i,o.sortProperty));let u=[];for(let d=0;d<i.length;d++){let{messageCid:l}=i[d],f=await this.get(e,l,a);f&&u.push(f)}return{messages:u,cursor:c}}async count(e,r,n,s){s?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,s)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:s}=r,{dateCreated:a,datePublished:o,messageTimestamp:i}=e,c=1,u="messageTimestamp";return a!==void 0?u="dateCreated":o!==void 0?u="datePublished":i!==void 0&&(u="messageTimestamp"),e[u]!==void 0&&(c=e[u]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:u,limit:n,cursor:s}}async delete(e,r,n){n?.signal?.throwIfAborted();let s=await Nn(this.blockstore.partition(e),n?.signal),a=qt.parse(r);await s.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,s){s?.signal?.throwIfAborted();let a=await Nn(this.blockstore.partition(e),s?.signal),o=await Nn(H9({value:r,codec:Fc,hasher:Sn}),s?.signal),i=Dr.parseCid(await we.getCid(r));await a.put(i,o.bytes,s);let c=i.toString();await this.index.put(e,c,n,s)}async clear(){await this.blockstore.clear(),await this.index.clear()}};w();Hc();var zA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:zi,...e},this.db=new Da({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,r){let n=await Dr.computeCid(e),s={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(s)),s}async grab(e){let r=[];for await(let[n,s]of this.db.iterator()){let a=JSON.parse(s);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+t.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),r.push(a)),r.length>=e)break}return r}async read(e){let r=await this.db.get(e);if(r)return JSON.parse(r)}async extend(e,r){let n=await this.db.get(e);if(n){let s=JSON.parse(n);s.timeout=Date.now()+r*1e3,await this.db.put(s.id,JSON.stringify(s))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}};w();w();function Z9(t){return{all:t=t||new Map,on:function(e,r){var n=t.get(e);n?n.push(r):t.set(e,[r])},off:function(e,r){var n=t.get(e);n&&(r?n.splice(n.indexOf(r)>>>0,1):t.set(e,[]))},emit:function(e,r){var n=t.get(e);n&&n.slice().map(function(s){s(r)}),(n=t.get("*"))&&n.slice().map(function(s){s(e,r)})}}}wa();ht();var Y9="events",qA=class t{emitter=Z9();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 r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,r,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(r),messageCid:n}}async validateCursor(e,r){let n=await this.getStreamId(e),s;if(r.streamId!==n)s="stream_mismatch";else if(r.epoch!==this.epoch)s="epoch_mismatch";else{let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let u=c.keys().next().value;if(t.parsePosition(r.position)<u-1)s="token_too_old";else return}else return}let a=await this.getReplayBounds(e),o={requested:r,oldestAvailable:a?.oldest??r,latestAvailable:a?.latest??r,reason:s},i=new ne("EventLogProgressGap",`progress token gap: ${s}`);throw i.gapInfo=o,i}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,r,n,s){if(!this.isOpen){this.errorHandler(new ne("EventLogNotOpenError","a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let i=this.tenantLogs.get(e);if(i===void 0&&(i=new Map,this.tenantLogs.set(e,i)),i.set(o,{event:r,indexes:n,messageCid:s}),i.size>this.maxEventsPerTenant){let u=i.size-this.maxEventsPerTenant,d=0;for(let l of i.keys()){if(d>=u)break;i.delete(l),d++}}let c=`${e}_${Y9}`;return this.emitter.emit(c,{tenant:e,event:r,indexes:n,seq:o}),this.buildToken(e,o,s)}async read(e,r={}){let{cursor:n,limit:s,filters:a}=r;n!==void 0&&await this.validateCursor(e,n);let o=n!==void 0?t.parsePosition(n.position):void 0,i=this.tenantLogs.get(e);if(i===void 0||i.size===0)return{events:[],cursor:n};let c=[],u=s??Number.MAX_SAFE_INTEGER;for(let[d,l]of i)if(!(o!==void 0&&d<=o)&&!(a!==void 0&&a.length>0&&!Gt.matchAnyFilter(l.indexes,a))&&(c.push({seq:d,event:l.event,indexes:l.indexes}),c.length>=u))break;if(c.length>0){let d=c[c.length-1],l=i.get(d.seq),f=await this.buildToken(e,d.seq,l.messageCid);return{events:c,cursor:f}}return{events:c,cursor:n}}static parsePosition(e){try{let r=BigInt(e);if(r<0n)throw new ne("EventLogNotOpenError",`invalid cursor position: '${e}'`);return Number(r)}catch(r){throw r instanceof ne?r:new ne("EventLogNotOpenError",`invalid cursor position: '${e}'`)}}async subscribe(e,r,n,s){let a=`${e}_${Y9}`,{cursor:o,filters:i}=s??{},c=async d=>{let h=this.tenantLogs.get(e)?.get(d.seq)?.messageCid??"";return this.buildToken(e,d.seq,h)};if(o!==void 0){await this.validateCursor(e,o);let d=t.parsePosition(o.position),l=[],f=!1,h=S=>{i!==void 0&&i.length>0&&!Gt.matchAnyFilter(S.indexes,i)||(f?c(S).then(v=>{n({type:"event",cursor:v,event:S.event})}):l.push({event:S.event,seq:S.seq}))};this.emitter.on(a,h);let p=await this.read(e,{cursor:o,filters:i}),m=p.cursor??o,y=p.cursor!==void 0?t.parsePosition(p.cursor.position):d;for(let S of p.events){let E=this.tenantLogs.get(e)?.get(S.seq),_=await this.buildToken(e,S.seq,E?.messageCid??"");n({type:"event",cursor:_,event:S.event})}f=!0;for(let S of l)if(S.seq>y){let E=this.tenantLogs.get(e)?.get(S.seq),_=await this.buildToken(e,S.seq,E?.messageCid??"");n({type:"event",cursor:_,event:S.event})}return n({type:"eose",cursor:m}),{id:r,close:async()=>{this.emitter.off(a,h)}}}let u=d=>{i!==void 0&&i.length>0&&!Gt.matchAnyFilter(d.indexes,i)||c(d).then(l=>{n({type:"event",cursor:l,event:d.event})})};return this.emitter.on(a,u),{id:r,close:async()=>{this.emitter.off(a,u)}}}async getReplayBounds(e){let r=this.tenantLogs.get(e);if(r===void 0||r.size===0)return;let n=[...r.keys()],s=n[0],a=n[n.length-1],o=r.get(s),i=r.get(a),c=await this.buildToken(e,s,o.messageCid),u=await this.buildToken(e,a,i.messageCid);return{oldest:c,latest:u}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let s of n.keys())if(s<r)n.delete(s);else break;else for(let[s,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(s)}};w();bu();w();bu();var Gw=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 r=Jn(e),n=await this.nodesPartition.get(r);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,r){this.ensureInitialized();let n=Jn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Jn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return tf(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Jn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Jn(e.leftHash),rightHash:Jn(e.rightHash)}:{type:"leaf",keyHash:Jn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:tf(e.leftHash),rightHash:tf(e.rightHash)}:{type:"leaf",keyHash:tf(e.keyHash),valueCid:e.valueCid}}};w();bu();var Ww=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await hh()}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 r=await ef(e),n=await lg(r,e),s={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,s);let a=await this.getRoot(),o=await this.insertAtNode(a,r,n,s,0);return await this.store.setRoot(o),o}async delete(e){let r=await ef(e),n=await this.getRoot(),s=await this.deleteAtNode(n,r,0);return await this.store.setRoot(s),s}async has(e){let r=await ef(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await ef(e),n=await this.getRoot();return this.generateProof(n,r,0)}async getSubtreeHash(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(rn(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let s=await this.store.getNode(r);if(s===void 0||s.type==="leaf")return s!==void 0&&s.type==="leaf"?this.computeSubtreeHashForLeaf(s,n,e):this.defaultHashes[e.length];let a=s;e[n]?r=a.rightHash:r=a.leftHash}return r}async getLeaves(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(rn(r,this.defaultHashes[n]))return[];let s=await this.store.getNode(r);if(s===void 0)return[];if(s.type==="leaf")return this.leafMatchesPrefix(s.keyHash,e)?[s.valueCid]:[];let a=s;e[n]?r=a.rightHash:r=a.leftHash}return this.collectLeaves(r,e.length)}async diff(e){let r=await this.getRoot(),n=await e.getRoot();if(rn(r,n))return{onlyLocal:[],onlyRemote:[]};let s=[],a=[];return await this.diffAtNode(r,n,0,this,e,s,a),{onlyLocal:s,onlyRemote:a}}async insertAtNode(e,r,n,s,a){if(a>=Pi||rn(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return rn(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=uo(r,a),u,d;c?(u=i.leftHash,d=await this.insertAtNode(i.rightHash,r,n,s,a+1)):(u=await this.insertAtNode(i.leftHash,r,n,s,a+1),d=i.rightHash);let l=await vu(u,d);if(!rn(l,e)){let f={type:"internal",leftHash:u,rightHash:d};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async splitLeaves(e,r,n,s,a){let o=a;for(;o<Pi&&uo(e.keyHash,o)===uo(n.keyHash,o);)o++;if(o>=Pi)return s;let i=uo(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await vu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=uo(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await vu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=Pi)return this.defaultHashes[Pi];if(rn(e,this.defaultHashes[n]))return e;let s=await this.store.getNode(e);if(s===void 0)return this.defaultHashes[n];if(s.type==="leaf")return rn(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=uo(r,n),i,c;if(o?(i=a.leftHash,c=await this.deleteAtNode(a.rightHash,r,n+1)):(i=await this.deleteAtNode(a.leftHash,r,n+1),c=a.rightHash),rn(i,this.defaultHashes[n+1])&&rn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=rn(i,this.defaultHashes[n+1]),d=rn(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let l=await vu(i,c);if(!rn(l,e)){let f={type:"internal",leftHash:i,rightHash:c};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async existsAtNode(e,r,n){if(n>=Pi||rn(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return rn(s.keyHash,r);let a=s;return uo(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=Pi)return{siblings:[],leafNode:void 0,depth:n};if(rn(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let s=await this.store.getNode(e);if(s===void 0)return{siblings:[],leafNode:void 0,depth:n};if(s.type==="leaf")return{siblings:[],leafNode:s,depth:n};let a=s,o=uo(r,n),i,c;o?(i=a.rightHash,c=a.leftHash):(i=a.leftHash,c=a.rightHash);let u=await this.generateProof(i,r,n+1);return u.siblings.unshift(c),u}async computeSubtreeHashForLeaf(e,r,n){for(let s=r;s<n.length;s++)if(uo(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await lg(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(uo(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=Pi||rn(e,this.defaultHashes[r]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let s=n,a=await this.collectLeaves(s.leftHash,r+1),o=await this.collectLeaves(s.rightHash,r+1);return[...a,...o]}async diffAtNode(e,r,n,s,a,o,i){if(rn(e,r)||n>=Pi)return;let c=rn(e,this.defaultHashes[n]),u=rn(r,this.defaultHashes[n]);if(c&&!u){let f=await a.collectLeaves(r,n);i.push(...f);return}if(!c&&u){let f=await s.collectLeaves(e,n);o.push(...f);return}let d=await s.store.getNode(e),l=await a.store.getNode(r);if(d?.type==="leaf"&&l?.type==="leaf"){rn(d.keyHash,l.keyHash)?d.valueCid!==l.valueCid&&(o.push(d.valueCid),i.push(l.valueCid)):(o.push(d.valueCid),i.push(l.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(r,n),h=d.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&i.push(m);return}if(l?.type==="leaf"){let f=await s.collectLeaves(e,n),h=l.valueCid;new Set(f).has(h)||i.push(h);for(let m of f)m!==h&&o.push(m);return}if(d?.type==="internal"&&l?.type==="internal"){await this.diffAtNode(d.leftHash,l.leftHash,n+1,s,a,o,i),await this.diffAtNode(d.rightHash,l.rightHash,n+1,s,a,o,i);return}if(d===void 0){let f=await a.collectLeaves(r,n);i.push(...f)}if(l===void 0){let f=await s.collectLeaves(e,n);o.push(...f)}}};var FA=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:zi,...e}}async open(){this.db=new Da({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await hh()}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,r,n){await(await this.getGlobalTree(e)).insert(r);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(r),await this.storeIndexes(e,r,n)}async delete(e,r){let n=await this.getGlobalTree(e);for(let s of r){let a=await this.getStoredIndexes(e,s);if(await n.delete(s),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(s)}await this.deleteStoredIndexes(e,s)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,r){return(await this.getProtocolTree(e,r)).getRoot()}async getSubtreeHash(e,r){return(await this.getGlobalTree(e)).getSubtreeHash(r)}async getProtocolSubtreeHash(e,r,n){return(await this.getProtocolTree(e,r)).getSubtreeHash(n)}async getLeaves(e,r){return(await this.getGlobalTree(e)).getLeaves(r)}async getProtocolLeaves(e,r,n){return(await this.getProtocolTree(e,r)).getLeaves(n)}getGlobalTree(e){let r=this.globalTrees.get(e);return r!==void 0||(r=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,r)),r}getProtocolTree(e,r){let n=`${e}\0${r}`,s=this.protocolTrees.get(n);return s!==void 0||(s=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,s)),s}async createTree(e,r){let n=e;for(let o of r)n=await n.partition(o);let s=new Gw(n),a=new Ww(s);return await a.initialize(),a}async storeIndexes(e,r,n){let s=await this.getMetaPartition(e),a={protocol:n.protocol};await s.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let s=await(await this.getMetaPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}};w();bu();var GA=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(Jn(e))}async putNode(e,r){this.nodes.set(Jn(e),r)}async deleteNode(e){this.nodes.delete(Jn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};bu();w();Ip();Gc();Hd();YP();hn();Na();T0();On();bi();ms();d0();Dd();Hs();Lp();Cy();Xt();zp();var mue={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},WA=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),s=e?.keyId??`${r}#${n}`,a=e?.keyPair??await Oa.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await vn.generateKey();o={publicJwk:await vn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ld({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await pd.create({definition:mue,signer:vt.createSigner(r)}),s=await e.processMessage(r.did,n.message);if(s.status.code!==202)throw new Error(`Failed to install default test protocol: ${s.status.code} ${s.status.detail}`)}static async generateProtocolsConfigure(e){let r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let i="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[i]={schema:"test-object",dataFormats:["text/plain"]},n.structure[i]={}}let s=vt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await pd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Ft(s);let a=await mf.create(s);return{author:r,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let r=e?.author??await t.generatePersona(),n=e?.grantedTo??await t.generatePersona(),s=e?.dateExpires??yt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:"Messages",method:"Read"},o=vt.createSigner(r),i=n.did,c={signer:o,grantedTo:i,dateExpires:s,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},u=await Ir.createGrant(c);return{dataStream:rs.fromBytes(u.permissionGrantBytes),recordsWrite:u.recordsWrite,dataBytes:u.permissionGrantBytes,message:u.recordsWrite.message,dataEncodedMessage:u.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s=vt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=rs.fromBytes(i));let u={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${t.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:i,dataCid:a,dataSize:o,signer:n,attestationSigners:s,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await xt.create(u),l=d.message;return{author:r,message:l,dataCid:a,dataSize:o,dataBytes:i,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:s,protocolDefinition:a,protocolPath:o,protocolParentContextId:i,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:u}=e,d=t.randomBytes(12),l=t.randomBytes(32),{ciphertext:f,tag:h}=await ga.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:v}=await t.generateRecordsWrite({author:n,recipient:s,protocol:a.protocol,protocolPath:o,parentContextId:i,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:l,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let $ of p)_=_[$];let I=_.$encryption?.publicKeyJwk,N={publicKeyId:_.$encryption?.rootKeyId,publicKey:I,derivationScheme:"protocolPath"};E.keyEncryptionInputs.push(N)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(i===void 0){let I={rootKeyId:n.keyId,derivationScheme:"protocolContext",derivedPrivateKey:n.encryptionKeyPair.privateJwk},R=await xt.getEntryId(n.did,y.descriptor),N=_e.constructKeyDerivationPathUsingProtocolContextScheme(R),$=await Ja.derivePublicKey(I,N);_={publicKeyId:n.keyId,publicKey:$,derivationScheme:"protocolContext"}}else{if(c===void 0||u===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:u,derivationScheme:"protocolContext"}}E.keyEncryptionInputs.push(_)}return await v.encryptSymmetricEncryptionKey(E),await v.sign({signer:vt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:v,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=yt.getCurrentTimestamp(),s=!(e.published??r.descriptor.published),a=e.datePublished??(s?n:void 0),o=e.data??t.randomBytes(32),i=rs.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:vt.createSigner(e.author)},u=await xt.createFrom(c);return{message:u.message,recordsWrite:u,dataBytes:o,dataStream:i}}static async generateRecordsQuery(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Ft(a);let i=(await Zl.create(a)).message;return{author:r,message:i}}static async generateRecordsSubscribe(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Ft(a);let i=(await yf.create(a)).message;return{author:r,message:i}}static async generateRecordsCount(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};Ft(a);let i=(await Jl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await hd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:vt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Ft(s);let a=await Ql.create(s),o=a.message;return{author:r,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),s={signer:vt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Yl.create(s);return{author:r,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:t.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await pm.generateKeyPair(),r=await pm.sign(t.randomBytes(32),e.privateJwk);return Te.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let s=0;s<e;s++)n+=r.charAt(Math.floor(Math.random()*r.length));return n}static randomBytes(e){let r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=Math.floor(Math.random()*256);return r}static async randomCborSha256Cid(){let e=t.randomBytes(32),r=await Sn.digest(e);return(await qt.createV1(Vd,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:s,hour:a,minute:o,second:i,millisecond:c,microsecond:u}=e||{};return yt.createTimestamp({year:r||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:s||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:i||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:u||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 Mw.create(),r=await Mw.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await vn.generateKey(),c={publicJwk:await vn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ld({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};w();Hs();var VA=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let s=Date.now();for(;;)try{return await e()}catch{if(Date.now()-s>=n)throw new Error("Operation timed out");await yt.sleep(r)}}};export{dg as AllowAllTenantGate,Nf as BlockstoreLevel,Dr as Cid,LE as ContentEncryptionAlgorithm,cg as CoreProtocolRegistry,BA as DataStoreLevel,rs as DataStream,Mp as DateSort,xA as Dwn,jo as DwnConstant,ne as DwnError,pt as DwnErrorCode,Qt as DwnInterfaceName,cr as DwnMethodName,Te as Encoder,ga as Encryption,qA as EventEmitterEventLog,Ja as HdKey,nm as IndexLevel,vt as Jws,g3 as KeyAgreementAlgorithm,Kp as KeyDerivationScheme,Da as LevelWrapper,we as Message,KA as MessageStoreLevel,Yl as MessagesRead,Ql as MessagesSubscribe,fg as MessagesSync,KE as PERMISSIONS_REVOCATION_PATH,v3 as PermissionConditionPublication,Xr as PermissionGrant,ug as PermissionRequest,Ir as PermissionsProtocol,VA as Poller,Ld as PrivateKeySigner,dm as ProtocolRecordLimitStrategy,sI as Protocols,pd as ProtocolsConfigure,mf as ProtocolsQuery,_e as Records,Jl as RecordsCount,hd as RecordsDelete,Zl as RecordsQuery,Vg as RecordsRead,yf as RecordsSubscribe,xt as RecordsWrite,zA as ResumableTaskStoreLevel,Gw as SMTStoreLevel,GA as SMTStoreMemory,Pi as SMT_DEPTH,Oa as Secp256k1,Ud as Secp256r1,Za as SortDirection,Ww as SparseMerkleTree,FA as StateIndexLevel,WA as TestDataGenerator,yt as Time,s_ as ZERO_HASH,dn as authenticate,zi as createLevelDatabase,Nn as executeUnlessAborted,uo as getBit,gO as getDefaultHashes,fd as getRuleSetAtPath,vu as hashChildren,rn as hashEquals,ef as hashKey,lg as hashLeaf,Jn as hashToHex,tf as hexToHash,hh as initDefaultHashes,hf as isCrossProtocolRef,Ni as parseCrossProtocolRef};
10
+ deps: ${r}}`};var Kee={keyword:"dependencies",type:"object",schemaType:"object",error:hc.error,code(t){let[e,r]=zee(t);uB(t,e),lB(t,r)}};function zee({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function uB(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let o in e){let i=e[o];if(i.length===0)continue;let c=(0,Kg.propertyInData)(r,n,o,s.opts.ownProperties);t.setParams({property:o,depsCount:i.length,deps:i.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of i)(0,Kg.checkReportMissingProp)(t,u)}):(r.if((0,xT._)`${c} && (${(0,Kg.checkMissingProp)(t,i,a)})`),(0,Kg.reportMissingProp)(t,a),r.else())}}hc.validatePropertyDeps=uB;function lB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Lee.alwaysValidSchema)(a,e[i])||(r.if((0,Kg.propertyInData)(r,n,i,a.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:i},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}hc.validateSchemaDeps=lB;hc.default=Kee});var pB=Ee(ST=>{"use strict";w();Object.defineProperty(ST,"__esModule",{value:!0});var fB=_t(),qee=Lt(),Fee={message:"property name must be valid",params:({params:t})=>(0,fB._)`{propertyName: ${t.propertyName}}`},Gee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Fee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,qee.alwaysValidSchema)(s,r))return;let a=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,fB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};ST.default=Gee});var kT=Ee(ET=>{"use strict";w();Object.defineProperty(ET,"__esModule",{value:!0});var Qb=Oo(),_a=_t(),Wee=Mo(),Xb=Lt(),Vee={message:"must NOT have additional properties",params:({params:t})=>(0,_a._)`{additionalProperty: ${t.additionalProperty}}`},Hee={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:a,it:o}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Xb.alwaysValidSchema)(o,r))return;let u=(0,Qb.allSchemaProperties)(n.properties),d=(0,Qb.allSchemaProperties)(n.patternProperties);l(),t.ok((0,_a._)`${a} === ${Wee.default.errors}`);function l(){e.forIn("key",s,y=>{!u.length&&!d.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let S;if(u.length>8){let v=(0,Xb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Qb.isOwnProperty)(e,v,y)}else u.length?S=(0,_a.or)(...u.map(v=>(0,_a._)`${y} === ${v}`)):S=_a.nil;return d.length&&(S=(0,_a.or)(S,...d.map(v=>(0,_a._)`${(0,Qb.usePattern)(t,v)}.test(${y})`))),(0,_a.not)(S)}function h(y){e.code((0,_a._)`delete ${s}[${y}]`)}function p(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Xb.alwaysValidSchema)(o,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,_a.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,_a.not)(S),()=>e.break()))}}function m(y,S,v){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Xb.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};ET.default=Hee});var yB=Ee(TT=>{"use strict";w();Object.defineProperty(TT,"__esModule",{value:!0});var Jee=_g(),hB=Oo(),_T=Lt(),mB=kT(),Zee={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&mB.default.code(new Jee.KeywordCxt(a,mB.default,"additionalProperties"));let o=(0,hB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=_T.mergeEvaluated.props(e,(0,_T.toHash)(o),a.props));let i=o.filter(l=>!(0,_T.alwaysValidSchema)(a,r[l]));if(i.length===0)return;let c=e.name("valid");for(let l of i)u(l)?d(l):(e.if((0,hB.propertyInData)(e,s,l,a.opts.ownProperties)),d(l),a.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return a.opts.useDefaults&&!a.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};TT.default=Zee});var bB=Ee(IT=>{"use strict";w();Object.defineProperty(IT,"__esModule",{value:!0});var gB=Oo(),e1=_t(),wB=Lt(),vB=Lt(),Yee={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:a}=t,{opts:o}=a,i=(0,gB.allSchemaProperties)(r),c=i.filter(m=>(0,wB.alwaysValidSchema)(a,r[m]));if(i.length===0||c.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof e1.Name)&&(a.props=(0,vB.evaluatedPropsToName)(e,a.props));let{props:l}=a;f();function f(){for(let m of i)u&&h(m),a.allErrors?p(m):(e.var(d,!0),p(m),e.if(d))}function h(m){for(let y in u)new RegExp(m).test(y)&&(0,wB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,e1._)`${(0,gB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:vB.Type.Str},d),a.opts.unevaluated&&l!==!0?e.assign((0,e1._)`${l}[${y}]`,!0):!S&&!a.allErrors&&e.if((0,e1.not)(d),()=>e.break())})})}}};IT.default=Yee});var PB=Ee(AT=>{"use strict";w();Object.defineProperty(AT,"__esModule",{value:!0});var Qee=Lt(),Xee={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Qee.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};AT.default=Xee});var xB=Ee(RT=>{"use strict";w();Object.defineProperty(RT,"__esModule",{value:!0});var ete=Oo(),tte={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ete.validateUnion,error:{message:"must match a schema in anyOf"}};RT.default=tte});var SB=Ee(DT=>{"use strict";w();Object.defineProperty(DT,"__esModule",{value:!0});var t1=_t(),rte=Lt(),nte={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},ste={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nte,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let a=r,o=e.let("valid",!1),i=e.let("passing",null),c=e.name("_valid");t.setParams({passing:i}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){a.forEach((d,l)=>{let f;(0,rte.alwaysValidSchema)(s,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,t1._)`${c} && ${o}`).assign(o,!1).assign(i,(0,t1._)`[${i}, ${l}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(i,l),f&&t.mergeEvaluated(f,t1.Name)})})}}};DT.default=ste});var EB=Ee(CT=>{"use strict";w();Object.defineProperty(CT,"__esModule",{value:!0});var ite=Lt(),ote={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((a,o)=>{if((0,ite.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};CT.default=ote});var TB=Ee(jT=>{"use strict";w();Object.defineProperty(jT,"__esModule",{value:!0});var r1=_t(),_B=Lt(),ate={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},cte={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ate,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_B.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=kB(n,"then"),a=kB(n,"else");if(!s&&!a)return;let o=e.let("valid",!0),i=e.name("_valid");if(c(),t.reset(),s&&a){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(i,u("then",d),u("else",d))}else s?e.if(i,u("then")):e.if((0,r1.not)(i),u("else"));t.pass(o,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},i);e.assign(o,i),t.mergeValidEvaluated(f,o),l?e.assign(l,(0,r1._)`${d}`):t.setParams({ifClause:d})}}}};function kB(t,e){let r=t.schema[e];return r!==void 0&&!(0,_B.alwaysValidSchema)(t,r)}jT.default=cte});var IB=Ee($T=>{"use strict";w();Object.defineProperty($T,"__esModule",{value:!0});var dte=Lt(),ute={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,dte.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};$T.default=ute});var AB=Ee(MT=>{"use strict";w();Object.defineProperty(MT,"__esModule",{value:!0});var lte=gT(),fte=oB(),pte=wT(),hte=cB(),mte=dB(),yte=Yb(),gte=pB(),wte=kT(),vte=yB(),bte=bB(),Pte=PB(),xte=xB(),Ste=SB(),Ete=EB(),kte=TB(),_te=IB();function Tte(t=!1){let e=[Pte.default,xte.default,Ste.default,Ete.default,kte.default,_te.default,gte.default,wte.default,yte.default,vte.default,bte.default];return t?e.push(fte.default,hte.default):e.push(lte.default,pte.default),e.push(mte.default),e}MT.default=Tte});var BT=Ee(zg=>{"use strict";w();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicAnchor=void 0;var OT=_t(),Ite=Mo(),RB=Ig(),Ate=Gb(),Rte={keyword:"$dynamicAnchor",schemaType:"string",code:t=>DB(t,t.schema)};function DB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,OT._)`${Ite.default.dynamicAnchors}${(0,OT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Dte(t);r.if((0,OT._)`!${s}`,()=>r.assign(s,a))}zg.dynamicAnchor=DB;function Dte(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:s,baseId:a,localRefs:o,meta:i}=e.root,{schemaId:c}=n.opts,u=new RB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return RB.compileSchema.call(n,u),(0,Ate.getValidate)(t,u)}zg.default=Rte});var NT=Ee(qg=>{"use strict";w();Object.defineProperty(qg,"__esModule",{value:!0});qg.dynamicRef=void 0;var CB=_t(),Cte=Mo(),jB=Gb(),jte={keyword:"$dynamicRef",schemaType:"string",code:t=>$B(t,t.schema)};function $B(t,e){let{gen:r,keyword:n,it:s}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(s.allErrors)o();else{let c=r.let("valid",!1);o(c),t.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[a]){let u=r.let("_v",(0,CB._)`${Cte.default.dynamicAnchors}${(0,CB.getProperty)(a)}`);r.if(u,i(u,c),i(s.validateName,c))}else i(s.validateName,c)()}function i(c,u){return u?()=>r.block(()=>{(0,jB.callRef)(t,c),r.let(u,!0)}):()=>(0,jB.callRef)(t,c)}}qg.dynamicRef=$B;qg.default=jte});var MB=Ee(UT=>{"use strict";w();Object.defineProperty(UT,"__esModule",{value:!0});var $te=BT(),Mte=Lt(),Ote={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,$te.dynamicAnchor)(t,""):(0,Mte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};UT.default=Ote});var OB=Ee(LT=>{"use strict";w();Object.defineProperty(LT,"__esModule",{value:!0});var Bte=NT(),Nte={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Bte.dynamicRef)(t,t.schema)};LT.default=Nte});var BB=Ee(KT=>{"use strict";w();Object.defineProperty(KT,"__esModule",{value:!0});var Ute=BT(),Lte=NT(),Kte=MB(),zte=OB(),qte=[Ute.default,Lte.default,Kte.default,zte.default];KT.default=qte});var UB=Ee(zT=>{"use strict";w();Object.defineProperty(zT,"__esModule",{value:!0});var NB=Yb(),Fte={keyword:"dependentRequired",type:"object",schemaType:"object",error:NB.error,code:t=>(0,NB.validatePropertyDeps)(t)};zT.default=Fte});var LB=Ee(qT=>{"use strict";w();Object.defineProperty(qT,"__esModule",{value:!0});var Gte=Yb(),Wte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Gte.validateSchemaDeps)(t)};qT.default=Wte});var KB=Ee(FT=>{"use strict";w();Object.defineProperty(FT,"__esModule",{value:!0});var Vte=Lt(),Hte={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Vte.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};FT.default=Hte});var zB=Ee(GT=>{"use strict";w();Object.defineProperty(GT,"__esModule",{value:!0});var Jte=UB(),Zte=LB(),Yte=KB(),Qte=[Jte.default,Zte.default,Yte.default];GT.default=Qte});var FB=Ee(WT=>{"use strict";w();Object.defineProperty(WT,"__esModule",{value:!0});var Iu=_t(),qB=Lt(),Xte=Mo(),ere={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Iu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},tre={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:ere,code(t){let{gen:e,schema:r,data:n,errsCount:s,it:a}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:i}=a;i instanceof Iu.Name?e.if((0,Iu._)`${i} !== true`,()=>e.forIn("key",n,l=>e.if(u(i,l),()=>c(l)))):i!==!0&&e.forIn("key",n,l=>i===void 0?c(l):e.if(d(i,l),()=>c(l))),a.props=!0,t.ok((0,Iu._)`${s} === ${Xte.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,qB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:qB.Type.Str},f),o||e.if((0,Iu.not)(f),()=>e.break())}}function u(l,f){return(0,Iu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Iu._)`${f} !== ${p}`);return(0,Iu.and)(...h)}}};WT.default=tre});var WB=Ee(VT=>{"use strict";w();Object.defineProperty(VT,"__esModule",{value:!0});var pf=_t(),GB=Lt(),rre={message:({params:{len:t}})=>(0,pf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pf._)`{limit: ${t}}`},nre={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:rre,code(t){let{gen:e,schema:r,data:n,it:s}=t,a=s.items||0;if(a===!0)return;let o=e.const("len",(0,pf._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,pf._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,GB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,pf._)`${o} <= ${a}`);e.if((0,pf.not)(c),()=>i(c,a)),t.ok(c)}s.items=!0;function i(c,u){e.forRange("i",u,o,d=>{t.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:GB.Type.Num},c),s.allErrors||e.if((0,pf.not)(c),()=>e.break())})}}};VT.default=nre});var VB=Ee(HT=>{"use strict";w();Object.defineProperty(HT,"__esModule",{value:!0});var sre=FB(),ire=WB(),ore=[sre.default,ire.default];HT.default=ore});var HB=Ee(JT=>{"use strict";w();Object.defineProperty(JT,"__esModule",{value:!0});var An=_t(),are={message:({schemaCode:t})=>(0,An.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,An._)`{format: ${t}}`},cre={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:are,code(t,e){let{gen:r,data:n,$data:s,schema:a,schemaCode:o,it:i}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=i;if(!c.validateFormats)return;s?f():h();function f(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,An._)`${p}[${o}]`),y=r.let("fType"),S=r.let("format");r.if((0,An._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,An._)`${m}.type || "string"`).assign(S,(0,An._)`${m}.validate`),()=>r.assign(y,(0,An._)`"string"`).assign(S,m)),t.fail$data((0,An.or)(v(),E()));function v(){return c.strictSchema===!1?An.nil:(0,An._)`${o} && !${S}`}function E(){let _=d.$async?(0,An._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,An._)`${S}(${n})`,I=(0,An._)`(typeof ${S} == "function" ? ${_} : ${S}.test(${n}))`;return(0,An._)`${S} && ${S} !== true && ${y} === ${e} && !${I}`}}function h(){let p=l.formats[a];if(!p){v();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(_());function v(){if(c.strictSchema===!1){l.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${a}" ignored in schema at path "${u}"`}}function E(I){let R=I instanceof RegExp?(0,An.regexpCode)(I):c.code.formats?(0,An._)`${c.code.formats}${(0,An.getProperty)(a)}`:void 0,N=r.scopeValue("formats",{key:a,ref:I,code:R});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,An._)`${N}.validate`]:["string",I,N]}function _(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,An._)`await ${S}(${n})`}return typeof y=="function"?(0,An._)`${S}(${n})`:(0,An._)`${S}.test(${n})`}}}};JT.default=cre});var JB=Ee(ZT=>{"use strict";w();Object.defineProperty(ZT,"__esModule",{value:!0});var dre=HB(),ure=[dre.default];ZT.default=ure});var ZB=Ee(_h=>{"use strict";w();Object.defineProperty(_h,"__esModule",{value:!0});_h.contentVocabulary=_h.metadataVocabulary=void 0;_h.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_h.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var QB=Ee(YT=>{"use strict";w();Object.defineProperty(YT,"__esModule",{value:!0});var lre=F4(),fre=rB(),pre=AB(),hre=BB(),mre=zB(),yre=VB(),gre=JB(),YB=ZB(),wre=[hre.default,lre.default,fre.default,(0,pre.default)(!0),gre.default,YB.metadataVocabulary,YB.contentVocabulary,mre.default,yre.default];YT.default=wre});var eN=Ee(n1=>{"use strict";w();Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var XB;(function(t){t.Tag="tag",t.Mapping="mapping"})(XB||(n1.DiscrError=XB={}))});var rN=Ee(XT=>{"use strict";w();Object.defineProperty(XT,"__esModule",{value:!0});var Th=_t(),QT=eN(),tN=Ig(),vre=Tg(),bre=Lt(),Pre={message:({params:{discrError:t,tagName:e}})=>t===QT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Th._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xre={keyword:"discriminator",type:"object",schemaType:"object",error:Pre,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:a}=t,{oneOf:o}=s;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=n.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Th._)`${r}${(0,Th.getProperty)(i)}`);e.if((0,Th._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:QT.DiscrError.Tag,tag:u,tagName:i})),t.ok(c);function d(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Th._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:QT.DiscrError.Mapping,tag:u,tagName:i}),e.endIf()}function l(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,Th.Name),p}function f(){var h;let p={},m=S(s),y=!0;for(let _=0;_<o.length;_++){let I=o[_];if(I?.$ref&&!(0,bre.schemaHasRulesButRef)(I,a.self.RULES)){let N=I.$ref;if(I=tN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),I instanceof tN.SchemaEnv&&(I=I.schema),I===void 0)throw new vre.default(a.opts.uriResolver,a.baseId,N)}let R=(h=I?.properties)===null||h===void 0?void 0:h[i];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(I)),v(R,_)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:_}){return Array.isArray(_)&&_.includes(i)}function v(_,I){if(_.const)E(_.const,I);else if(_.enum)for(let R of _.enum)E(R,I);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function E(_,I){if(typeof _!="string"||_ in p)throw new Error(`discriminator: "${i}" values must be unique strings`);p[_]=I}}}};XT.default=xre});var nN=Ee((NDe,Sre)=>{Sre.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 sN=Ee((UDe,Ere)=>{Ere.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 iN=Ee((LDe,kre)=>{kre.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 oN=Ee((KDe,_re)=>{_re.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 aN=Ee((zDe,Tre)=>{Tre.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 cN=Ee((qDe,Ire)=>{Ire.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 dN=Ee((FDe,Are)=>{Are.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 uN=Ee((GDe,Rre)=>{Rre.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 lN=Ee(eI=>{"use strict";w();Object.defineProperty(eI,"__esModule",{value:!0});var Dre=nN(),Cre=sN(),jre=iN(),$re=oN(),Mre=aN(),Ore=cN(),Bre=dN(),Nre=uN(),Ure=["/properties"];function Lre(t){return[Dre,Cre,jre,$re,Mre,e(this,Ore),Bre,e(this,Nre)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Ure):n}}eI.default=Lre});var nI=Ee((Hr,rI)=>{"use strict";w();Object.defineProperty(Hr,"__esModule",{value:!0});Hr.MissingRefError=Hr.ValidationError=Hr.CodeGen=Hr.Name=Hr.nil=Hr.stringify=Hr.str=Hr._=Hr.KeywordCxt=Hr.Ajv2020=void 0;var Kre=U4(),zre=QB(),qre=rN(),Fre=lN(),tI="https://json-schema.org/draft/2020-12/schema",Ih=class extends Kre.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),zre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(qre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(Fre.default.call(this,e),this.refs["http://json-schema.org/schema"]=tI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(tI)?tI:void 0)}};Hr.Ajv2020=Ih;rI.exports=Hr=Ih;rI.exports.Ajv2020=Ih;Object.defineProperty(Hr,"__esModule",{value:!0});Hr.default=Ih;var Gre=_g();Object.defineProperty(Hr,"KeywordCxt",{enumerable:!0,get:function(){return Gre.KeywordCxt}});var Ah=_t();Object.defineProperty(Hr,"_",{enumerable:!0,get:function(){return Ah._}});Object.defineProperty(Hr,"str",{enumerable:!0,get:function(){return Ah.str}});Object.defineProperty(Hr,"stringify",{enumerable:!0,get:function(){return Ah.stringify}});Object.defineProperty(Hr,"nil",{enumerable:!0,get:function(){return Ah.nil}});Object.defineProperty(Hr,"Name",{enumerable:!0,get:function(){return Ah.Name}});Object.defineProperty(Hr,"CodeGen",{enumerable:!0,get:function(){return Ah.CodeGen}});var Wre=Ob();Object.defineProperty(Hr,"ValidationError",{enumerable:!0,get:function(){return Wre.default}});var Vre=Tg();Object.defineProperty(Hr,"MissingRefError",{enumerable:!0,get:function(){return Vre.default}})});var b9=Ee((YOe,_A)=>{"use strict";w();var Xde=Object.prototype.hasOwnProperty,_i="~";function Bw(){}Object.create&&(Bw.prototype=Object.create(null),new Bw().__proto__||(_i=!1));function eue(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function v9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new eue(r,n||t,s),o=_i?_i+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}function wP(t,e){--t._eventsCount===0?t._events=new Bw:delete t._events[e]}function ri(){this._events=new Bw,this._eventsCount=0}ri.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Xde.call(r,n)&&e.push(_i?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ri.prototype.listeners=function(e){var r=_i?_i+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,o=new Array(a);s<a;s++)o[s]=n[s].fn;return o};ri.prototype.listenerCount=function(e){var r=_i?_i+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ri.prototype.emit=function(e,r,n,s,a,o){var i=_i?_i+e:e;if(!this._events[i])return!1;var c=this._events[i],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,s),!0;case 5:return c.fn.call(c.context,r,n,s,a),!0;case 6:return c.fn.call(c.context,r,n,s,a,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var f=c.length,h;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,r);break;case 3:c[l].fn.call(c[l].context,r,n);break;case 4:c[l].fn.call(c[l].context,r,n,s);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];c[l].fn.apply(c[l].context,d)}}return!0};ri.prototype.on=function(e,r,n){return v9(this,e,r,n,!1)};ri.prototype.once=function(e,r,n){return v9(this,e,r,n,!0)};ri.prototype.removeListener=function(e,r,n,s){var a=_i?_i+e:e;if(!this._events[a])return this;if(!r)return wP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&wP(this,a);else{for(var i=0,c=[],u=o.length;i<u;i++)(o[i].fn!==r||s&&!o[i].once||n&&o[i].context!==n)&&c.push(o[i]);c.length?this._events[a]=c.length===1?c[0]:c:wP(this,a)}return this};ri.prototype.removeAllListeners=function(e){var r;return e?(r=_i?_i+e:e,this._events[r]&&wP(this,r)):(this._events=new Bw,this._eventsCount=0),this};ri.prototype.off=ri.prototype.removeListener;ri.prototype.addListener=ri.prototype.on;ri.prefixed=_i;ri.EventEmitter=ri;typeof _A<"u"&&(_A.exports=ri)});w();w();var dm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(dm||{});w();w();hn();Na();w();w();var jm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,LD=new Set,n2=typeof process=="object"&&process?process:{},KD=(t,e,r,n)=>{typeof n2.emitWarning=="function"?n2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},I0=globalThis.AbortController,UD=globalThis.AbortSignal;if(typeof I0>"u"){UD=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},I0=class{constructor(){e()}signal=new UD;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n)}}};let t=n2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,KD("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var AF=t=>!LD.has(t),Zhe=Symbol("type"),Kd=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),zD=t=>Kd(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?mp:null:null,mp=class extends Array{constructor(e){super(e),this.fill(0)}},s2=class t{heap;length;static#c=!1;static create(e){let r=zD(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},A0=class t{#c;#l;#w;#h;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#s;#r;#e;#d;#f;#a;#i;#y;#o;#x;#S;#g;#v;#k;#u;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#g,sizes:e.#x,keyMap:e.#s,keyList:e.#r,valList:e.#e,next:e.#d,prev:e.#f,get head(){return e.#a},get tail(){return e.#i},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,s,a)=>e.#C(r,n,s,a),moveToTail:r=>e.#I(r),indexes:r=>e.#b(r),rindexes:r=>e.#P(r),isStale:r=>e.#p(r)}}get max(){return this.#c}get maxSize(){return this.#l}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#A}get dispose(){return this.#w}get disposeAfter(){return this.#h}constructor(e){let{max:r=0,ttl:n,ttlResolution:s=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:i,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:_,ignoreFetchAbort:I}=e;if(r!==0&&!Kd(r))throw new TypeError("max option must be a nonnegative integer");let R=r?zD(r):Array;if(!R)throw new Error("invalid max value: "+r);if(this.#c=r,this.#l=h,this.maxEntrySize=p||this.#l,this.sizeCalculation=m,this.sizeCalculation){if(!this.#l&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#A=y,this.#k=!!y,this.#s=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#d=new R(r),this.#f=new R(r),this.#a=0,this.#i=0,this.#y=s2.create(r),this.#n=0,this.#m=0,typeof u=="function"&&(this.#w=u),typeof d=="function"?(this.#h=d,this.#o=[]):(this.#h=void 0,this.#o=void 0),this.#v=!!this.#w,this.#u=!!this.#h,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#l!==0&&!Kd(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Kd(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Kd(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Kd(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#c===0&&this.ttl===0&&this.#l===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#l){let N="LRU_CACHE_UNBOUNDED";AF(N)&&(LD.add(N),KD("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,t))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#j(){let e=new mp(this.#c),r=new mp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=jm.now())=>{if(r[a]=o!==0?i:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#p(a)&&this.delete(this.#r[a])},o+1);c.unref&&c.unref()}},this.#_=a=>{r[a]=e[a]!==0?jm.now():0},this.#E=(a,o)=>{if(e[o]){let i=e[o],c=r[o];a.ttl=i,a.start=c,a.now=n||s();let u=a.now-c;a.remainingTTL=i-u}};let n=0,s=()=>{let a=jm.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#s.get(a);if(o===void 0)return 0;let i=e[o],c=r[o];if(i===0||c===0)return 1/0;let u=(n||s())-c;return i-u},this.#p=a=>e[a]!==0&&r[a]!==0&&(n||s())-r[a]>e[a]}#_=()=>{};#E=()=>{};#$=()=>{};#p=()=>!1;#N(){let e=new mp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#M=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Kd(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Kd(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#R=(r,n,s)=>{if(e[r]=n,this.#l){let a=this.#l-e[r];for(;this.#m>a;)this.#D(!0)}this.#m+=e[r],s&&(s.entrySize=n,s.totalCalculatedSize=this.#m)}}#T=e=>{};#R=(e,r,n)=>{};#M=(e,r,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#i;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#P({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#O(e){return e!==void 0&&this.#s.get(this.#r[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#P())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#b()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#P()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#b())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#P())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#P()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#P({allowStale:!0}))this.#p(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#b({allowStale:!0})){let n=this.#r[r],s=this.#e[r],a=this.#t(s)?s.__staleWhileFetching:s;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#g&&this.#S){o.ttl=this.#g[r];let i=jm.now()-this.#S[r];o.start=Math.floor(Date.now()-i)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let s=Date.now()-n.start;n.start=jm.now()-s}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,d=this.#M(e,r,n.size||0,i);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let l=this.#n===0?void 0:this.#s.get(e);if(l===void 0)l=this.#n===0?this.#i:this.#y.length!==0?this.#y.pop():this.#n===this.#c?this.#D(!1):this.#n,this.#r[l]=e,this.#e[l]=r,this.#s.set(e,l),this.#d[this.#i]=l,this.#f[l]=this.#i,this.#i=l,this.#n++,this.#R(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(r!==f){if(this.#k&&this.#t(f)?f.__abortController.abort(new Error("replaced")):o||(this.#v&&this.#w?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"])),this.#T(l),this.#R(l,d,c),this.#e[l]=r,c){c.set="replace";let h=f&&this.#t(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(s!==0&&!this.#g&&this.#j(),this.#g&&(u||this.#$(l,s,a),c&&this.#E(c,l)),!o&&this.#u&&this.#o){let f=this.#o,h;for(;h=f?.shift();)this.#h?.(...h)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#D(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}}#D(e){let r=this.#a,n=this.#r[r],s=this.#e[r];return this.#k&&this.#t(s)?s.__abortController.abort(new Error("evicted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,n,"evict"),this.#u&&this.#o?.push([s,n,"evict"])),this.#T(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#n===1?(this.#a=this.#i=0,this.#y.length=0):this.#a=this.#d[r],this.#s.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=r,a=this.#s.get(e);if(a!==void 0){let o=this.#e[a];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(a))s&&(s.has="stale",this.#E(s,a));else return n&&this.#_(a),s&&(s.has="hit",this.#E(s,a)),!0}else s&&(s.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,s=this.#s.get(e);if(s!==void 0&&(n||!this.#p(s))){let a=this.#e[s];return this.#t(a)?a.__staleWhileFetching:a}}#C(e,r,n,s){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new I0,{signal:i}=n;i?.addEventListener("abort",()=>o.abort(i.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:s},u=(m,y=!1)=>{let{aborted:S}=o.signal,v=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,v&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!v&&!y)return l(o.signal.reason);let E=h;return this.#e[r]===h&&(m===void 0?E.__staleWhileFetching?this.#e[r]=E.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),l(m)),l=m=>{let{aborted:y}=o.signal,S=y&&n.allowStaleOnFetchAbort,v=S||n.allowStaleOnFetchRejection,E=v||n.noDeleteOnFetchRejection,_=h;if(this.#e[r]===h&&(!E||_.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=_.__staleWhileFetching)),v)return n.status&&_.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,y)=>{let S=this.#A?.(e,a,c);S&&S instanceof Promise&&S.then(v=>m(v),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=v=>u(v,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(u,d),p=Object.assign(h,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,p,{...c.options,status:void 0}),r=this.#s.get(e)):this.#e[r]=p,p}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof I0}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:y=!1,status:S,signal:v}=r;if(!this.#k)return S&&(S.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,status:S});let E={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:i,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:S,signal:v},_=this.#s.get(e);if(_===void 0){S&&(S.fetch="miss");let I=this.#C(e,_,E,m);return I.__returned=I}else{let I=this.#e[_];if(this.#t(I)){let z=n&&I.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",z&&(S.returnedStale=!0)),z?I.__staleWhileFetching:I.__returned=I}let R=this.#p(_);if(!y&&!R)return S&&(S.fetch="hit"),this.#I(_),s&&this.#_(_),S&&this.#E(S,_),I;let N=this.#C(e,_,E,m),F=N.__staleWhileFetching!==void 0&&n;return S&&(S.fetch=R?"stale":"refresh",F&&R&&(S.returnedStale=!0)),F?N.__staleWhileFetching:N.__returned=N}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,i=this.#s.get(e);if(i!==void 0){let c=this.#e[i],u=this.#t(c);return o&&this.#E(o,i),this.#p(i)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.delete(e),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#I(i),s&&this.#_(i),c))}else o&&(o.get="miss")}#B(e,r){this.#f[r]=e,this.#d[e]=r}#I(e){e!==this.#i&&(e===this.#a?this.#a=this.#d[e]:this.#B(this.#f[e],this.#d[e]),this.#B(this.#i,e),this.#i=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#s.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#T(n);let s=this.#e[n];this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,e,"delete"),this.#u&&this.#o?.push([s,e,"delete"])),this.#s.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#i?this.#i=this.#f[n]:n===this.#a?this.#a=this.#d[n]:(this.#d[this.#f[n]]=this.#d[n],this.#f[this.#d[n]]=this.#f[n]),this.#n--,this.#y.push(n)}}if(this.#u&&this.#o?.length){let n=this.#o,s;for(;s=n?.shift();)this.#h?.(...s)}return r}clear(){for(let e of this.#P({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#v&&this.#w?.(r,n,"delete"),this.#u&&this.#o?.push([r,n,"delete"])}}if(this.#s.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#g&&this.#S&&(this.#g.fill(0),this.#S.fill(0)),this.#x&&this.#x.fill(0),this.#a=0,this.#i=0,this.#y.length=0,this.#m=0,this.#n=0,this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}};var R0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new A0({max:1e5,ttl:e*1e3})}cache;async set(e,r){try{this.cache.set(e,r)}catch{}}async get(e){return this.cache.get(e)}};j0();ht();var qd=class t{static _singleton;cache;constructor(e){this.cache=e||new R0(600)}static get singleton(){return t._singleton===void 0&&(t._singleton=new t),t._singleton}static async verifySignatures(e,r){return await t.singleton.verifySignatures(e,r)}async verifySignatures(e,r){let n=[];for(let s of e.signatures){let a,o=Te.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new ne("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new ne("GeneralJwsVerifierMissingAlg","JWS protected header is missing required 'alg' property");let u=`${s.protected}.${e.payload}.${s.signature}`,d=await this.cache.get(u);if(d===void 0){let f=await t.getPublicKey(i,r);a=await vt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=vt.extractDid(i);if(a)n.push(l);else throw new ne("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=vt.extractDid(e),{didDocument:s}=await r.resolve(n),{verificationMethod:a=[]}=s||{},o;for(let c of a)if(e.endsWith(c.id)){o=c;break}if(!o)throw new ne("GeneralJwsVerifierGetPublicKeyNotFound","public key needed to verify signature not found in DID Document");Kc("JwkVerificationMethod",o);let{publicKeyJwk:i}=o;return i}};bi();ht();async function dn(t,e,r){if(t===void 0)throw new ne("AuthenticateJwsMissing","Missing JWS.");if(await qd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await qd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await xt.parse(t.authorDelegatedGrant);await qd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await xt.parse(t.ownerDelegatedGrant);await qd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await qd.verifySignatures(r,e)}w();var cg=class{_protocols=new Map;register(e){this._protocols.set(e.uri,e)}get(e){return this._protocols.get(e)}getDefinition(e){return this._protocols.get(e)?.definition}has(e){return this._protocols.has(e)}all(){return[...this._protocols.values()]}mapErrorToStatusCode(e){for(let r of this._protocols.values()){let n=r.mapErrorToStatusCode?.(e);if(n!==void 0)return n}}};zE();w();var dg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Hc();w();w();Na();or();var xn=class{_message;get message(){return this._message}_signer;get signer(){return this._signer}_author;get author(){return this._author}_signaturePayload;get signaturePayload(){return this._signaturePayload}get isSignedByAuthorDelegate(){return we.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=we.getSigner(e),e.authorization.authorDelegatedGrant!==void 0?this._author=we.getSigner(e.authorization.authorDelegatedGrant):this._author=this._signer,this._signaturePayload=vt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var Jl=class t extends xn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Count",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter)};Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};w();Al();or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var Zl=class t extends xn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new ne("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Hd();zp();w();or();w();function ut(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}w();Hd();hn();w();Xt();Mv();w();w();var jo=class{static maxDataSizeAllowedToBeEncoded=3e4};hn();wa();or();pa();w();hn();or();ht();var ug=class t{id;requester;description;delegated;scope;conditions;static parse(e){return t.validateMessage(e),new t(e)}static validateMessage(e){if(e.encodedData===void 0||e.encodedData===null)throw new ne("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(we.getSigner(e)===void 0)throw new ne("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(Te.base64UrlToObject(e.encodedData).scope===void 0)throw new ne("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=we.getSigner(e);let r=e.encodedData,n=Te.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};On();bi();Hs();j0();ht();Xt();Ro();var Ir=class t{static uri="https://identity.foundation/dwn/permissions";static requestPath="request";static grantPath="grant";static revocationPath="grant/revocation";static definition={published:!0,protocol:t.uri,types:{request:{dataFormats:["application/json"]},grant:{dataFormats:["application/json"]},revocation:{dataFormats:["application/json"]}},structure:{request:{$size:{max:1e4},$actions:[{who:"anyone",can:["create"]}]},grant:{$size:{max:1e4},$actions:[{who:"recipient",of:"grant",can:["read"]}],revocation:{$size:{max:1e4},$actions:[{who:"anyone",can:["read"]}]}}}};get uri(){return t.uri}get definition(){return t.definition}validateRecord(e,r){t.validateSchema(e,r)}async preProcessWrite(e,r,n){if(r.descriptor.protocolPath!==t.revocationPath)return;let s=r.descriptor.parentId,a=await t.fetchGrant(e,n,s),o=r.descriptor.tags?.protocol,i="protocol"in a.scope?a.scope.protocol:void 0;if(i!==o)throw new ne("PermissionsProtocolValidateRevocationProtocolTagMismatch",`Revocation protocol ${o} does not match grant protocol ${i}`)}async postProcessWrite(e,r,n){if(r.message.descriptor.protocolPath!==t.revocationPath)return;let a={permissionGrantId:r.message.descriptor.parentId,dateCreated:{gte:r.message.descriptor.messageTimestamp}},{messages:o}=await n.messageStore.query(e,[a]);if(o.length===0)return;for(let c of o)if(c.descriptor.method==="Write"){let u=c;u.descriptor.dataSize>jo.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>we.getCid(c)));await n.stateIndex.delete(e,i),await Promise.all(i.map(c=>n.messageStore.delete(e,c)))}mapErrorToStatusCode(e){if(e.startsWith("PermissionsProtocolValidate"))return 400}constructAdditionalMessageFilter(e){let{protocol:r,messageTimestamp:n}=e;if(r===void 0)return;let s={protocol:t.uri,..._e.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Gt.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return Te.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateRequestRecordsScopeMissingProtocol","Permission request for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await xt.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRequestData:n,permissionRequestBytes:a,dataEncodedMessage:i}}static async createGrant(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateGrantRecordsScopeMissingProtocol","Permission grants for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={dateExpires:e.dateExpires,requestId:e.requestId,description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await xt.create({signer:e.signer,messageTimestamp:e.dateGranted,dateCreated:e.dateGranted,recipient:e.grantedTo,protocol:t.uri,protocolPath:t.grantPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionGrantData:n,permissionGrantBytes:a,dataEncodedMessage:i}}static async createRevocation(e){let r={description:e.description},n=e.grant.id,s;this.hasProtocolScope(e.grant.scope)&&(s={protocol:hi(e.grant.scope.protocol)});let a=Te.objectToBytes(r),o=await xt.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=Te.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Kc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Kc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Kc("PermissionRevocationData",s);else throw new ne("PermissionsProtocolValidateSchemaUnexpectedRecord",`Unexpected permission record: ${e.descriptor.protocolPath}`)}static async fetchGrant(e,r,n){let s={recordId:n,isLatestBaseState:!0},{messages:a}=await r.query(e,[s]),o=a[0],i=o?.descriptor.interface,c=o?.descriptor.method;if(i!=="Records"||c!=="Write"||o.descriptor.protocolPath!==t.grantPath)throw new ne("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Xr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new ne("PermissionsProtocolGetScopeInvalidProtocol",`Unexpected protocol for permission record: ${n.descriptor.protocol}`);return n.descriptor.protocolPath===t.revocationPath?(await t.fetchGrant(e,r,n.descriptor.parentId)).scope:n.descriptor.protocolPath===t.grantPath?Xr.parse(n).scope:ug.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=hi(r.protocol)),r}static isRecordPermissionScope(e){return e.interface==="Records"}static hasProtocolScope(e){return"protocol"in e&&e.protocol!==void 0}static validateTags(e,r){if(e.descriptor.tags===void 0||e.descriptor.tags.protocol===void 0)throw new ne("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new ne("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(Fn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new ne("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};On();bi();ht();var wu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await no.performBaseValidation({incomingMessage:r,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i});let c=o.scope;await t.verifyScope(s,n,c,i)}static async authorizeSubscribeOrSync(e){let{incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;if(await no.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),Ir.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${c.descriptor.protocol} does not match the scoped protocol ${i}`)}else{let c=r;for(let u of c.descriptor.filters)if(u.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${u.protocol} does not match the scoped protocol ${i}`)}}}static async verifyScope(e,r,n,s){if(n.protocol!==void 0){if(r.descriptor.interface==="Records"){let a=r,o=_e.isRecordsWrite(a)?a:await xt.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===Ir.uri){let i=await Ir.getScopeFromPermissionRecord(e,s,o);if(Ir.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new ne("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};w();Hc();or();Hs();ht();Xt();var Yl=class t extends xn{static async parse(e){return we.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{signer:r,permissionGrantId:n}=e,s={interface:"Messages",method:"Read",messageCid:e.messageCid,messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),...n!==void 0&&{permissionGrantId:n}},a=await we.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Dr.parseCid(e)}catch{throw new ne("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};On();ht();var bb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Yl.parse(r)}catch(o){return ut(o,400)}try{await dn(r.authorization,this.deps.didResolver)}catch(o){return ut(o,401)}let s=await this.deps.messageStore.get(e,r.descriptor.messageCid);if(s===void 0)return{status:{code:404,detail:"Not Found"}};try{await t.authorizeMessagesRead(e,n,s,this.deps.messageStore)}catch(o){return ut(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(_e.isRecordsWrite(s)){let o=a.message;if(o.encodedData!==void 0){let i=Te.base64UrlToBytes(o.encodedData);a.data=rs.fromBytes(i),delete o.encodedData}else{let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}}return{status:{code:200,detail:"OK"},entry:a}}static async authorizeMessagesRead(e,r,n,s){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let a=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await wu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new ne("MessagesReadAuthorizationFailed","protocol message failed authorization")}};w();or();w();wa();Ro();ms();var Pb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol!==void 0?hi(n.protocol):void 0,a={...n,protocol:s};Ft(a),Il(a)||r.push(a)}return r}static convertFilters(e,r){let n=[];for(let s of e){if(r!==void 0)for(let a of r.all()){let o=a.constructAdditionalMessageFilter?.(s);o!==void 0&&n.push(o)}if(n.push(this.convertFilter(s)),(s.protocolPathPrefix!==void 0||s.contextIdPrefix!==void 0)&&s.protocol!==void 0){let a={interface:"Protocols",method:"Configure",protocol:s.protocol};if(s.messageTimestamp!==void 0){let o=Gt.convertRangeCriterion(s.messageTimestamp);o&&(a.messageTimestamp=o)}n.push(a)}}return n}static convertFilter(e){let r={...e},{messageTimestamp:n,protocolPathPrefix:s,contextIdPrefix:a}=e,o=n?Gt.convertRangeCriterion(n):void 0;return o&&(r.messageTimestamp=o,delete r.dateUpdated),s!==void 0&&(delete r.protocolPathPrefix,r.protocolPath={gte:s,lt:s+"/\uFFFF"}),a!==void 0&&(delete r.contextIdPrefix,r.contextId={gte:a,lt:a+"/\uFFFF"}),r}};w();or();ms();Hs();Ro();Xt();var Ql=class t extends xn{static async parse(e){we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&Fn(r.protocol);return yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=yt.getCurrentTimestamp(),n={interface:"Messages",method:"Subscribe",filters:e.filters??[],messageTimestamp:e.messageTimestamp??r,permissionGrantId:e.permissionGrantId,cursor:e.cursor};Ft(n);let{permissionGrantId:s,signer:a}=e,o=await we.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return we.validateJsonSchema(i),new t(i)}};ht();var xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Ql.parse(r)}catch(u){return ut(u,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ut(u,401)}let{filters:a,cursor:o}=r.descriptor,i=Pb.convertFilters(a,this.deps.coreProtocols),c=await we.getCid(r);try{let u=await this.deps.eventLog.subscribe(e,c,n,{cursor:o,filters:i});return{status:{code:200,detail:"OK"},subscription:u}}catch(u){if(u instanceof ne&&u.code==="EventLogProgressGap"){let d=u.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:d!==void 0?{code:"ProgressGap",...d}:void 0}}return ut(u,500)}}static async authorizeMessagesSubscribe(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await wu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSubscribeAuthorizationFailed","message failed authorization")}};w();hn();bu();w();or();ms();Hs();Ro();Xt();var fg=class t extends xn{static async parse(e){return we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&Fn(e.descriptor.protocol),new t(e)}static async create(e){let r={interface:"Messages",method:"Sync",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),action:e.action,protocol:e.protocol,prefix:e.prefix,permissionGrantId:e.permissionGrantId,hashes:e.hashes,depth:e.depth};Ft(r);let{permissionGrantId:n,signer:s}=e,a=await we.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return we.validateJsonSchema(o),new t(o)}};ht();var xZ=jo.maxDataSizeAllowedToBeEncoded,Sb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fg.parse(r)}catch(i){return ut(i,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ut(i,401)}let{action:s,protocol:a,prefix:o}=r.descriptor;try{switch(s){case"root":{let i=a!==void 0?await this.deps.stateIndex.getProtocolRoot(e,a):await this.deps.stateIndex.getRoot(e);return{status:{code:200,detail:"OK"},root:Jn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i):await this.deps.stateIndex.getSubtreeHash(e,i);return{status:{code:200,detail:"OK"},hash:Jn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolLeaves(e,a,i):await this.deps.stateIndex.getLeaves(e,i);return{status:{code:200,detail:"OK"},entries:c}}case"diff":return this.handleDiff(e,r);default:return{status:{code:400,detail:`Unknown action: ${s}`}}}}catch(i){return ut(i,500)}}async handleDiff(e,r){let{protocol:n,hashes:s,depth:a}=r.descriptor;if(!s||a===void 0)return{status:{code:400,detail:"diff action requires hashes and depth"}};let o=this.deps.stateIndex,i=[],c=[],u=await this.getDefaultHashHex(a),d=new Set;for(let[h,p]of Object.entries(s))p!==u&&d.add(h);let l=await this.collectSubtreeHashes(e,n,a);for(let h of Object.keys(l))d.add(h);for(let h of d){let p=s[h],m=l[h];if(p===m)continue;if(m===void 0){c.push(h);continue}if(p===void 0){let v=t.parseBitPrefix(h),E=n!==void 0?await o.getProtocolLeaves(e,n,v):await o.getLeaves(e,v);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n!==void 0?await o.getProtocolLeaves(e,n,y):await o.getLeaves(e,y);i.push(...S),c.push(h)}let f=await this.buildDiffEntries(e,i);return{status:{code:200,detail:"OK"},onlyRemote:f,onlyLocal:c}}async collectSubtreeHashes(e,r,n){let s=this.deps.stateIndex,a={},o=await this.getDefaultHashHex(n),i=async(c,u)=>{let d=t.parseBitPrefix(c),l=r!==void 0?await s.getProtocolSubtreeHash(e,r,d):await s.getSubtreeHash(e,d),f=Jn(l);if(f!==o){if(u>=n){a[c]=f;return}await Promise.all([i(c+"0",u+1),i(c+"1",u+1)])}};return await i("",0),a}_defaultHashHexCache;async getDefaultHashHex(e){if(this._defaultHashHexCache===void 0){let{initDefaultHashes:r}=await Promise.resolve().then(()=>(bu(),wO)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Jn(n[s]))}return this._defaultHashHexCache.get(e)??""}async buildDiffEntries(e,r){let n=[];for(let s of r){let{message:a,encodedData:o,data:i}=await this.readMessageByCid(e,s);if(!a)continue;let c={messageCid:s,message:a};if(o)c.encodedData=o;else if(i){let u=await t.streamToBytes(i);u.byteLength<=xZ&&(c.encodedData=Te.bytesToBase64Url(u))}n.push(c)}return n}async readMessageByCid(e,r){let n=await this.deps.messageStore.get(e,r);if(!n)return{};let s;"encodedData"in n&&(s=n.encodedData,delete n.encodedData);let a;if(n.descriptor.interface==="Records"&&n.descriptor.method==="Write"){let o=n.descriptor?.dataCid;if(o&&this.deps.dataStore){let i=n.descriptor?.recordId;if(i){let c=await this.deps.dataStore.get(e,i,o);c?.dataStream&&(a=c.dataStream)}}}return{message:n,encodedData:s,data:a}}static async streamToBytes(e){let r=e.getReader(),n=[],s=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;n.push(c),s+=c.byteLength}let a=new Uint8Array(s),o=0;for(let i of n)a.set(i,o),o+=i.byteLength;return a}static parseBitPrefix(e){if(!/^[01]*$/.test(e))throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: length must be <= 256, got: ${e.length}`);return Array.from(e,r=>r==="1")}static async authorizeMessagesSync(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await wu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSyncAuthorizationFailed","message failed authorization")}};w();or();w();var fN=Ln(nI(),1);or();pa();w();Mv();ht();var Au=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await no.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:s,permissionGrant:a,messageStore:o}=e;await no.performBaseValidation({incomingMessage:s,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:o});let c=a.scope.protocol,u=s.descriptor.filter?.protocol;if(c!==void 0&&u!==c)throw new ne("ProtocolsGrantAuthorizationQueryProtocolScopeMismatch",`Grant protocol scope ${c} does not match protocol in message ${u}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ne("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};Hs();ht();Xt();w();Lp();zp();function Ni(t){let e=t.indexOf(":");if(e===-1)return;let r=t.substring(0,e),n=t.substring(e+1);return{alias:r,protocolPath:n}}function hf(t){return t.includes(":")}function s1(t){return t.split("/").slice(-1)[0]}function fd(t,e){let r=t.split("/"),n,s=e;for(let a of r){if(!Object.hasOwn(s,a))return;n=s[a],s=n}return n}var sI=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let s=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let u=r,d=["protocolPath",e.protocol];async function l(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await l(y,m);continue}let S=await u.derivePublicKey(m);y.$encryption={rootKeyId:u.rootKeyId,publicKeyJwk:S},await l(y,m)}}return await l(s.structure,d),s}let a=r;async function o(u,d){for(let l in u)if(!l.startsWith("$")){let f=await Ja.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await vn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Ja.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ro();var pd=class t extends xn{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Configure",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),definition:t.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await we.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),s={descriptor:r,authorization:n};return we.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await Au.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:s}=e;Fn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Qa(o)}s!==void 0&&t.validateUses(s,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let s in e){if(!n.test(s))throw new ne("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{Fn(e[s])}catch{throw new ne("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new ne("ProtocolsConfigureInvalidUsesSelfReference",`'uses' alias '${s}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),s=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:s,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ne("ProtocolsConfigureRecordNestingDepthExceeded","Record nesting depth exceeded 10 levels.");for(let s in r){if(s.startsWith("$"))continue;let a=r[s],o;e===""?o=s:o=`${e}/${s}`,a.$role?n.push(o):t.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:s,roles:a,uses:o,types:i}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new ne("ProtocolsConfigureInvalidRefNotAtRoot",`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);t.validateRefNode(r,n,o)}if(r.$size!==void 0){let{min:u=0,max:d}=r.$size;if(d!==void 0&&d<u)throw new ne("ProtocolsConfigureInvalidSize",`Invalid size range found: max limit ${d} less than min limit ${u} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:u,strategy:d}=r.$recordLimit;if(!Number.isInteger(u)||u<1)throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(dm);if(!l.includes(d))throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new fN.default.default,{$allowUndefinedTags:d,$requiredTags:l,...f}=r.$tags;for(let h in f){let p=f[h];if(!u.validateSchema(p)){let m=u.errorsText(u.errors,{dataVar:`${n}/$tags/${h}`});throw new ne("ProtocolsConfigureInvalidTagSchema",`tags schema validation error: ${m}`)}}}let c=r.$actions??[];for(let u=0;u<c.length;u++){let d=c[u];if(d.role!==void 0){if(hf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ne("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne("ProtocolsConfigureInvalidActionOfNotAllowed",`'of' is not allowed at rule set protocol path (${n})`);if(d.who==="recipient"&&d.of===void 0&&d.can.some(f=>!["co-update","co-delete","co-prune"].includes(f)))throw new ne("ProtocolsConfigureInvalidRecipientOfAction","Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who==="author"&&!d.of)throw new ne("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(hf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionUpdateWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes("delete")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionDeleteWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes("prune")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionPruneWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let l=u+1;l<c.length;l++){let f=c[l];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ne("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ne("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let u=n.split("/").pop();i[u]?.encryptionRequired===!0&&c.some(f=>f.who==="anyone"&&f.can.includes("read"))&&console.warn(`ProtocolsConfigure: type '${u}' 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.`)}r.$delivery!==void 0&&(r.$actions===void 0||r.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${r.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),r.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes("update")||d.can.includes("co-update"))&&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 u in r){if(u.startsWith("$"))continue;let d=r[u];if(d.$ref===void 0&&!s.includes(u))throw new ne("ProtocolsConfigureInvalidRuleSetRecordType",`Rule set ${u} is not declared as an allowed type in the protocol definition.`);let l;n===""?l=u:l=`${n}/${u}`,t.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:l,recordTypes:s,roles:a,uses:o,types:i})}}static validateRefNode(e,r,n){let s=e.$ref,a=Ni(s);if(a===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${a.alias}' at protocol path '${r}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let i of o)if(e[i]!==void 0)throw new ne("ProtocolsConfigureInvalidRefNodeHasDirectives",`'$ref' node at protocol path '${r}' must not have '${i}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,s){let a=Ni(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r===void 0||r[a.alias]===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let s in e.types)r[s]={...e.types[s]};for(let s in r){let a=r[s].schema;a!==void 0&&(r[s].schema=Cl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=hi(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:hi(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ht();Xt();var i1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await pd.parse(r)}catch(d){return ut(d,400)}try{await dn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return ut(d,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(d){return ut(d,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getCid(r);for(let d of a)if(await we.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let i=await we.getNewestMessage(a),c=!1;(i===void 0||await we.isNewer(r,i))&&(c=!0,i=r);let u;if(c){let d=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},d,l),u={status:{code:202,detail:"Accepted"}}}else{let d=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),u={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==i){let l=await pd.parse(d),f=t.constructIndexes(l,!1),h=await we.getCid(d);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,d,f)}return u}static constructIndexes(e,r){let{definition:n,...s}=e.message.descriptor,{author:a}=e;return{...s,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:r}}static async authorizeProtocolsConfigure(e,r,n){if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Au.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("ProtocolsConfigureAuthorizationFailed","message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:s}=r;if(s===void 0)return;let a=new Map;for(let o in s){let i=s[o],c=await t.fetchInstalledProtocolDefinition(e,i,n);if(c===void 0)throw new ne("ProtocolsConfigureComposedProtocolNotInstalled",`composed protocol '${i}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let s={interface:"Protocols",method:"Configure",protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[s]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let s in e){if(s.startsWith("$"))continue;let a=e[s],o=r===""?s:`${r}/${s}`;if(a.$ref!==void 0){let c=Ni(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),l=u.structure;for(let f=0;f<d.length;f++){let h=d[f],p=l[h];if(p===void 0)throw new ne("ProtocolsConfigureInvalidRefProtocolPath",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${u.protocol}'.`);if(p.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne("ProtocolsConfigureInvalidRefTargetThroughRef",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${u.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}l=p}}}let i=a.$actions??[];for(let c of i){if(c.role!==void 0){let u=Ni(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let l=fd(u.protocolPath,d.structure);if(l===void 0||!l.$role)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Ni(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(fd(u.protocolPath,d.structure)===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,o,n)}}};w();ht();w();or();ms();Hs();ht();Xt();Ro();var mf=class t extends xn{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&Fn(e.descriptor.filter.protocol),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Ft(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return we.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:hi(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Ir.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Au.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ne("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};ms();Xt();var o1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await mf.parse(r)}catch(o){return ut(o,400)}try{await dn(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code==="AuthenticateJwsMissing"||o.code==="ProtocolsQueryUnauthorized"||o.code==="ProtocolsGrantAuthorizationQueryProtocolScopeMismatch"){let i=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:i}}else return ut(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};Ft(s);let{messages:a}=await this.deps.messageStore.query(e,[s]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:"Protocols",method:"Configure",published:!0,isLatestBaseState:!0},{messages:s}=await this.deps.messageStore.query(e,[n]);return s}};w();or();w();Ya();ht();Xt();w();wa();bi();ht();Xt();async function Fg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(hf(c)){let p=Ni(c);if(p===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses===void 0||s.uses[p.alias]===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role alias '${p.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);u=s.uses[p.alias],d=p.protocolPath;let m=await o(t,u,a,i),y=fd(d,m.structure);if(y===void 0||!y.$role)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else{let p=fd(c,s.structure);if(p===void 0||!p.$role)throw new ne("ProtocolAuthorizationNotARole",`Protocol path ${c} does not match role record type.`)}let l={interface:"Records",method:"Write",protocol:u,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Gt.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new ne("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function Zre(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await xt.fetchInitialRecordsWrite(r,t,s);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push("co-prune"),e.author===a.author&&o.push("prune")):(o.push("co-delete"),e.author===a.author&&o.push("delete")),o;case"Count":return["read"];case"Query":return["read"];case"Read":return["read"];case"Subscribe":return["read"];case"Write":let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?["squash","create"]:["create"];{let u=e.message.recordId,d=await xt.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Gg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await Zre(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new ne("ProtocolAuthorizationActionRulesNotFound",`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let l of u){if(!l.can.some(p=>i.includes(p)))continue;if(l.who==="anyone")return;if(c===void 0)continue;if(d!==void 0){if(l.role===d)return;continue}if(l.who==="recipient"&&l.of===void 0){let p;if(e.message.descriptor.method==="Write"?p=e.message:p=n[n.length-1],p.descriptor.recipient===c)return;continue}if(await Yre(c,l,n,a))return}throw new ne("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Yre(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(hf(s)&&n?.uses!==void 0){let o=Ni(s);if(o!==void 0){let i=n.uses[o.alias];i!==void 0&&(a=r.find(c=>c.descriptor.protocol===i&&c.descriptor.protocolPath===o.protocolPath))}}else a=r.find(o=>o.descriptor.protocolPath===s);if(a===void 0)return!1;if(e.who==="recipient")return t===a.descriptor.recipient;{let o=(await xt.parse(a)).author;return t===o}}w();bi();ht();Xt();async function Rh(t,e,r){let n={interface:"Records",method:"Write",recordId:e},{messages:s}=await r.query(t,[n]);return s.length===0?void 0:await xt.getInitialWrite(s)}async function Wg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Rh(t,s,r);if(a===void 0)throw new ne("ProtocolAuthorizationParentNotFoundConstructingRecordChain",`Unexpected error that should never trigger: no parent found with ID ${s} when constructing record chain.`);n.push(a),s=a.descriptor.parentId}return n.reverse()}async function iI(t,e,r){let n=await Rh(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}w();var pN=Ln(nI(),1);wa();On();ht();Xt();async function hN(t,e,r,n,s){let a=e.message.descriptor.protocolPath,o=s1(a),i=e.message.descriptor.parentId;if(i===void 0){if(a!==o)throw new ne("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await Qre(t,c,a,r,n,s),d={isLatestBaseState:!0,interface:"Records",method:"Write",protocol:u,recordId:i},{messages:l}=await r.query(t,[d]),f=l[0];if(f===void 0)throw u!==c?new ne("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Qre(t,e,r,n,s,a){let o=r.split("/");if(o.length<=1)return e;let i=await s(t,e,n,a),c=i.structure[o[0]];if(c?.$ref!==void 0){let u=Ni(c.$ref);if(u!==void 0&&i.uses!==void 0){let d=i.uses[u.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function mN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=s1(o),c=await Xre(t,o,r,n,s,a);ene(e,c,i)}async function Xre(t,e,r,n,s,a){let o=e.split("/"),i=r.structure[o[0]];if(i?.$ref!==void 0&&o.length===1){let c=Ni(i.$ref);if(c!==void 0&&r.uses!==void 0){let u=r.uses[c.alias];if(u!==void 0)return(await s(t,u,n,a)).types}}return r.types}function ene(t,e,r){let n=r??s1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne("ProtocolAuthorizationInvalidType",`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=t.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ne("ProtocolAuthorizationInvalidSchema",`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:i}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(i))throw new ne("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ne("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function yN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new ne("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new ne("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function gN(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:s}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...i}=e.$tags,c=a||!1,u=o||[],d=new pN.default.default,l=d.compile({type:"object",properties:i,required:u,additionalProperties:c});if(!l(r)){let h=d.errorsText(l.errors,{dataVar:`${n}/${s}/$tags`});throw new ne("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function wN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new ne("ProtocolAuthorizationRoleMissingRecipient","Role records must have a recipient");let o=s.message.descriptor.protocolPath,i={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:s.message.descriptor.protocol,protocolPath:o,recipient:a},c=_e.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Gt.constructPrefixFilterAsRangeFilter(c);i.contextId=f}let{messages:u}=await n.query(t,[i]);if(u.filter(f=>f.recordId!==s.message.recordId).length>0)throw new ne("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function vN(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=r.$recordLimit,i=e.message.descriptor.protocolPath,c={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:i},u=_e.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Gt.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new ne("ProtocolAuthorizationRecordLimitExceeded",`record limit of ${a} reached at protocol path '${i}'${u!==""?` under parent context '${u}'`:""}: new records are rejected until existing records are deleted.`):new ne("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function bN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne("ProtocolAuthorizationSquashNotEnabled",`squash writes are not enabled at protocol path '${t.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await t.isInitialWrite())throw new ne("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function PN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ne("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Qs=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await iI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await mN(e,r.message,o,n,i,a),await hN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await wN(e,r,c,n),yN(r,c),gN(r,c),await PN(r,c),await bN(r,c),await vN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Rh(e,r.message.recordId,n),o;a===void 0?o=await Wg(e,r.message.descriptor.parentId,n):o=await Wg(e,r.message.recordId,n);let i=await iI(e,r,n),c=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,i,s),u=t.getRuleSet(r.message.descriptor.protocolPath,c),d=t.createBoundFetchDefinition(s);await Fg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Gg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Wg(e,n.message.recordId,s),i=await Rh(e,n.message.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await Fg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Gg(e,r,d,o,s,u)}static async authorizeQueryOrSubscribe(e,r,n,s){let{protocol:a,protocolPath:o,contextId:i}=r.message.descriptor.filter,c=await t.fetchProtocolDefinition(e,a,n,void 0,s),u=t.getRuleSet(o,c),d=t.createBoundFetchDefinition(s);await Fg(e,r,a,i,c,n,d),await Gg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Wg(e,r.message.descriptor.recordId,s),i=await Rh(e,r.message.descriptor.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await Fg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Gg(e,r,d,o,s,u)}static async fetchProtocolDefinition(e,r,n,s,a){if(a!==void 0){let u=a.getDefinition(r);if(u!==void 0)return u}let o={interface:"Protocols",method:"Configure",protocol:r};s!==void 0?o.messageTimestamp={lte:s}:o.isLatestBaseState=!0;let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new ne("ProtocolAuthorizationProtocolNotFound",`unable to find protocol definition for ${r}`);return i[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,s,a)=>t.fetchProtocolDefinition(r,n,s,a,e)}static getRuleSet(e,r){let n=fd(e,r.structure);if(n===void 0)throw new ne("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};On();Xt();var a1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(a){return ut(a,400)}let s;if(_e.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ut(a,401)}n.author===e?s=await this.countRecordsAsOwner(e,n):s=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:s}}async countRecordsAsOwner(e,r){let{filter:n}=r.message.descriptor,s={..._e.convertFilter(n),interface:"Records",method:"Write",isLatestBaseState:!0};return this.deps.messageStore.count(e,[s])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,s=[];return _e.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),_e.filterIncludesUnpublishedRecords(n)&&(_e.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),_e.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),_e.shouldBuildUnpublishedRecipientFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,s)}async countPublishedRecords(e,r){let n=t.buildPublishedRecordsFilter(r);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{..._e.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Xt();or();On();w();or();pa();On();Xa();ms();Hs();Xt();var hd=class t extends xn{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=yt.getCurrentTimestamp(),s={interface:"Records",method:"Delete",messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),new t(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u}=e.descriptor,d={isLatestBaseState:!0,protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u,contextId:e.contextId,author:this.author,...n};return Ft(d),d}async authorizeDelegate(e,r){let n=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Xa();bi();w();var c1=class t{constructor(e,r){this.resumableTaskStore=e;this.resumableTaskHandlers={RecordsDelete:async n=>await r.performRecordsDelete(n),RecordsSquash:async n=>await r.performRecordsSquash(n)}}static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;async run(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,r);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,r)},t.timeoutExtensionFrequencyInSeconds*1e3);let s=this.resumableTaskHandlers[e.task.name];await s(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{t.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 r=e;for(;r.length>0;){let n=r;r=[];for(let s of n)try{await this.runWithAutomaticTimeoutExtension(s)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",s),r.push(s)}}}};var d1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hd.parse(r)}catch(u){return ut(u,400)}try{await dn(r.authorization,this.deps.didResolver)}catch(u){return ut(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getNewestMessage(a);if(!_e.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await xt.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ut(u,401)}return await this.deps.resumableTaskManager.run({name:"RecordsDelete",data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,s,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await kn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:s})}else await Qs.authorizeDelete(e,r,n,s,a)}};w();Al();or();On();bi();Ya();Xt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ut(o,400)}let s,a;if(_e.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);s=o.messages,a=o.cursor}else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ut(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);s=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);s=o.messages,a=o.cursor}}for(let o of s)if(!await xt.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:s,cursor:a}}convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:s,pagination:a}=r.message.descriptor,o={..._e.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0},i=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],i,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:s,filter:a}=r.message.descriptor,o=[];_e.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),_e.filterIncludesUnpublishedRecords(a)&&(_e.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),_e.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),_e.shouldBuildUnpublishedRecipientFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let i=this.convertDateSort(n);return this.deps.messageStore.query(e,o,i,s)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:s}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,s)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Hd();hn();or();On();Xa();w();Al();or();pa();On();Xa();ms();Hs();ht();Xt();var Vg=class t extends xn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsReadParseFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:s,protocolRole:a,dateSort:o}=e,i=yt.getCurrentTimestamp();if(e.filter.published===!1&&(o==="publishedAscending"||o==="publishedDescending"))throw new ne("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:_e.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};Ft(c);let u;n!==void 0&&(u=await we.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return we.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};bi();ht();Xt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Vg.parse(r)}catch(l){return ut(l,400)}try{n.author!==void 0&&await dn(r.authorization,this.deps.didResolver)}catch(l){return ut(l,401)}let s={interface:"Records",isLatestBaseState:!0,..._e.convertFilter(r.descriptor.filter)},a=_e.convertDateSort(r.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[s],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let i=o[0];if(i.descriptor.method==="Delete"){let l=i,f=l.descriptor.recordId,h=await xt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ut(new ne("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await xt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await xt.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ut(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await xt.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ut(l,401)}let u;if(c.encodedData!==void 0){let l=Te.base64UrlToBytes(c.encodedData);u=rs.fromBytes(l),delete c.encodedData}else{let l=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(l?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};u=l.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await xt.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,r,n,s,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s);let{descriptor:o}=n.message;if(r.author!==e){if(o.published===!0)return;if(r.author!==void 0&&(r.author===o.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await Ir.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await kn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:s})}else await Qs.authorizeRead(e,r,n,s,a)}}};w();Al();or();On();w();or();pa();On();Xa();ms();Hs();ht();Xt();Ro();var yf=class t extends xn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await _e.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Fn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Qa(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Subscribe",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:_e.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Ft(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Xr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};bi();Ya();ht();Xt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await yf.parse(r)}catch(f){return ut(f,400)}let a=[],o=[];if(_e.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await dn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ut(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await we.getCid(r),{cursor:c}=s.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,i,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code==="EventLogProgressGap"){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h!==void 0?{code:"ProgressGap",...h}:void 0}}return ut(f,500)}let u=await this.deps.eventLog.subscribe(e,i,n,{filters:a}),d,l;try{let{dateSort:f,pagination:h}=s.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);d=m.messages,l=m.cursor;for(let y of d)if(!await xt.isInitialWrite(y)){let v=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete v.encodedData,y.initialWrite=v}}catch(f){return await u.close(),ut(f,500)}return{status:{code:200,detail:"OK"},subscription:u,entries:d,cursor:l}}static convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{..._e.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return _e.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),_e.filterIncludesUnpublishedRecords(n)&&(_e.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({..._e.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),_e.shouldProtocolAuthorize(e.signaturePayload)&&r.push({..._e.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),_e.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({..._e.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{..._e.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{..._e.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return _e.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),_e.filterIncludesUnpublishedRecords(s)&&(_e.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({..._e.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),_e.shouldProtocolAuthorize(e.signaturePayload)&&r.push({..._e.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),_e.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({..._e.convertFilter(s,n),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{..._e.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),_e.shouldProtocolAuthorize(r.signaturePayload)&&await Qs.authorizeQueryOrSubscribe(e,r,n,s)}};w();Hc();Hd();hn();wa();or();On();Xa();bi();Ya();w();wa();or();On();bi();Xt();var Dh=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:s}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=s}async performRecordsDelete({tenant:e,message:r}){let n={interface:"Records",recordId:r.descriptor.recordId},{messages:s}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(s);if(!_e.canPerformDeleteAgainstRecord(r,a))return;let o=await hd.parse(r),i=await xt.getInitialWrite(s),c=o.constructIndexes(i),u=await we.getCid(r);await this.messageStore.put(e,r,c),await this.stateIndex.insert(e,u,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:i},c,u),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,s,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:s,messageTimestamp:a}=r.descriptor,o={interface:"Records",protocol:n,protocolPath:s},i=_e.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Gt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;_e.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f!==void 0?f.push(d):u.set(l,[d])}for(let[d,l]of u){if(d===r.recordId)continue;let f=await we.getNewestMessage(l);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,l,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,s){if(n.descriptor.method!=="Write")return;let a=n;a.descriptor.dataSize<=jo.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==s.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,s,a){let o={interface:"Records",parentId:r},{messages:i}=await n.query(e,[o]),c=new Map;for(let u of i){let d;_e.isRecordsWrite(u)?d=u.recordId:d=u.descriptor.recordId;let l=c.get(d);l?l.push(u):c.set(d,[u])}for(let u of c.keys())await t.purgeRecordDescendants(e,u,n,s,a);for(let u of c.keys())await t.purgeRecordMessages(e,c.get(u),n,s,a)}static async purgeRecordMessages(e,r,n,s,a){let o=r.filter(u=>u.descriptor.method==="Write"),i=await we.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>we.getCid(u)));await a.delete(e,c),await Promise.all(c.map(u=>n.delete(e,u)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,s,a,o){let i=[];for(let c of r){if(await we.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await we.getCid(c);if(await s.delete(e,d),await xt.isInitialWrite(c)){let p=await(await xt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await we.getCid(c);i.push(f)}}await o.delete(e,i)}}};ht();Xt();var p1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await xt.parse(r),await Qs.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return ut(p,400)}try{await dn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(p){return ut(p,401)}let a={interface:"Records",recordId:r.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),i=await s.isInitialWrite(),c;if(!i)try{c=await xt.getInitialWrite(o),xt.verifyEqualityOfImmutableProperties(c,r)}catch(p){return ut(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return ut(p,409)}let u=await we.getNewestMessage(o),d=!1,l;if(u===void 0||await we.isNewer(r,u)?(d=!0,l=r):l=u,!d){let p=!1;if(u!==void 0&&n!==void 0&&await xt.isInitialWrite(u)){let y=!!u.encodedData,S=this.deps.dataStore?!!await this.deps.dataStore.get(e,s.message.recordId,r.descriptor.dataCid):!1;p=!y&&!S}if(!p)return{status:{code:409,detail:"Conflict"}}}let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(u?.descriptor.method==="Delete")throw new ne("RecordsWriteNotAllowedAfterDelete","RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,r,this.deps.messageStore);let p=!1,m=r;if(n!==void 0)m=await this.processMessageWithDataStream(e,r,n),p=!0;else if(!i){let v=u;m=await this.processMessageWithoutDataStream(e,r,v),p=!0}let y=await s.constructIndexes(p);await this.deps.messageStore.put(e,m,y);let S=await we.getCid(r);await this.deps.stateIndex.insert(e,S,y),this.deps.eventLog!==void 0&&p&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,S)}catch(p){if(p instanceof ne&&(p.code==="RecordsWriteMissingEncodedDataInPrevious"||p.code==="RecordsWriteMissingDataInPrevious"||p.code==="RecordsWriteNotAllowedAfterDelete"||p.code==="RecordsWriteDataCidMismatch"||p.code==="RecordsWriteDataSizeMismatch"||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return ut(p,400);throw p}let h={status:i&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Dh.deleteAllOlderMessagesButKeepInitialWrite(e,o,l,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:"RecordsSquash",data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,s,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=Te.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=jo.maxDataSizeAllowedToBeEncoded){let a=await rs.toBytes(n),o=await Dr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=rs.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Dr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,o)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,i,c.dataSize)}catch(i){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),i}}return s}async processMessageWithoutDataStream(e,r,n){let s={...r},{dataCid:a,dataSize:o}=r.descriptor;if(t.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=jo.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)s.encodedData=n.encodedData;else throw new ne("RecordsWriteMissingEncodedDataInPrevious","No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new ne("RecordsWriteMissingDataInPrevious","No dataStream was provided and unable to get data from previous message");return s}static validateDataIntegrity(e,r,n,s){if(e!==n)throw new ne("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new ne("RecordsWriteDataSizeMismatch",`actual data size ${s} bytes does not match dataSize in descriptor: ${r}`)}async enforceSquashBackstop(e,r){if(r.descriptor.protocol===void 0||r.descriptor.protocolPath===void 0)return;let n;try{n=await Qs.fetchProtocolDefinition(e,r.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,d);return}let s=r.descriptor.protocolPath.split("/"),a=n.structure[s[0]];for(let d=1;d<s.length&&a!==void 0;d++)a=a[s[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=_e.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Gt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:-1},{limit:1});if(c.length===0)return;let u=c[0];if(r.descriptor.messageTimestamp<=u.descriptor.messageTimestamp)throw new ne("ProtocolAuthorizationSquashBackstop",`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${u.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new ne("RecordsWriteOwnerAndTenantMismatch",`Owner ${r.owner} must be the same as tenant ${e} when specified.`);if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.isSignedByOwnerDelegate&&await r.authorizeOwnerDelegate(n),r.owner===void 0){if(r.author===e)return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Ir.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await kn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Qs.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};w();var rne=Object.create,BI=Object.defineProperty,nne=Object.getOwnPropertyDescriptor,sne=Object.getOwnPropertyNames,ine=Object.getPrototypeOf,one=Object.prototype.hasOwnProperty,zt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),NI=(t,e)=>{for(var r in e)BI(t,r,{get:e[r],enumerable:!0})},ane=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sne(e))!one.call(t,s)&&s!==r&&BI(t,s,{get:()=>e[s],enumerable:!(n=nne(e,s))||n.enumerable});return t},Df=(t,e,r)=>(r=t!=null?rne(ine(t)):{},ane(e||!t||!t.__esModule?BI(r,"default",{value:t,enumerable:!0}):r,t)),cne=zt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),s=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),a=i=>i===1/0||s(i),o=class NU{constructor({max:c=1/0,ttl:u,updateAgeOnGet:d=!1,checkAgeOnGet:l=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,u!==void 0&&!a(u))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=u,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!l,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(c,u){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let l in this.expirations){this.setTimer(l,l-n());break}},u);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==NU.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[u,d]of c)this.dispose(d,u,"delete")}setTTL(c,u=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let l=this.expirations[d];!l||l.length<=1?delete this.expirations[d]:this.expirations[d]=l.filter(f=>f!==c)}if(u!==1/0){let l=Math.floor(n()+u);this.expirationMap.set(c,l),this.expirations[l]||(this.expirations[l]=[],this.setTimer(l,u)),this.expirations[l].push(c)}else this.expirationMap.set(c,1/0)}set(c,u,{ttl:d=this.ttl,noUpdateTTL:l=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){l||this.setTTL(c,d);let h=this.data.get(c);h!==u&&(this.data.set(c,u),f||this.dispose(h,c,"set"))}else this.setTTL(c,d),this.data.set(c,u);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let u=this.expirationMap.get(c);return u===1/0?u:u!==void 0?Math.max(0,Math.ceil(u-n())):0}get(c,{updateAgeOnGet:u=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:l=this.checkAgeOnGet}={}){let f=this.data.get(c);if(l&&this.getRemainingTTL(c)===0){this.delete(c);return}return u&&this.setTTL(c,d),f}dispose(c,u){}delete(c){let u=this.expirationMap.get(c);if(u!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let l=this.expirations[u];return l&&(l.length<=1?delete this.expirations[u]:this.expirations[u]=l.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let u=this.expirations[c];if(this.size-u.length>=this.max){delete this.expirations[c];let d=[];for(let l of u)d.push([l,this.data.get(l)]),this.data.delete(l),this.expirationMap.delete(l);for(let[l,f]of d)this.dispose(f,l,"evict")}else{let d=this.size-this.max,l=[];for(let f of u.splice(0,d))l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let u in this.expirations){if(u==="Infinity"||u>c)return;let d=[...this.expirations[u]||[]],l=[];delete this.expirations[u];for(let f of d)l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let u of this.expirations[c])yield[u,this.data.get(u)]}*keys(){for(let c in this.expirations)for(let u of this.expirations[c])yield u}*values(){for(let c in this.expirations)for(let u of this.expirations[c])yield this.data.get(u)}[Symbol.iterator](){return this.entries()}};e.exports=o}),dne=zt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,s)=>Object.assign(n,s),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}}),_c=zt((t,e)=>{"use strict";e.exports=class extends Error{constructor(r,n){super(r||""),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)}}}),une=zt(t=>{"use strict";t.byteLength=c,t.toByteArray=d,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=s.length;a<o;++a)e[a]=s[a],r[s.charCodeAt(a)]=a;var a,o;r[45]=62,r[95]=63;function i(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 S=y===m?0:4-y%4;return[y,S]}function c(p){var m=i(p),y=m[0],S=m[1];return(y+S)*3/4-S}function u(p,m,y){return(m+y)*3/4-y}function d(p){var m,y=i(p),S=y[0],v=y[1],E=new n(u(p,S,v)),_=0,I=v>0?S-4:S,R;for(R=0;R<I;R+=4)m=r[p.charCodeAt(R)]<<18|r[p.charCodeAt(R+1)]<<12|r[p.charCodeAt(R+2)]<<6|r[p.charCodeAt(R+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return v===2&&(m=r[p.charCodeAt(R)]<<2|r[p.charCodeAt(R+1)]>>4,E[_++]=m&255),v===1&&(m=r[p.charCodeAt(R)]<<10|r[p.charCodeAt(R+1)]<<4|r[p.charCodeAt(R+2)]>>2,E[_++]=m>>8&255,E[_++]=m&255),E}function l(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var S,v=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),v.push(l(S));return v.join("")}function h(p){for(var m,y=p.length,S=y%3,v=[],E=16383,_=0,I=y-S;_<I;_+=E)v.push(f(p,_,_+E>I?I:_+E));return S===1?(m=p[y-1],v.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],v.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),v.join("")}}),lne=zt(t=>{t.read=function(e,r,n,s,a){var o,i,c=a*8-s-1,u=(1<<c)-1,d=u>>1,l=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=c;l>0;o=o*256+e[r+f],f+=h,l-=8);for(i=o&(1<<-l)-1,o>>=-l,l+=s;l>0;i=i*256+e[r+f],f+=h,l-=8);if(o===0)o=1-d;else{if(o===u)return i?NaN:(p?-1:1)*(1/0);i=i+Math.pow(2,s),o=o-d}return(p?-1:1)*i*Math.pow(2,o-s)},t.write=function(e,r,n,s,a,o){var i,c,u,d=o*8-a-1,l=(1<<d)-1,f=l>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:o-1,m=s?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(c=isNaN(r)?1:0,i=l):(i=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-i))<1&&(i--,u*=2),i+f>=1?r+=h/u:r+=h*Math.pow(2,1-f),r*u>=2&&(i++,u/=2),i+f>=l?(c=0,i=l):i+f>=1?(c=(r*u-1)*Math.pow(2,a),i=i+f):(c=r*Math.pow(2,f-1)*Math.pow(2,a),i=0));a>=8;e[n+p]=c&255,p+=m,c/=256,a-=8);for(i=i<<a|c,d+=a;d>0;e[n+p]=i&255,p+=m,i/=256,d-=8);e[n+p-m]|=y*128}}),UI=zt(t=>{"use strict";var e=une(),r=lne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=v,t.INSPECT_MAX_BYTES=50;var s=2147483647;t.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function o(T){if(T>s)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,i.prototype),M}function i(T,M,L){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(T)}return c(T,M,L)}i.poolSize=8192;function c(T,M,L){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return p(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Se(T,ArrayBuffer)||T&&Se(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Se(T,SharedArrayBuffer)||T&&Se(T.buffer,SharedArrayBuffer)))return m(T,M,L);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return i.from(te,M,L);let ae=y(T);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return i.from(T[Symbol.toPrimitive]("string"),M,L);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}i.from=function(T,M,L){return c(T,M,L)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function u(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,L){return u(T),T<=0?o(T):M!==void 0?typeof L=="string"?o(T).fill(M,L):o(T).fill(M):o(T)}i.alloc=function(T,M,L){return d(T,M,L)};function l(T){return u(T),o(T<0?0:S(T)|0)}i.allocUnsafe=function(T){return l(T)},i.allocUnsafeSlow=function(T){return l(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!i.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let L=E(T,M)|0,te=o(L),ae=te.write(T,M);return ae!==L&&(te=te.slice(0,ae)),te}function h(T){let M=T.length<0?0:S(T.length)|0,L=o(M);for(let te=0;te<M;te+=1)L[te]=T[te]&255;return L}function p(T){if(Se(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return h(T)}function m(T,M,L){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(L||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&L===void 0?te=new Uint8Array(T):L===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,L),Object.setPrototypeOf(te,i.prototype),te}function y(T){if(i.isBuffer(T)){let M=S(T.length)|0,L=o(M);return L.length===0||T.copy(L,0,0,M),L}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):h(T);if(T.type==="Buffer"&&Array.isArray(T.data))return h(T.data)}function S(T){if(T>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return T|0}function v(T){return+T!=T&&(T=0),i.alloc(+T)}i.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==i.prototype},i.compare=function(T,M){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),Se(M,Uint8Array)&&(M=i.from(M,M.offset,M.byteLength)),!i.isBuffer(T)||!i.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let L=T.length,te=M.length;for(let ae=0,he=Math.min(L,te);ae<he;++ae)if(T[ae]!==M[ae]){L=T[ae],te=M[ae];break}return L<te?-1:te<L?1:0},i.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return i.alloc(0);let L;if(M===void 0)for(M=0,L=0;L<T.length;++L)M+=T[L].length;let te=i.allocUnsafe(M),ae=0;for(L=0;L<T.length;++L){let he=T[L];if(Se(he,Uint8Array))ae+he.length>te.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(te,ae)):Uint8Array.prototype.set.call(te,he,ae);else if(i.isBuffer(he))he.copy(te,ae);else throw new TypeError('"list" argument must be an Array of Buffers');ae+=he.length}return te};function E(T,M){if(i.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Se(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let L=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&L===0)return 0;let ae=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return L;case"utf8":case"utf-8":return ge(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return qe(T).length;default:if(ae)return te?-1:ge(T).length;M=(""+M).toLowerCase(),ae=!0}}i.byteLength=E;function _(T,M,L){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((L===void 0||L>this.length)&&(L=this.length),L<=0)||(L>>>=0,M>>>=0,L<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,M,L);case"utf8":case"utf-8":return D(this,M,L);case"ascii":return x(this,M,L);case"latin1":case"binary":return P(this,M,L);case"base64":return X(this,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,M,L);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}i.prototype._isBuffer=!0;function I(T,M,L){let te=T[M];T[M]=T[L],T[L]=te}i.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)I(this,M,M+1);return this},i.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)I(this,M,M+3),I(this,M+1,M+2);return this},i.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)I(this,M,M+7),I(this,M+1,M+6),I(this,M+2,M+5),I(this,M+3,M+4);return this},i.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?D(this,0,T):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(T){if(!i.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:i.compare(this,T)===0},i.prototype.inspect=function(){let T="",M=t.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(i.prototype[n]=i.prototype.inspect),i.prototype.compare=function(T,M,L,te,ae){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),!i.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),L===void 0&&(L=T?T.length:0),te===void 0&&(te=0),ae===void 0&&(ae=this.length),M<0||L>T.length||te<0||ae>this.length)throw new RangeError("out of range index");if(te>=ae&&M>=L)return 0;if(te>=ae)return-1;if(M>=L)return 1;if(M>>>=0,L>>>=0,te>>>=0,ae>>>=0,this===T)return 0;let he=ae-te,xe=L-M,Ot=Math.min(he,xe),Un=this.slice(te,ae),Or=T.slice(M,L);for(let hr=0;hr<Ot;++hr)if(Un[hr]!==Or[hr]){he=Un[hr],xe=Or[hr];break}return he<xe?-1:xe<he?1:0};function R(T,M,L,te,ae){if(T.length===0)return-1;if(typeof L=="string"?(te=L,L=0):L>2147483647?L=2147483647:L<-2147483648&&(L=-2147483648),L=+L,et(L)&&(L=ae?0:T.length-1),L<0&&(L=T.length+L),L>=T.length){if(ae)return-1;L=T.length-1}else if(L<0)if(ae)L=0;else return-1;if(typeof M=="string"&&(M=i.from(M,te)),i.isBuffer(M))return M.length===0?-1:N(T,M,L,te,ae);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(T,M,L):Uint8Array.prototype.lastIndexOf.call(T,M,L):N(T,[M],L,te,ae);throw new TypeError("val must be string, number or Buffer")}function N(T,M,L,te,ae){let he=1,xe=T.length,Ot=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;he=2,xe/=2,Ot/=2,L/=2}function Un(hr,ir){return he===1?hr[ir]:hr.readUInt16BE(ir*he)}let Or;if(ae){let hr=-1;for(Or=L;Or<xe;Or++)if(Un(T,Or)===Un(M,hr===-1?0:Or-hr)){if(hr===-1&&(hr=Or),Or-hr+1===Ot)return hr*he}else hr!==-1&&(Or-=Or-hr),hr=-1}else for(L+Ot>xe&&(L=xe-Ot),Or=L;Or>=0;Or--){let hr=!0;for(let ir=0;ir<Ot;ir++)if(Un(T,Or+ir)!==Un(M,ir)){hr=!1;break}if(hr)return Or}return-1}i.prototype.includes=function(T,M,L){return this.indexOf(T,M,L)!==-1},i.prototype.indexOf=function(T,M,L){return R(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return R(this,T,M,L,!1)};function $(T,M,L,te){L=Number(L)||0;let ae=T.length-L;te?(te=Number(te),te>ae&&(te=ae)):te=ae;let he=M.length;te>he/2&&(te=he/2);let xe;for(xe=0;xe<te;++xe){let Ot=parseInt(M.substr(xe*2,2),16);if(et(Ot))return xe;T[L+xe]=Ot}return xe}function F(T,M,L,te){return Et(ge(M,T.length-L),T,L,te)}function z(T,M,L,te){return Et(Me(M),T,L,te)}function B(T,M,L,te){return Et(qe(M),T,L,te)}function W(T,M,L,te){return Et(Le(M,T.length-L),T,L,te)}i.prototype.write=function(T,M,L,te){if(M===void 0)te="utf8",L=this.length,M=0;else if(L===void 0&&typeof M=="string")te=M,L=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(L)?(L=L>>>0,te===void 0&&(te="utf8")):(te=L,L=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ae=this.length-M;if((L===void 0||L>ae)&&(L=ae),T.length>0&&(L<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let he=!1;for(;;)switch(te){case"hex":return $(this,T,M,L);case"utf8":case"utf-8":return F(this,T,M,L);case"ascii":case"latin1":case"binary":return z(this,T,M,L);case"base64":return B(this,T,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,M,L);default:if(he)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(T,M,L){return M===0&&L===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,L))}function D(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],xe=null,Ot=he>239?4:he>223?3:he>191?2:1;if(ae+Ot<=L){let Un,Or,hr,ir;switch(Ot){case 1:he<128&&(xe=he);break;case 2:Un=T[ae+1],(Un&192)===128&&(ir=(he&31)<<6|Un&63,ir>127&&(xe=ir));break;case 3:Un=T[ae+1],Or=T[ae+2],(Un&192)===128&&(Or&192)===128&&(ir=(he&15)<<12|(Un&63)<<6|Or&63,ir>2047&&(ir<55296||ir>57343)&&(xe=ir));break;case 4:Un=T[ae+1],Or=T[ae+2],hr=T[ae+3],(Un&192)===128&&(Or&192)===128&&(hr&192)===128&&(ir=(he&15)<<18|(Un&63)<<12|(Or&63)<<6|hr&63,ir>65535&&ir<1114112&&(xe=ir))}}xe===null?(xe=65533,Ot=1):xe>65535&&(xe-=65536,te.push(xe>>>10&1023|55296),xe=56320|xe&1023),te.push(xe),ae+=Ot}return b(te)}var C=4096;function b(T){let M=T.length;if(M<=C)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=C));return L}function x(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]&127);return te}function P(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]);return te}function k(T,M,L){let te=T.length;(!M||M<0)&&(M=0),(!L||L<0||L>te)&&(L=te);let ae="";for(let he=M;he<L;++he)ae+=wt[T[he]];return ae}function A(T,M,L){let te=T.slice(M,L),ae="";for(let he=0;he<te.length-1;he+=2)ae+=String.fromCharCode(te[he]+te[he+1]*256);return ae}i.prototype.slice=function(T,M){let L=this.length;T=~~T,M=M===void 0?L:~~M,T<0?(T+=L,T<0&&(T=0)):T>L&&(T=L),M<0?(M+=L,M<0&&(M=0)):M>L&&(M=L),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,i.prototype),te};function O(T,M,L){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>L)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return te},i.prototype.readUintBE=i.prototype.readUIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T+--M],ae=1;for(;M>0&&(ae*=256);)te+=this[T+--M]*ae;return te},i.prototype.readUint8=i.prototype.readUInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]|this[T+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]<<8|this[T+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},i.prototype.readBigUInt64LE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ae=this[++T]+this[++T]*2**8+this[++T]*2**16+L*2**24;return BigInt(te)+(BigInt(ae)<<BigInt(32))}),i.prototype.readBigUInt64BE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ae=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L;return(BigInt(te)<<BigInt(32))+BigInt(ae)}),i.prototype.readIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return ae*=128,te>=ae&&(te-=Math.pow(2,8*M)),te},i.prototype.readIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=M,ae=1,he=this[T+--te];for(;te>0&&(ae*=256);)he+=this[T+--te]*ae;return ae*=128,he>=ae&&(he-=Math.pow(2,8*M)),he},i.prototype.readInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},i.prototype.readInt16LE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T]|this[T+1]<<8;return L&32768?L|4294901760:L},i.prototype.readInt16BE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T+1]|this[T]<<8;return L&32768?L|4294901760:L},i.prototype.readInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},i.prototype.readInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},i.prototype.readBigInt64LE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(L<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),i.prototype.readBigInt64BE=St(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L)}),i.prototype.readFloatLE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!0,23,4)},i.prototype.readFloatBE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!1,23,4)},i.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!0,52,8)},i.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!1,52,8)};function q(T,M,L,te,ae,he){if(!i.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ae||M<he)throw new RangeError('"value" argument is out of bounds');if(L+te>T.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;q(this,T,M,L,xe,0)}let ae=1,he=0;for(this[M]=T&255;++he<L&&(ae*=256);)this[M+he]=T/ae&255;return M+L},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;q(this,T,M,L,xe,0)}let ae=L-1,he=1;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)this[M+ae]=T/he&255;return M+L},i.prototype.writeUint8=i.prototype.writeUInt8=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,1,255,0),this[M]=T&255,M+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function G(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,L}function V(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L+7]=he,he=he>>8,T[L+6]=he,he=he>>8,T[L+5]=he,he=he>>8,T[L+4]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=xe,xe=xe>>8,T[L+2]=xe,xe=xe>>8,T[L+1]=xe,xe=xe>>8,T[L]=xe,L+8}i.prototype.writeBigUInt64LE=St(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=St(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Ot=Math.pow(2,8*L-1);q(this,T,M,L,Ot-1,-Ot)}let ae=0,he=1,xe=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&xe===0&&this[M+ae-1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Ot=Math.pow(2,8*L-1);q(this,T,M,L,Ot-1,-Ot)}let ae=L-1,he=1,xe=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&xe===0&&this[M+ae+1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},i.prototype.writeInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},i.prototype.writeInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||q(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},i.prototype.writeBigInt64LE=St(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=St(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function H(T,M,L,te,ae,he){if(L+te>T.length)throw new RangeError("Index out of range");if(L<0)throw new RangeError("Index out of range")}function Y(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return Y(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return Y(this,T,M,!1,L)};function K(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return K(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return K(this,T,M,!1,L)},i.prototype.copy=function(T,M,L,te){if(!i.isBuffer(T))throw new TypeError("argument should be a Buffer");if(L||(L=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<L&&(te=L),te===L||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-L&&(te=T.length-M+L);let ae=te-L;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,L,te):Uint8Array.prototype.set.call(T,this.subarray(L,te),M),ae},i.prototype.fill=function(T,M,L,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,L=this.length):typeof L=="string"&&(te=L,L=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!i.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let he=T.charCodeAt(0);(te==="utf8"&&he<128||te==="latin1")&&(T=he)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<L)throw new RangeError("Out of range index");if(L<=M)return this;M=M>>>0,L=L===void 0?this.length:L>>>0,T||(T=0);let ae;if(typeof T=="number")for(ae=M;ae<L;++ae)this[ae]=T;else{let he=i.isBuffer(T)?T:i.from(T,te),xe=he.length;if(xe===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%xe]}return this};var Q={};function se(T,M,L){Q[T]=class extends L{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,L){let te=`The value of "${T}" is out of range.`,ae=L;return Number.isInteger(L)&&Math.abs(L)>2**32?ae=re(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=re(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function re(T){let M="",L=T.length,te=T[0]==="-"?1:0;for(;L>=te+4;L-=3)M=`_${T.slice(L-3,L)}${M}`;return`${T.slice(0,L)}${M}`}function Z(T,M,L){le(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&pe(M,T.length-(L+1))}function de(T,M,L,te,ae,he){if(T>L||T<M){let xe=typeof M=="bigint"?"n":"",Ot;throw he>3?M===0||M===BigInt(0)?Ot=`>= 0${xe} and < 2${xe} ** ${(he+1)*8}${xe}`:Ot=`>= -(2${xe} ** ${(he+1)*8-1}${xe}) and < 2 ** ${(he+1)*8-1}${xe}`:Ot=`>= ${M}${xe} and <= ${L}${xe}`,new Q.ERR_OUT_OF_RANGE("value",Ot,T)}Z(te,ae,he)}function le(T,M){if(typeof T!="number")throw new Q.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,L){throw Math.floor(T)!==T?(le(T,L),new Q.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var ve=/[^+/0-9A-Za-z-_]/g;function ce(T){if(T=T.split("=")[0],T=T.trim().replace(ve,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ge(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let xe=0;xe<te;++xe){if(L=T.charCodeAt(xe),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(xe+1===te){(M-=3)>-1&&he.push(239,191,189);continue}ae=L;continue}if(L<56320){(M-=3)>-1&&he.push(239,191,189),ae=L;continue}L=(ae-55296<<10|L-56320)+65536}else ae&&(M-=3)>-1&&he.push(239,191,189);if(ae=null,L<128){if((M-=1)<0)break;he.push(L)}else if(L<2048){if((M-=2)<0)break;he.push(L>>6|192,L&63|128)}else if(L<65536){if((M-=3)<0)break;he.push(L>>12|224,L>>6&63|128,L&63|128)}else if(L<1114112){if((M-=4)<0)break;he.push(L>>18|240,L>>12&63|128,L>>6&63|128,L&63|128)}else throw new Error("Invalid code point")}return he}function Me(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Le(T,M){let L,te,ae,he=[];for(let xe=0;xe<T.length&&!((M-=2)<0);++xe)L=T.charCodeAt(xe),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function qe(T){return e.toByteArray(ce(T))}function Et(T,M,L,te){let ae;for(ae=0;ae<te&&!(ae+L>=M.length||ae>=T.length);++ae)M[ae+L]=T[ae];return ae}function Se(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function et(T){return T!==T}var wt=function(){let T="0123456789abcdef",M=new Array(256);for(let L=0;L<16;++L){let te=L*16;for(let ae=0;ae<16;++ae)M[te+ae]=T[L]+T[ae]}return M}();function St(T){return typeof BigInt>"u"?Mt:T}function Mt(){throw new Error("BigInt not supported")}}),UU=zt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),LU=zt(t=>{"use strict";var e=_c(),r=new Set(["buffer","view","utf8"]),n=class{constructor(s){if(this.encode=s.encode||this.encode,this.decode=s.decode||this.decode,this.name=s.name||this.name,this.format=s.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"||!r.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");s.createViewTranscoder&&(this.createViewTranscoder=s.createViewTranscoder),s.createBufferTranscoder&&(this.createBufferTranscoder=s.createBufferTranscoder),s.createUTF8Transcoder&&(this.createUTF8Transcoder=s.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"})}};t.Encoding=n}),KU=zt(t=>{"use strict";var{Buffer:e}=UI()||{},{Encoding:r}=LU(),n=UU(),s=class extends r{constructor(i){super({...i,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:i=>this.decode(e.from(i.buffer,i.byteOffset,i.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends r{constructor(i){super({...i,format:"view"})}createBufferTranscoder(){return new s({encode:i=>{let c=this.encode(i);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends r{constructor(i){super({...i,format:"utf8"})}createBufferTranscoder(){return new s({encode:i=>e.from(this.encode(i),"utf8"),decode:i=>this.decode(i.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:i,textDecoder:c}=n();return new a({encode:u=>i.encode(this.encode(u)),decode:u=>this.decode(c.decode(u)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=s,t.ViewFormat=a,t.UTF8Format=o}),fne=zt(t=>{"use strict";var{Buffer:e}=UI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=UU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=KU(),i=c=>c;t.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:i,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:i,name:"view",createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:`${this.name}+buffer`})}}),t.hex=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),t.base64=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),pne=zt(t=>{"use strict";var e=_c(),r=fne(),{Encoding:n}=LU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=KU(),i=Symbol("formats"),c=Symbol("encodings"),u=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(S=>u.has(S)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[i]=new Set(y);for(let S in r)try{this.encoding(S)}catch(v){if(v.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw v}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let S=this[c].get(y);if(S===void 0){if(typeof y=="string"&&y!==""){if(S=p[y],!S)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");S=l(y)}let{name:v,format:E}=S;if(!this[i].has(E))if(this[i].has("view"))S=S.createViewTranscoder();else if(this[i].has("buffer"))S=S.createBufferTranscoder();else if(this[i].has("utf8"))S=S.createUTF8Transcoder();else throw new e(`Encoding '${v}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,v,S.name,S.commonName])this[c].set(_,S)}return S}};t.Transcoder=d;function l(y){if(y instanceof n)return y;let S="type"in y&&typeof y.type=="string"?y.type:void 0,v=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:v});case"utf8":return new o({...y,name:v});case"buffer":return new s({...y,name:v});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:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),hne=zt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(n=!1));function a(u,d,l){this.fn=u,this.context=d,this.once=l||!1}function o(u,d,l,f,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new a(l,f||u,h),m=n?n+d:d;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],p]:u._events[m].push(p):(u._events[m]=p,u._eventsCount++),u}function i(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],d,l;if(this._eventsCount===0)return u;for(l in d=this._events)r.call(d,l)&&u.push(n?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},c.prototype.listeners=function(u){var d=n?n+u:u,l=this._events[d];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,h=l.length,p=new Array(h);f<h;f++)p[f]=l[f].fn;return p},c.prototype.listenerCount=function(u){var d=n?n+u:u,l=this._events[d];return l?l.fn?1:l.length:0},c.prototype.emit=function(u,d,l,f,h,p){var m=n?n+u:u;if(!this._events[m])return!1;var y=this._events[m],S=arguments.length,v,E;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),S){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,l),!0;case 4:return y.fn.call(y.context,d,l,f),!0;case 5:return y.fn.call(y.context,d,l,f,h),!0;case 6:return y.fn.call(y.context,d,l,f,h,p),!0}for(E=1,v=new Array(S-1);E<S;E++)v[E-1]=arguments[E];y.fn.apply(y.context,v)}else{var _=y.length,I;for(E=0;E<_;E++)switch(y[E].once&&this.removeListener(u,y[E].fn,void 0,!0),S){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,l);break;case 4:y[E].fn.call(y[E].context,d,l,f);break;default:if(!v)for(I=1,v=new Array(S-1);I<S;I++)v[I-1]=arguments[I];y[E].fn.apply(y[E].context,v)}}return!0},c.prototype.on=function(u,d,l){return o(this,u,d,l,!1)},c.prototype.once=function(u,d,l){return o(this,u,d,l,!0)},c.prototype.removeListener=function(u,d,l,f){var h=n?n+u:u;if(!this._events[h])return this;if(!d)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===d&&(!f||p.once)&&(!l||p.context===l)&&i(this,h);else{for(var m=0,y=[],S=p.length;m<S;m++)(p[m].fn!==d||f&&!p[m].once||l&&p[m].context!==l)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},c.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&i(this,d)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),mne=zt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),eP=zt(t=>{"use strict";var e=mne();t.fromCallback=function(r,n){if(r===void 0){var s=new Promise(function(a,o){r=function(i,c){i?o(i):a(c)}});r[n!==void 0?n:"promise"]=s}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r},t.fromPromise=function(r,n){if(n===void 0)return r;r.then(function(s){e(()=>n(null,s))}).catch(function(s){e(()=>n(s))})}}),LI=zt(t=>{"use strict";t.getCallback=function(e,r){return typeof e=="function"?e:r},t.getOptions=function(e,r){return typeof e=="object"&&e!==null?e:r!==void 0?r:{}}}),Ef=zt(t=>{"use strict";var{fromCallback:e}=eP(),r=_c(),{getOptions:n,getCallback:s}=LI(),a=Symbol("promise"),o=Symbol("callback"),i=Symbol("working"),c=Symbol("handleOne"),u=Symbol("handleMany"),d=Symbol("autoClose"),l=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),S=Symbol("keyEncoding"),v=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),I=Symbol("keys"),R=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),F=Object.freeze({}),z=()=>{},B=!1,W=class{constructor(x,P,k){if(typeof x!="object"||x===null){let A=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[i]=!1,this[h]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[u]=this[u].bind(this),this[p]=this[p].bind(this),this[S]=P[S],this[v]=P[v],this[_]=k,this[N]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[$]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[$]}get limit(){return this[N]}next(x){let P;if(x===void 0)P=new Promise((k,A)=>{x=(O,q,G)=>{O?A(O):this[_]?q===void 0&&G===void 0?k():k([q,G]):k(q)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(x,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(x,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=x,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,k){return k=s(P,k),k=e(k,a),P=n(P,F),Number.isInteger(x)?(this[h]?this.nextTick(k,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(k,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[N]<1/0&&(x=Math.min(x,this[N]-this[$])),this[i]=!0,this[o]=k,x<=0?this.nextTick(this[u],null,[]):this._nextv(x,P,this[u])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(x,P,k){let A=[],O=(q,G,V)=>{if(q)return k(q);if(this[_]?G===void 0&&V===void 0:G===void 0)return k(null,A);A.push(this[_]?[G,V]:G),A.length===x?k(null,A):this._next(O)};this._next(O)}all(x,P){return P=s(x,P),P=e(P,a),x=n(x,F),this[h]?this.nextTick(P,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[d]=!0,this[$]>=this[N]?this.nextTick(this[u],null,[]):this._all(x,this[u])),P[a]}_all(x,P){let k=this[$],A=[],O=()=>{let G=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;G<=0?this.nextTick(P,null,A):this._nextv(G,F,q)},q=(G,V)=>{G?P(G):V.length===0?P(null,A):(A.push.apply(A,V),k+=V.length,O())};O()}[l](){let x=this[o];return this[E]&&x===null?z:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),x)}[f](x,P,k){this[d]?this.close(x.bind(null,P,k)):x(P,k)}seek(x,P){if(P=n(P,F),!this[h]){if(this[i])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(P.keyEncoding||this[S]),A=k.format;P.keyEncoding!==A&&(P={...P,keyEncoding:A});let O=this.db.prefixKey(k.encode(x),A);this._seek(O,P)}}}_seek(x,P){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[h]?this[y].push(x):(this[h]=!0,this[y].push(x),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),x[a]}_close(x){this.nextTick(x)}[p](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},X=class extends W{constructor(x,P){super(x,P,!0),this[I]=P.keys!==!1,this[R]=P.values!==!1}[c](x,P,k){let A=this[l]();if(x)return A(x);try{P=this[I]&&P!==void 0?this[S].decode(P):void 0,k=this[R]&&k!==void 0?this[v].decode(k):void 0}catch(O){return A(new b("entry",O))}P===void 0&&k===void 0||this[$]++,A(null,P,k)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A of P){let O=A[0],q=A[1];A[0]=this[I]&&O!==void 0?this[S].decode(O):void 0,A[1]=this[R]&&q!==void 0?this[v].decode(q):void 0}}catch(A){return this[f](k,new b("entries",A))}this[$]+=P.length,this[f](k,null,P)}end(x){return!B&&typeof console<"u"&&(B=!0,console.warn(new r("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(x)}},D=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[l]();if(x)return k(x);try{P=P!==void 0?this[S].decode(P):void 0}catch(A){return k(new b("key",A))}P!==void 0&&this[$]++,k(null,P)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A=0;A<P.length;A++){let O=P[A];P[A]=O!==void 0?this[S].decode(O):void 0}}catch(A){return this[f](k,new b("keys",A))}this[$]+=P.length,this[f](k,null,P)}},C=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[l]();if(x)return k(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(A){return k(new b("value",A))}P!==void 0&&this[$]++,k(null,P)}[u](x,P){let k=this[l]();if(x)return this[f](k,x);try{for(let A=0;A<P.length;A++){let O=P[A];P[A]=O!==void 0?this[v].decode(O):void 0}}catch(A){return this[f](k,new b("values",A))}this[$]+=P.length,this[f](k,null,P)}},b=class extends r{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(X.prototype,x.split(" ")[0],{get(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});X.keyEncoding=S,X.valueEncoding=v,t.AbstractIterator=X,t.AbstractKeyIterator=D,t.AbstractValueIterator=C}),yne=zt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Ef(),n=Symbol("iterator"),s=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),i=class extends e{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends r{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let u of[i,c]){let d=u===i,l=d?f=>f[0]:f=>f[1];u.prototype._next=function(f){this[s]=f,this[n].next(this[a])},u.prototype[a]=function(f,h,p){let m=this[s];f?m(f):m(null,d?h:p)},u.prototype._nextv=function(f,h,p){this[s]=p,this[n].nextv(f,h,this[o])},u.prototype._all=function(f,h){this[s]=h,this[n].all(f,this[o])},u.prototype[o]=function(f,h){let p=this[s];f?p(f):p(null,h.map(l))},u.prototype._seek=function(f,h){this[n].seek(f,h)},u.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=i,t.DefaultValueIterator=c}),gne=zt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Ef(),s=_c(),a=Symbol("nut"),o=Symbol("undefer"),i=Symbol("factory"),c=class extends e{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.iterator(f),this.db.defer(()=>this[o]())}},u=class extends r{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.values(f),this.db.defer(()=>this[o]())}};for(let l of[c,u,d])l.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[i]())},l.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new s("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._nextv=function(f,h,p){this[a]!==null?this[a].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new s("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._all=function(f,h){this[a]!==null?this[a].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new s("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},l.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};t.DeferredIterator=c,t.DeferredKeyIterator=u,t.DeferredValueIterator=d}),zU=zt(t=>{"use strict";var{fromCallback:e}=eP(),r=_c(),{getCallback:n,getOptions:s}=LI(),a=Symbol("promise"),o=Symbol("status"),i=Symbol("operations"),c=Symbol("finishClose"),u=Symbol("closeCallbacks"),d=class{constructor(l){if(typeof l!="object"||l===null){let f=l===null?"null":typeof l;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[i]=[],this[u]=[],this[o]="open",this[c]=this[c].bind(this),this.db=l,this.db.attachResource(this),this.nextTick=l.nextTick}get length(){return this[i].length}put(l,f,h){if(this[o]!=="open")throw new r("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(l)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,S=m.keyEncoding(h&&h.keyEncoding),v=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:v.format},m!==this.db&&(h.sublevel=null);let _=m.prefixKey(S.encode(l),E),I=v.encode(f);return this._put(_,I,h),this[i].push({...y,type:"put",key:l,value:f}),this}_put(l,f,h){}del(l,f){if(this[o]!=="open")throw new r("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(l);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),S=y.format;return f={...f,keyEncoding:S},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(l),S),f),this[i].push({...m,type:"del",key:l}),this}_del(l,f){}clear(){if(this[o]!=="open")throw new r("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[i]=[],this}_clear(){}write(l,f){return f=n(l,f),f=e(f,a),l=s(l),this[o]!=="open"?this.nextTick(f,new r("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(l,h=>{this[o]="closing",this[u].push(()=>f(h)),h||this.db.emit("batch",this[i]),this._close(this[c])})),f[a]}_write(l,f){}close(l){return l=e(l,a),this[o]==="closing"?this[u].push(l):this[o]==="closed"?this.nextTick(l):(this[u].push(l),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),l[a]}_close(l){this.nextTick(l)}[c](){this[o]="closed",this.db.detachResource(this);let l=this[u];this[u]=[];for(let f of l)f()}};t.AbstractChainedBatch=d}),wne=zt(t=>{"use strict";var{AbstractChainedBatch:e}=zU(),r=_c(),n=Symbol("encoded"),s=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,i){this[n].push({...i,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=s}),vne=zt((t,e)=>{"use strict";var r=_c(),n=Object.prototype.hasOwnProperty,s=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let i={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new r(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});s.has(c)?i[c]=o.encode(a[c]):i[c]=a[c]}return i.reverse=!!i.reverse,i.limit=Number.isInteger(i.limit)&&i.limit>=0?i.limit:-1,i}}),qU=zt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(s=>setTimeout(()=>{throw s},0))}),bne=zt((t,e)=>{"use strict";var r=qU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),Pne=zt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Ef(),s=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),i=Symbol("handleMany"),c=Symbol("callback"),u=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h,p){let m=this[c];if(f)return m(f);h!==void 0&&(h=this[s](h)),m(f,h,p)}[i](f,h){let p=this[c];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[s](y))}p(f,h)}},d=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h){let p=this[c];if(f)return p(f);h!==void 0&&(h=this[s](h)),p(f,h)}[i](f,h){let p=this[c];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[s](y))}p(f,h)}},l=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[u,d])f.prototype._next=function(h){this[c]=h,this[a].next(this[o])},f.prototype._nextv=function(h,p,m){this[c]=m,this[a].nextv(h,p,this[i])},f.prototype._all=function(h,p){this[c]=p,this[a].all(h,this[i])};for(let f of[l])f.prototype._next=function(h){this[a].next(h)},f.prototype._nextv=function(h,p,m){this[a].nextv(h,p,m)},f.prototype._all=function(h,p){this[a].all(h,p)};for(let f of[u,d,l])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=u,t.AbstractSublevelKeyIterator=d,t.AbstractSublevelValueIterator=l}),xne=zt((t,e)=>{"use strict";var r=_c(),{Buffer:n}=UI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Pne(),i=Symbol("prefix"),c=Symbol("upperBound"),u=Symbol("prefixRange"),d=Symbol("parent"),l=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:E}){class _ extends E{static defaults(R){if(typeof R=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(R&&R.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return R==null?h:R.separator?R:{...R,separator:"!"}}constructor(R,N,$){let{separator:F,manifest:z,...B}=_.defaults($);N=v(N,F);let W=F.charCodeAt(0)+1,X=R[d]||R;if(!f.encode(N).every(b=>b>W&&b<127))throw new r(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(X,z),B);let D=(R.prefix||"")+F+N+F,C=D.slice(0,-1)+String.fromCharCode(W);this[d]=X,this[i]=new y(D),this[c]=new y(C),this[l]=new S,this.nextTick=X.nextTick}prefixKey(R,N){if(N==="utf8")return this[i].utf8+R;if(R.byteLength===0)return this[i][N];if(N==="view"){let $=this[i].view,F=new Uint8Array($.byteLength+R.byteLength);return F.set($,0),F.set(R,$.byteLength),F}else{let $=this[i].buffer;return n.concat([$,R],$.byteLength+R.byteLength)}}[u](R,N){R.gte!==void 0?R.gte=this.prefixKey(R.gte,N):R.gt!==void 0?R.gt=this.prefixKey(R.gt,N):R.gte=this[i][N],R.lte!==void 0?R.lte=this.prefixKey(R.lte,N):R.lt!==void 0?R.lt=this.prefixKey(R.lt,N):R.lte=this[c][N]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(R,N){this[d].open({passive:!0},N)}_put(R,N,$,F){this[d].put(R,N,$,F)}_get(R,N,$){this[d].get(R,N,$)}_getMany(R,N,$){this[d].getMany(R,N,$)}_del(R,N,$){this[d].del(R,N,$)}_batch(R,N,$){this[d].batch(R,N,$)}_clear(R,N){this[u](R,R.keyEncoding),this[d].clear(R,N)}_iterator(R){this[u](R,R.keyEncoding);let N=this[d].iterator(R),$=this[l].get(this[i].utf8.length,R.keyEncoding);return new s(this,R,N,$)}_keys(R){this[u](R,R.keyEncoding);let N=this[d].keys(R),$=this[l].get(this[i].utf8.length,R.keyEncoding);return new a(this,R,N,$)}_values(R){this[u](R,R.keyEncoding);let N=this[d].values(R);return new o(this,R,N)}}return{AbstractSublevel:_}};var p=function(E,_){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,_){return E.supports.encodings[_]?E.keyEncoding(_).name===_:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},S=class{constructor(){this.cache=new Map}get(E,_){let I=this.cache.get(_);return I===void 0&&(_==="view"?I=(function(R,N){return N.subarray(R)}).bind(null,E):I=(function(R,N){return N.slice(R)}).bind(null,E),this.cache.set(_,I)),I}},v=function(E,_){let I=0,R=E.length;for(;I<R&&E[I]===_;)I++;for(;R>I&&E[R-1]===_;)R--;return E.slice(I,R)}}),xN=zt(t=>{"use strict";var{supports:e}=dne(),{Transcoder:r}=pne(),{EventEmitter:n}=hne(),{fromCallback:s}=eP(),a=_c(),{AbstractIterator:o}=Ef(),{DefaultKeyIterator:i,DefaultValueIterator:c}=yne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=gne(),{DefaultChainedBatch:f}=wne(),{getCallback:h,getOptions:p}=LI(),m=vne(),y=Symbol("promise"),S=Symbol("landed"),v=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),I=Symbol("undefer"),R=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),F=Symbol("defaultOptions"),z=Symbol("transcoder"),B=Symbol("keyEncoding"),W=Symbol("valueEncoding"),X=()=>{},D=class extends n{constructor(P,k){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");k=p(k);let{keyEncoding:A,valueEncoding:O,passive:q,...G}=k;this[v]=new Set,this[_]=[],this[R]=!0,this[N]=G,this[$]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(x(this)),this[B]=this[z].encoding(A||"utf8"),this[W]=this[z].encoding(O||"utf8");for(let V of this[z].encodings())this.supports.encodings[V.commonName]||(this.supports.encodings[V.commonName]=!0);this[F]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[R]&&this.open({passive:!1},X)})}get status(){return this[$]}keyEncoding(P){return this[z].encoding(P??this[B])}valueEncoding(P){return this[z].encoding(P??this[W])}open(P,k){k=h(P,k),k=s(k,y),P={...this[N],...p(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let A=O=>{this[$]==="closing"||this[$]==="opening"?this.once(S,O?()=>A(O):A):this[$]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:O})):k()};return P.passive?this[$]==="opening"?this.once(S,A):this.nextTick(A):this[$]==="closed"||this[R]?(this[R]=!1,this[$]="opening",this.emit("opening"),this._open(P,O=>{if(O){this[$]="closed",this[E](()=>{this.emit(S),A(O)}),this[I]();return}this[$]="open",this[I](),this.emit(S),this[$]==="open"&&this.emit("open"),this[$]==="open"&&this.emit("ready"),A()})):this[$]==="open"?this.nextTick(A):this.once(S,()=>this.open(P,k)),k[y]}_open(P,k){this.nextTick(k)}close(P){P=s(P,y);let k=A=>{this[$]==="opening"||this[$]==="closing"?this.once(S,A?k(A):k):this[$]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):P()};if(this[$]==="open"){this[$]="closing",this.emit("closing");let A=O=>{this[$]="open",this[I](),this.emit(S),k(O)};this[E](()=>{this._close(O=>{if(O)return A(O);this[$]="closed",this[I](),this.emit(S),this[$]==="closed"&&this.emit("closed"),k()})})}else this[$]==="closed"?this.nextTick(k):this.once(S,()=>this.close(P));return P[y]}[E](P){if(this[v].size===0)return this.nextTick(P);let k=this[v].size,A=!0,O=()=>{--k===0&&(A?this.nextTick(P):P())};for(let q of this[v])q.close(O);A=!1,this[v].clear()}_close(P){this.nextTick(P)}get(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.get(P,k,A)),A[y];if(b(this,A))return A[y];let O=this._checkKey(P);if(O)return this.nextTick(A,O),A[y];let q=this.keyEncoding(k.keyEncoding),G=this.valueEncoding(k.valueEncoding),V=q.format,H=G.format;return(k.keyEncoding!==V||k.valueEncoding!==H)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:H})),this._get(this.prefixKey(q.encode(P),V),k,(Y,K)=>{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{K=G.decode(K)}catch(Q){return A(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,K)}),A[y]}_get(P,k,A){this.nextTick(A,new Error("NotFound"))}getMany(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.getMany(P,k,A)),A[y];if(b(this,A))return A[y];if(!Array.isArray(P))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(P.length===0)return this.nextTick(A,null,[]),A[y];let O=this.keyEncoding(k.keyEncoding),q=this.valueEncoding(k.valueEncoding),G=O.format,V=q.format;(k.keyEncoding!==G||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:G,valueEncoding:V}));let H=new Array(P.length);for(let Y=0;Y<P.length;Y++){let K=P[Y],Q=this._checkKey(K);if(Q)return this.nextTick(A,Q),A[y];H[Y]=this.prefixKey(O.encode(K),G)}return this._getMany(H,k,(Y,K)=>{if(Y)return A(Y);try{for(let Q=0;Q<K.length;Q++)K[Q]!==void 0&&(K[Q]=q.decode(K[Q]))}catch(Q){return A(new a(`Could not decode one or more of ${K.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}A(null,K)}),A[y]}_getMany(P,k,A){this.nextTick(A,null,new Array(P.length).fill(void 0))}put(P,k,A,O){if(O=h(A,O),O=s(O,y),A=p(A,this[F].entry),this[$]==="opening")return this.defer(()=>this.put(P,k,A,O)),O[y];if(b(this,O))return O[y];let q=this._checkKey(P)||this._checkValue(k);if(q)return this.nextTick(O,q),O[y];let G=this.keyEncoding(A.keyEncoding),V=this.valueEncoding(A.valueEncoding),H=G.format,Y=V.format;(A.keyEncoding!==H||A.valueEncoding!==Y)&&(A=Object.assign({},A,{keyEncoding:H,valueEncoding:Y}));let K=this.prefixKey(G.encode(P),H),Q=V.encode(k);return this._put(K,Q,A,se=>{if(se)return O(se);this.emit("put",P,k),O()}),O[y]}_put(P,k,A,O){this.nextTick(O)}del(P,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].key),this[$]==="opening")return this.defer(()=>this.del(P,k,A)),A[y];if(b(this,A))return A[y];let O=this._checkKey(P);if(O)return this.nextTick(A,O),A[y];let q=this.keyEncoding(k.keyEncoding),G=q.format;return k.keyEncoding!==G&&(k=Object.assign({},k,{keyEncoding:G})),this._del(this.prefixKey(q.encode(P),G),k,V=>{if(V)return A(V);this.emit("del",P),A()}),A[y]}_del(P,k,A){this.nextTick(A)}batch(P,k,A){if(!arguments.length){if(this[$]==="opening")return new f(this);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?A=P:A=h(k,A),A=s(A,y),k=p(k,this[F].empty),this[$]==="opening")return this.defer(()=>this.batch(P,k,A)),A[y];if(b(this,A))return A[y];if(!Array.isArray(P))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(P.length===0)return this.nextTick(A),A[y];let O=new Array(P.length),{keyEncoding:q,valueEncoding:G,...V}=k;for(let H=0;H<P.length;H++){if(typeof P[H]!="object"||P[H]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let Y=Object.assign({},P[H]);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 K=this._checkKey(Y.key);if(K)return this.nextTick(A,K),A[y];let Q=Y.sublevel!=null?Y.sublevel:this,se=Q.keyEncoding(Y.keyEncoding||q),re=se.format;if(Y.key=Q.prefixKey(se.encode(Y.key),re),Y.keyEncoding=re,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(A,Z),A[y];let de=Q.valueEncoding(Y.valueEncoding||G);Y.value=de.encode(Y.value),Y.valueEncoding=de.format}Q!==this&&(Y.sublevel=null),O[H]=Y}return this._batch(O,V,H=>{if(H)return A(H);this.emit("batch",P),A()}),A[y]}_batch(P,k,A){this.nextTick(A)}sublevel(P,k){return this._sublevel(P,C.defaults(k))}_sublevel(P,k){return new C(this,P,k)}prefixKey(P,k){return P}clear(P,k){if(k=h(P,k),k=s(k,y),P=p(P,this[F].empty),this[$]==="opening")return this.defer(()=>this.clear(P,k)),k[y];if(b(this,k))return k[y];let A=P,O=this.keyEncoding(P.keyEncoding);return P=m(P,O),P.keyEncoding=O.format,P.limit===0?this.nextTick(k):this._clear(P,q=>{if(q)return k(q);this.emit("clear",A),k()}),k[y]}_clear(P,k){this.nextTick(k)}iterator(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P.keys=P.keys!==!1,P.values=P.values!==!1,P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new u(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new o(this,P)}keys(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new d(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new i(this,P)}values(P){let k=this.keyEncoding(P&&P.keyEncoding),A=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[o.keyEncoding]=k,P[o.valueEncoding]=A,P.keyEncoding=k.format,P.valueEncoding=A.format,this[$]==="opening")return new l(this,P);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[_].push(P)}[I](){if(this[_].length===0)return;let P=this[_];this[_]=[];for(let k of P)k()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[v].add(P)}detachResource(P){this[v].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};D.prototype.nextTick=bne();var{AbstractSublevel:C}=xne()({AbstractLevel:D});t.AbstractLevel=D,t.AbstractSublevel=C;var b=function(P,k){return P[$]!=="open"?(P.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(k=>!!P.supports.encodings[k])}}),FU=zt(t=>{"use strict";t.AbstractLevel=xN().AbstractLevel,t.AbstractSublevel=xN().AbstractSublevel,t.AbstractIterator=Ef().AbstractIterator,t.AbstractKeyIterator=Ef().AbstractKeyIterator,t.AbstractValueIterator=Ef().AbstractValueIterator,t.AbstractChainedBatch=zU().AbstractChainedBatch}),Sne=zt((t,e)=>{e.exports=n;var r=qU();function n(s,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let i,c,u,d,l,f=!0,h;Array.isArray(s)?(i=[],u=c=s.length):(d=Object.keys(s),i={},u=c=d.length);function p(y){function S(){o&&o(y,i),o=null}f?r(S):S()}function m(y,S,v){if(i[y]=v,S&&(l=!0),--u===0||S)p(S);else if(!l&&h<c){let E;d?(E=d[h],h+=1,s[E](function(_,I){m(E,_,I)})):(E=h,h+=1,s[E](function(_,I){m(E,_,I)}))}}h=a,u?d?d.some(function(y,S){return s[y](function(v,E){m(y,v,E)}),S===a-1}):s.some(function(y,S){return y(function(v,E){m(S,v,E)}),S===a-1}):p(null),f=!1}}),GU=zt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,s=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,o=r.lte===void 0;return n!==void 0&&s!==void 0?IDBKeyRange.bound(n,s,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):s!==void 0?IDBKeyRange.upperBound(s,o):null}}),WU=zt((t,e)=>{"use strict";var r=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):r.encode(n)}}),Ene=zt(t=>{"use strict";var{AbstractIterator:e}=FU(),r=GU(),n=WU(),s=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),i=Symbol("currentOptions"),c=Symbol("position"),u=Symbol("location"),d=Symbol("first"),l={},f=class extends e{constructor(p,m,y){super(p,y),this[s]=[],this[a]=this.limit===0,this[o]=y,this[i]={...y},this[c]=void 0,this[u]=m,this[d]=!0}_nextv(p,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[s].length>0)return p=Math.min(p,this[s].length),this.nextTick(y,null,this[s].splice(0,p));this[c]!==void 0&&(this[o].reverse?(this[i].lt=this[c],this[i].lte=void 0):(this[i].gt=this[c],this[i].gte=void 0));let S;try{S=r(this[i])}catch{return this[a]=!0,this.nextTick(y,null,[])}let v=this.db.db.transaction([this[u]],"readonly"),E=v.objectStore(this[u]),_=[];if(this[o].reverse){let I=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[I](S,"prev").onsuccess=R=>{let N=R.target.result;if(N){let{key:$,value:F}=N;this[c]=$,_.push([this[o].keys&&$!==void 0?n($):void 0,this[o].values&&F!==void 0?n(F):void 0]),_.length<p?N.continue():h(v)}else this[a]=!0}}else{let I,R,N=()=>{if(I===void 0||R===void 0)return;let $=Math.max(I.length,R.length);$===0||p===1/0?this[a]=!0:this[c]=I[$-1],_.length=$;for(let F=0;F<$;F++){let z=I[F],B=R[F];_[F]=[this[o].keys&&z!==void 0?n(z):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(v)};this[o].keys||p<1/0?E.getAllKeys(S,p<1/0?p:void 0).onsuccess=$=>{I=$.target.result,N()}:(I=[],this.nextTick(N)),this[o].values?E.getAll(S,p<1/0?p:void 0).onsuccess=$=>{R=$.target.result,N()}:(R=[],this.nextTick(N))}v.onabort=()=>{y(v.error||new Error("aborted by user")),y=null},v.oncomplete=()=>{y(null,_),y=null}}_next(p){if(this[s].length>0){let[m,y]=this[s].shift();this.nextTick(p,null,m,y)}else if(this[a])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,l,(y,S)=>{if(y)return p(y);this[s]=S,this._next(p)})}}_all(p,m){this[d]=!1;let y=this[s].splice(0,this[s].length),S=this.limit-this.count-y.length;if(S<=0)return this.nextTick(m,null,y);this._nextv(S,l,(v,E)=>{if(v)return m(v);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(p,m){this[d]=!0,this[s]=[],this[a]=!1,this[c]=void 0,this[i]={...this[o]};let y;try{y=r(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[o].reverse?this[i].lte=p:this[i].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),kne=zt((t,e)=>{"use strict";e.exports=function(r,n,s,a,o){if(a.limit===0)return r.nextTick(o);let i=r.db.transaction([n],"readwrite"),c=i.objectStore(n),u=0;i.oncomplete=function(){o()},i.onabort=function(){o(i.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",l=a.reverse?"prev":"next";c[d](s,l).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(a.limit<=0||++u<a.limit)&&h.continue()})}}}),_ne=zt(t=>{"use strict";var{AbstractLevel:e}=FU(),r=_c(),n=Sne(),{fromCallback:s}=eP(),{Iterator:a}=Ene(),o=WU(),i=kne(),c=GU(),u="level-js-",d=Symbol("idb"),l=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),S=class extends e{constructor(v,E,_){if(typeof E=="function"||typeof _=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:I,version:R,...N}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof v!="string")throw new Error("constructor requires a location string argument");this[f]=v,this[l]=I??u,this[h]=parseInt(R||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[l]}get version(){return this[h]}get db(){return this[d]}get type(){return"browser-level"}_open(v,E){let _=indexedDB.open(this[l]+this[f],this[h]);_.onerror=function(){E(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,E()},_.onupgradeneeded=I=>{let R=I.target.result;R.objectStoreNames.contains(this[f])||R.createObjectStore(this[f])}}[p](v){return this[d].transaction([this[f]],v).objectStore(this[f])}[m](v,E){let _=v.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,v.result)}}_get(v,E,_){let I=this[p]("readonly"),R;try{R=I.get(v)}catch(N){return this.nextTick(_,N)}this[m](R,function(N,$){if(N)return _(N);if($===void 0)return _(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(v,E,_){let I=this[p]("readonly"),R=v.map(N=>$=>{let F;try{F=I.get(N)}catch(z){return $(z)}F.onsuccess=()=>{let z=F.result;$(null,z===void 0?z:o(z))},F.onerror=z=>{z.stopPropagation(),$(F.error)}});n(R,16,_)}_del(v,E,_){let I=this[p]("readwrite"),R;try{R=I.delete(v)}catch(N){return this.nextTick(_,N)}this[m](R,_)}_put(v,E,_,I){let R=this[p]("readwrite"),N;try{N=R.put(E,v)}catch($){return this.nextTick(I,$)}this[m](N,I)}_iterator(v){return new a(this,this[f],v)}_batch(v,E,_){let I=this[p]("readwrite"),R=I.transaction,N=0,$;R.onabort=function(){_($||R.error||new Error("aborted by user"))},R.oncomplete=function(){_()};function F(){let z=v[N++],B=z.key,W;try{W=z.type==="del"?I.delete(B):I.put(z.value,B)}catch(X){$=X,R.abort();return}N<v.length?W.onsuccess=F:typeof R.commit=="function"&&R.commit()}F()}_clear(v,E){let _,I;try{_=c(v)}catch{return this.nextTick(E)}if(v.limit>=0)return i(this,this[f],_,v,E);try{let R=this[p]("readwrite");I=_?R.delete(_):R.clear()}catch(R){return this.nextTick(E,R)}this[m](I,E)}_close(v){this[d].close(),this.nextTick(v)}};S.destroy=function(v,E,_){typeof E=="function"&&(_=E,E=u),_=s(_,y);let I=indexedDB.deleteDatabase(E+v);return I.onsuccess=function(){_()},I.onerror=function(R){_(R)},_[y]},t.BrowserLevel=S}),VU=zt(t=>{t.Level=_ne().BrowserLevel}),Tne=zt((t,e)=>{(function(r,n){typeof t=="object"&&typeof e<"u"?n(t):typeof define=="function"&&define.amd?define(["exports"],n):n(r.URI=r.URI||{})})(t,function(r){"use strict";function n(){for(var J=arguments.length,ie=Array(J),oe=0;oe<J;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,be=1;be<ye;++be)ie[be]=ie[be].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(J){return"(?:"+J+")"}function a(J){return J===void 0?"undefined":J===null?"null":Object.prototype.toString.call(J).split(" ").pop().split("]").shift().toLowerCase()}function o(J){return J.toUpperCase()}function i(J){return J!=null?J instanceof Array?J:typeof J.length!="number"||J.split||J.setInterval||J.call?[J]:Array.prototype.slice.call(J):[]}function c(J,ie){var oe=J;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(J){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",be="[\\x22]",ze=n(ye,"[A-Fa-f]"),At="[\\x0A]",ur="[\\x20]",zr=s(s("%[EFef]"+ze+"%"+ze+ze+"%"+ze+ze)+"|"+s("%[89A-Fa-f]"+ze+"%"+ze+ze)+"|"+s("%"+ze+ze)),qr="[\\:\\/\\?\\#\\[\\]\\@]",tr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",pn=n(qr,tr),$n=J?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",sn=J?"[\\uE000-\\uF8FF]":"[]",wr=n(ie,ye,"[\\-\\.\\_\\~]",$n),mr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Ns=s(s(zr+"|"+n(wr,tr,"[\\:]"))+"*"),sm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),Ti=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Yo=s(Ti+"\\."+Ti+"\\."+Ti+"\\."+Ti),vr=s(ze+"{1,4}"),Fi=s(s(vr+"\\:"+vr)+"|"+Yo),bo=s(s(vr+"\\:")+"{6}"+Fi),Tc=s("\\:\\:"+s(vr+"\\:")+"{5}"+Fi),Yu=s(s(vr)+"?\\:\\:"+s(vr+"\\:")+"{4}"+Fi),ja=s(s(s(vr+"\\:")+"{0,1}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{3}"+Fi),Vw=s(s(s(vr+"\\:")+"{0,2}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{2}"+Fi),Hw=s(s(s(vr+"\\:")+"{0,3}"+vr)+"?\\:\\:"+vr+"\\:"+Fi),Ff=s(s(s(vr+"\\:")+"{0,4}"+vr)+"?\\:\\:"+Fi),Gf=s(s(s(vr+"\\:")+"{0,5}"+vr)+"?\\:\\:"+vr),Wf=s(s(s(vr+"\\:")+"{0,6}"+vr)+"?\\:\\:"),Qu=s([bo,Tc,Yu,ja,Vw,Hw,Ff,Gf,Wf].join("|")),Vf=s(s(wr+"|"+zr)+"+"),Hf=s(Qu+"\\%25"+Vf),cz=s(Qu+s("\\%25|\\%(?!"+ze+"{2})")+Vf),dz=s("[vV]"+ze+"+\\."+n(wr,tr,"[\\:]")+"+"),uz=s("\\["+s(cz+"|"+Qu+"|"+dz)+"\\]"),QA=s(s(zr+"|"+n(wr,tr))+"*"),im=s(uz+"|"+Yo+"(?!"+QA+")|"+QA),om=s(ye+"*"),XA=s(s(Ns+"@")+"?"+im+s("\\:"+om)+"?"),am=s(zr+"|"+n(wr,tr,"[\\:\\@]")),lz=s(am+"*"),eR=s(am+"+"),fz=s(s(zr+"|"+n(wr,tr,"[\\@]"))+"+"),Ic=s(s("\\/"+lz)+"*"),Jf=s("\\/"+s(eR+Ic)+"?"),jP=s(fz+Ic),Jw=s(eR+Ic),Zf="(?!"+am+")",yue=s(Ic+"|"+Jf+"|"+jP+"|"+Jw+"|"+Zf),Yf=s(s(am+"|"+n("[\\/\\?]",sn))+"*"),cm=s(s(am+"|[\\/\\?]")+"*"),tR=s(s("\\/\\/"+XA+Ic)+"|"+Jf+"|"+Jw+"|"+Zf),pz=s(mr+"\\:"+tR+s("\\?"+Yf)+"?"+s("\\#"+cm)+"?"),hz=s(s("\\/\\/"+XA+Ic)+"|"+Jf+"|"+jP+"|"+Zf),mz=s(hz+s("\\?"+Yf)+"?"+s("\\#"+cm)+"?"),gue=s(pz+"|"+mz),wue=s(mr+"\\:"+tR+s("\\?"+Yf)+"?"),vue="^("+mr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+Jw+"|"+Zf+")")+s("\\?("+Yf+")")+"?"+s("\\#("+cm+")")+"?$",bue="^(){0}"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+jP+"|"+Zf+")")+s("\\?("+Yf+")")+"?"+s("\\#("+cm+")")+"?$",Pue="^("+mr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?)")+"?("+Ic+"|"+Jf+"|"+Jw+"|"+Zf+")")+s("\\?("+Yf+")")+"?$",xue="^"+s("\\#("+cm+")")+"?$",Sue="^"+s("("+Ns+")@")+"?("+im+")"+s("\\:("+om+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",wr,tr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",wr,tr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",wr,tr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",wr,tr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",wr,tr,"[\\:\\@\\/\\?]",sn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",wr,tr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",wr,tr),"g"),UNRESERVED:new RegExp(wr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",wr,pn),"g"),PCT_ENCODED:new RegExp(zr,"g"),IPV4ADDRESS:new RegExp("^("+Yo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Qu+")"+s(s("\\%25|\\%(?!"+ze+"{2})")+"("+Vf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function J(ie,oe){var ye=[],be=!0,ze=!1,At=void 0;try{for(var ur=ie[Symbol.iterator](),zr;!(be=(zr=ur.next()).done)&&(ye.push(zr.value),!(oe&&ye.length===oe));be=!0);}catch(qr){ze=!0,At=qr}finally{try{!be&&ur.return&&ur.return()}finally{if(ze)throw At}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return J(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(J){if(Array.isArray(J)){for(var ie=0,oe=Array(J.length);ie<J.length;ie++)oe[ie]=J[ie];return oe}else return Array.from(J)},p=2147483647,m=36,y=1,S=26,v=38,E=700,_=72,I=128,R="-",N=/^xn--/,$=/[^\0-\x7E]/,F=/[\x2E\u3002\uFF0E\uFF61]/g,z={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,W=Math.floor,X=String.fromCharCode;function D(J){throw new RangeError(z[J])}function C(J,ie){for(var oe=[],ye=J.length;ye--;)oe[ye]=ie(J[ye]);return oe}function b(J,ie){var oe=J.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",J=oe[1]),J=J.replace(F,".");var be=J.split("."),ze=C(be,ie).join(".");return ye+ze}function x(J){for(var ie=[],oe=0,ye=J.length;oe<ye;){var be=J.charCodeAt(oe++);if(be>=55296&&be<=56319&&oe<ye){var ze=J.charCodeAt(oe++);(ze&64512)==56320?ie.push(((be&1023)<<10)+(ze&1023)+65536):(ie.push(be),oe--)}else ie.push(be)}return ie}var P=function(J){return String.fromCodePoint.apply(String,h(J))},k=function(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:m},A=function(J,ie){return J+22+75*(J<26)-((ie!=0)<<5)},O=function(J,ie,oe){var ye=0;for(J=oe?W(J/E):J>>1,J+=W(J/ie);J>B*S>>1;ye+=m)J=W(J/B);return W(ye+(B+1)*J/(J+v))},q=function(J){var ie=[],oe=J.length,ye=0,be=I,ze=_,At=J.lastIndexOf(R);At<0&&(At=0);for(var ur=0;ur<At;++ur)J.charCodeAt(ur)>=128&&D("not-basic"),ie.push(J.charCodeAt(ur));for(var zr=At>0?At+1:0;zr<oe;){for(var qr=ye,tr=1,pn=m;;pn+=m){zr>=oe&&D("invalid-input");var $n=k(J.charCodeAt(zr++));($n>=m||$n>W((p-ye)/tr))&&D("overflow"),ye+=$n*tr;var sn=pn<=ze?y:pn>=ze+S?S:pn-ze;if($n<sn)break;var wr=m-sn;tr>W(p/wr)&&D("overflow"),tr*=wr}var mr=ie.length+1;ze=O(ye-qr,mr,qr==0),W(ye/mr)>p-be&&D("overflow"),be+=W(ye/mr),ye%=mr,ie.splice(ye++,0,be)}return String.fromCodePoint.apply(String,ie)},G=function(J){var ie=[];J=x(J);var oe=J.length,ye=I,be=0,ze=_,At=!0,ur=!1,zr=void 0;try{for(var qr=J[Symbol.iterator](),tr;!(At=(tr=qr.next()).done);At=!0){var pn=tr.value;pn<128&&ie.push(X(pn))}}catch(Hf){ur=!0,zr=Hf}finally{try{!At&&qr.return&&qr.return()}finally{if(ur)throw zr}}var $n=ie.length,sn=$n;for($n&&ie.push(R);sn<oe;){var wr=p,mr=!0,Ns=!1,sm=void 0;try{for(var Ti=J[Symbol.iterator](),Yo;!(mr=(Yo=Ti.next()).done);mr=!0){var vr=Yo.value;vr>=ye&&vr<wr&&(wr=vr)}}catch(Hf){Ns=!0,sm=Hf}finally{try{!mr&&Ti.return&&Ti.return()}finally{if(Ns)throw sm}}var Fi=sn+1;wr-ye>W((p-be)/Fi)&&D("overflow"),be+=(wr-ye)*Fi,ye=wr;var bo=!0,Tc=!1,Yu=void 0;try{for(var ja=J[Symbol.iterator](),Vw;!(bo=(Vw=ja.next()).done);bo=!0){var Hw=Vw.value;if(Hw<ye&&++be>p&&D("overflow"),Hw==ye){for(var Ff=be,Gf=m;;Gf+=m){var Wf=Gf<=ze?y:Gf>=ze+S?S:Gf-ze;if(Ff<Wf)break;var Qu=Ff-Wf,Vf=m-Wf;ie.push(X(A(Wf+Qu%Vf,0))),Ff=W(Qu/Vf)}ie.push(X(A(Ff,0))),ze=O(be,Fi,sn==$n),be=0,++sn}}}catch(Hf){Tc=!0,Yu=Hf}finally{try{!bo&&ja.return&&ja.return()}finally{if(Tc)throw Yu}}++be,++ye}return ie.join("")},V=function(J){return b(J,function(ie){return N.test(ie)?q(ie.slice(4).toLowerCase()):ie})},H=function(J){return b(J,function(ie){return $.test(ie)?"xn--"+G(ie):ie})},Y={version:"2.1.0",ucs2:{decode:x,encode:P},decode:q,encode:G,toASCII:H,toUnicode:V},K={};function Q(J){var ie=J.charCodeAt(0),oe=void 0;return ie<16?oe="%0"+ie.toString(16).toUpperCase():ie<128?oe="%"+ie.toString(16).toUpperCase():ie<2048?oe="%"+(ie>>6|192).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase():oe="%"+(ie>>12|224).toString(16).toUpperCase()+"%"+(ie>>6&63|128).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase(),oe}function se(J){for(var ie="",oe=0,ye=J.length;oe<ye;){var be=parseInt(J.substr(oe+1,2),16);if(be<128)ie+=String.fromCharCode(be),oe+=3;else if(be>=194&&be<224){if(ye-oe>=6){var ze=parseInt(J.substr(oe+4,2),16);ie+=String.fromCharCode((be&31)<<6|ze&63)}else ie+=J.substr(oe,6);oe+=6}else if(be>=224){if(ye-oe>=9){var At=parseInt(J.substr(oe+4,2),16),ur=parseInt(J.substr(oe+7,2),16);ie+=String.fromCharCode((be&15)<<12|(At&63)<<6|ur&63)}else ie+=J.substr(oe,9);oe+=9}else ie+=J.substr(oe,3),oe+=3}return ie}function re(J,ie){function oe(ye){var be=se(ye);return be.match(ie.UNRESERVED)?be:ye}return J.scheme&&(J.scheme=String(J.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),J.userinfo!==void 0&&(J.userinfo=String(J.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Q).replace(ie.PCT_ENCODED,o)),J.host!==void 0&&(J.host=String(J.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Q).replace(ie.PCT_ENCODED,o)),J.path!==void 0&&(J.path=String(J.path).replace(ie.PCT_ENCODED,oe).replace(J.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Q).replace(ie.PCT_ENCODED,o)),J.query!==void 0&&(J.query=String(J.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Q).replace(ie.PCT_ENCODED,o)),J.fragment!==void 0&&(J.fragment=String(J.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Q).replace(ie.PCT_ENCODED,o)),J}function Z(J){return J.replace(/^0*(.*)/,"$1")||"0"}function de(J,ie){var oe=J.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),be=ye[1];return be?be.split(".").map(Z).join("."):J}function le(J,ie){var oe=J.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),be=ye[1],ze=ye[2];if(be){for(var At=be.toLowerCase().split("::").reverse(),ur=f(At,2),zr=ur[0],qr=ur[1],tr=qr?qr.split(":").map(Z):[],pn=zr.split(":").map(Z),$n=ie.IPV4ADDRESS.test(pn[pn.length-1]),sn=$n?7:8,wr=pn.length-sn,mr=Array(sn),Ns=0;Ns<sn;++Ns)mr[Ns]=tr[Ns]||pn[wr+Ns]||"";$n&&(mr[sn-1]=de(mr[sn-1],ie));var sm=mr.reduce(function(bo,Tc,Yu){if(!Tc||Tc==="0"){var ja=bo[bo.length-1];ja&&ja.index+ja.length===Yu?ja.length++:bo.push({index:Yu,length:1})}return bo},[]),Ti=sm.sort(function(bo,Tc){return Tc.length-bo.length})[0],Yo=void 0;if(Ti&&Ti.length>1){var vr=mr.slice(0,Ti.index),Fi=mr.slice(Ti.index+Ti.length);Yo=vr.join(":")+"::"+Fi.join(":")}else Yo=mr.join(":");return ze&&(Yo+="%"+ze),Yo}else return J}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ve="".match(/(){0}/)[1]===void 0;function ce(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(J=(ie.scheme?ie.scheme+":":"")+"//"+J);var be=J.match(pe);if(be){ve?(oe.scheme=be[1],oe.userinfo=be[3],oe.host=be[4],oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=be[7],oe.fragment=be[8],isNaN(oe.port)&&(oe.port=be[5])):(oe.scheme=be[1]||void 0,oe.userinfo=J.indexOf("@")!==-1?be[3]:void 0,oe.host=J.indexOf("//")!==-1?be[4]:void 0,oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=J.indexOf("?")!==-1?be[7]:void 0,oe.fragment=J.indexOf("#")!==-1?be[8]:void 0,isNaN(oe.port)&&(oe.port=J.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?be[4]:void 0)),oe.host&&(oe.host=le(de(oe.host,ye),ye)),oe.scheme===void 0&&oe.userinfo===void 0&&oe.host===void 0&&oe.port===void 0&&!oe.path&&oe.query===void 0?oe.reference="same-document":oe.scheme===void 0?oe.reference="relative":oe.fragment===void 0?oe.reference="absolute":oe.reference="uri",ie.reference&&ie.reference!=="suffix"&&ie.reference!==oe.reference&&(oe.error=oe.error||"URI is not a "+ie.reference+" reference.");var ze=K[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!ze||!ze.unicodeSupport)){if(oe.host&&(ie.domainHost||ze&&ze.domainHost))try{oe.host=Y.toASCII(oe.host.replace(ye.PCT_ENCODED,se).toLowerCase())}catch(At){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+At}re(oe,d)}else re(oe,ye);ze&&ze.parse&&ze.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function ge(J,ie){var oe=ie.iri!==!1?l:d,ye=[];return J.userinfo!==void 0&&(ye.push(J.userinfo),ye.push("@")),J.host!==void 0&&ye.push(le(de(String(J.host),oe),oe).replace(oe.IPV6ADDRESS,function(be,ze,At){return"["+ze+(At?"%25"+At:"")+"]"})),(typeof J.port=="number"||typeof J.port=="string")&&(ye.push(":"),ye.push(String(J.port))),ye.length?ye.join(""):void 0}var Me=/^\.\.?\//,Le=/^\/\.(\/|$)/,qe=/^\/\.\.(\/|$)/,Et=/^\/?(?:.|\n)*?(?=\/|$)/;function Se(J){for(var ie=[];J.length;)if(J.match(Me))J=J.replace(Me,"");else if(J.match(Le))J=J.replace(Le,"/");else if(J.match(qe))J=J.replace(qe,"/"),ie.pop();else if(J==="."||J==="..")J="";else{var oe=J.match(Et);if(oe){var ye=oe[0];J=J.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function et(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],be=K[(ie.scheme||J.scheme||"").toLowerCase()];if(be&&be.serialize&&be.serialize(J,ie),J.host&&!oe.IPV6ADDRESS.test(J.host)&&(ie.domainHost||be&&be.domainHost))try{J.host=ie.iri?Y.toUnicode(J.host):Y.toASCII(J.host.replace(oe.PCT_ENCODED,se).toLowerCase())}catch(ur){J.error=J.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+ur}re(J,oe),ie.reference!=="suffix"&&J.scheme&&(ye.push(J.scheme),ye.push(":"));var ze=ge(J,ie);if(ze!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(ze),J.path&&J.path.charAt(0)!=="/"&&ye.push("/")),J.path!==void 0){var At=J.path;!ie.absolutePath&&(!be||!be.absolutePath)&&(At=Se(At)),ze===void 0&&(At=At.replace(/^\/\//,"/%2F")),ye.push(At)}return J.query!==void 0&&(ye.push("?"),ye.push(J.query)),J.fragment!==void 0&&(ye.push("#"),ye.push(J.fragment)),ye.join("")}function wt(J,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],be={};return ye||(J=ce(et(J,oe),oe),ie=ce(et(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(be.scheme=ie.scheme,be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?be.path=Se(ie.path):((J.userinfo!==void 0||J.host!==void 0||J.port!==void 0)&&!J.path?be.path="/"+ie.path:J.path?be.path=J.path.slice(0,J.path.lastIndexOf("/")+1)+ie.path:be.path=ie.path,be.path=Se(be.path)),be.query=ie.query):(be.path=J.path,ie.query!==void 0?be.query=ie.query:be.query=J.query),be.userinfo=J.userinfo,be.host=J.host,be.port=J.port),be.scheme=J.scheme),be.fragment=ie.fragment,be}function St(J,ie,oe){var ye=c({scheme:"null"},oe);return et(wt(ce(J,ye),ce(ie,ye),ye,!0),ye)}function Mt(J,ie){return typeof J=="string"?J=et(ce(J,ie),ie):a(J)==="object"&&(J=ce(et(J,ie),ie)),J}function T(J,ie,oe){return typeof J=="string"?J=et(ce(J,oe),oe):a(J)==="object"&&(J=et(J,oe)),typeof ie=="string"?ie=et(ce(ie,oe),oe):a(ie)==="object"&&(ie=et(ie,oe)),J===ie}function M(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Q)}function L(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(J,ie){return J.host||(J.error=J.error||"HTTP URIs must have a host."),J},serialize:function(J,ie){var oe=String(J.scheme).toLowerCase()==="https";return(J.port===(oe?443:80)||J.port==="")&&(J.port=void 0),J.path||(J.path="/"),J}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(J){return typeof J.secure=="boolean"?J.secure:String(J.scheme).toLowerCase()==="wss"}var xe={scheme:"ws",domainHost:!0,parse:function(J,ie){var oe=J;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(J,ie){if((J.port===(he(J)?443:80)||J.port==="")&&(J.port=void 0),typeof J.secure=="boolean"&&(J.scheme=J.secure?"wss":"ws",J.secure=void 0),J.resourceName){var oe=J.resourceName.split("?"),ye=f(oe,2),be=ye[0],ze=ye[1];J.path=be&&be!=="/"?be:void 0,J.query=ze,J.resourceName=void 0}return J.fragment=void 0,J}},Ot={scheme:"wss",domainHost:xe.domainHost,parse:xe.parse,serialize:xe.serialize},Un={},Or=!0,hr="[A-Za-z0-9\\-\\.\\_\\~"+(Or?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",ir="[0-9A-Fa-f]",Q9=s(s("%[EFef]"+ir+"%"+ir+ir+"%"+ir+ir)+"|"+s("%[89A-Fa-f]"+ir+"%"+ir+ir)+"|"+s("%"+ir+ir)),X9="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",ez="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",tz=n(ez,'[\\"\\\\]'),rz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",nz=new RegExp(hr,"g"),qf=new RegExp(Q9,"g"),sz=new RegExp(n("[^]",X9,"[\\.]",'[\\"]',tz),"g"),HA=new RegExp(n("[^]",hr,rz),"g"),iz=HA;function CP(J){var ie=se(J);return ie.match(nz)?ie:J}var JA={scheme:"mailto",parse:function(J,ie){var oe=J,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var be=!1,ze={},At=oe.query.split("&"),ur=0,zr=At.length;ur<zr;++ur){var qr=At[ur].split("=");switch(qr[0]){case"to":for(var tr=qr[1].split(","),pn=0,$n=tr.length;pn<$n;++pn)ye.push(tr[pn]);break;case"subject":oe.subject=L(qr[1],ie);break;case"body":oe.body=L(qr[1],ie);break;default:be=!0,ze[L(qr[0],ie)]=L(qr[1],ie);break}}be&&(oe.headers=ze)}oe.query=void 0;for(var sn=0,wr=ye.length;sn<wr;++sn){var mr=ye[sn].split("@");if(mr[0]=L(mr[0]),ie.unicodeSupport)mr[1]=L(mr[1],ie).toLowerCase();else try{mr[1]=Y.toASCII(L(mr[1],ie).toLowerCase())}catch(Ns){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ns}ye[sn]=mr.join("@")}return oe},serialize:function(J,ie){var oe=J,ye=i(J.to);if(ye){for(var be=0,ze=ye.length;be<ze;++be){var At=String(ye[be]),ur=At.lastIndexOf("@"),zr=At.slice(0,ur).replace(qf,CP).replace(qf,o).replace(sz,Q),qr=At.slice(ur+1);try{qr=ie.iri?Y.toUnicode(qr):Y.toASCII(L(qr,ie).toLowerCase())}catch(sn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+sn}ye[be]=zr+"@"+qr}oe.path=ye.join(",")}var tr=J.headers=J.headers||{};J.subject&&(tr.subject=J.subject),J.body&&(tr.body=J.body);var pn=[];for(var $n in tr)tr[$n]!==Un[$n]&&pn.push($n.replace(qf,CP).replace(qf,o).replace(HA,Q)+"="+tr[$n].replace(qf,CP).replace(qf,o).replace(iz,Q));return pn.length&&(oe.query=pn.join("&")),oe}},oz=/^([^\:]+)\:(.*)/,ZA={scheme:"urn",parse:function(J,ie){var oe=J.path&&J.path.match(oz),ye=J;if(oe){var be=ie.scheme||ye.scheme||"urn",ze=oe[1].toLowerCase(),At=oe[2],ur=be+":"+(ie.nid||ze),zr=K[ur];ye.nid=ze,ye.nss=At,ye.path=void 0,zr&&(ye=zr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(J,ie){var oe=ie.scheme||J.scheme||"urn",ye=J.nid,be=oe+":"+(ie.nid||ye),ze=K[be];ze&&(J=ze.serialize(J,ie));var At=J,ur=J.nss;return At.path=(ye||ie.nid)+":"+ur,At}},az=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,YA={scheme:"urn:uuid",parse:function(J,ie){var oe=J;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(az))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(J,ie){var oe=J;return oe.nss=(J.uuid||"").toLowerCase(),oe}};K[te.scheme]=te,K[ae.scheme]=ae,K[xe.scheme]=xe,K[Ot.scheme]=Ot,K[JA.scheme]=JA,K[ZA.scheme]=ZA,K[YA.scheme]=YA,r.SCHEMES=K,r.pctEncChar=Q,r.pctDecChars=se,r.parse=ce,r.removeDotSegments=Se,r.serialize=et,r.resolveComponents=wt,r.resolve=St,r.normalize=Mt,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),Ine=zt((t,e)=>{"use strict";e.exports=function r(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?r(n.toJSON()):Array.isArray(n)?`[${n.reduce((s,a,o)=>`${s}${o===0?"":","}${r(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((s,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return s;let o=s.length===0?"":",";return`${s}${o}${r(a)}:${r(n[a])}`},"")}}`}}),HU=zt((t,e)=>{var r=1e3,n=r*60,s=n*60,a=s*24,o=a*7,i=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return c(f);if(p==="number"&&isFinite(f))return h.long?d(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var 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*i;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*s;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*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function u(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=s?Math.round(f/s)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function d(f){var h=Math.abs(f);return h>=a?l(f,h,a,"day"):h>=s?l(f,h,s,"hour"):h>=n?l(f,h,n,"minute"):h>=r?l(f,h,r,"second"):f+" ms"}function l(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),tP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(tP||{}),us={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Cs=class JU{constructor({method:e,id:r,path:n,query:s,fragment:a,params:o}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=s,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let r=JU.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:s,path:a,query:o,fragment:i}=r.groups,c={uri:`did:${n}:${s}`,method:n,id:s};if(a&&(c.path=a),o&&(c.query=o.slice(1)),i&&(c.fragment=i.slice(1)),o){let u={},d=o.slice(1).split("&");for(let l of d){let[f,h]=l.split("=");u[f]=h}c.params=u}return c}};Cs.METHOD_PATTERN="([a-z0-9]+)",Cs.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Cs.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Cs.PCT_ENCODED_PATTERN})`,Cs.METHOD_ID_PATTERN=`((?:${Cs.ID_CHAR_PATTERN}*:)*(${Cs.ID_CHAR_PATTERN}+))`,Cs.PATH_PATTERN="(/[^#?]*)?",Cs.QUERY_PATTERN="([?][^#]*)?",Cs.FRAGMENT_PATTERN="(#.*)?",Cs.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Cs.METHOD_PATTERN+"):(?<id>"+Cs.METHOD_ID_PATTERN+")(?<path>"+Cs.PATH_PATTERN+")(?<query>"+Cs.QUERY_PATTERN+")(?<fragment>"+Cs.FRAGMENT_PATTERN+")$");var ls=Cs,Ze=class ZU extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ZU)}},Ane=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType",t))(Ane||{}),Vo=class YU extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,YU)}},Ki;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Ki||(Ki={}));var Rne=Df(cne(),1);function Dne(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<t.length;s++){var a=t.charAt(s),o=a.charCodeAt(0);if(r[o]!==255)throw new TypeError(a+" is ambiguous");r[o]=s}var i=t.length,c=t.charAt(0),u=Math.log(i)/Math.log(256),d=Math.log(256)/Math.log(i);function l(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,S=0,v=p.length;S!==v&&p[S]===0;)S++,m++;for(var E=(v-S)*d+1>>>0,_=new Uint8Array(E);S!==v;){for(var I=p[S],R=0,N=E-1;(I!==0||R<y)&&N!==-1;N--,R++)I+=256*_[N]>>>0,_[N]=I%i>>>0,I=I/i>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,S++}for(var $=E-y;$!==E&&_[$]===0;)$++;for(var F=c.repeat(m);$<E;++$)F+=t.charAt(_[$]);return F}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,S=0;p[m]===c;)y++,m++;for(var v=(p.length-m)*u+1>>>0,E=new Uint8Array(v);p[m];){var _=r[p.charCodeAt(m)];if(_===255)return;for(var I=0,R=v-1;(_!==0||I<S)&&R!==-1;R--,I++)_+=i*E[R]>>>0,E[R]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");S=I,m++}if(p[m]!==" "){for(var N=v-S;N!==v&&E[N]===0;)N++;for(var $=new Uint8Array(y+(v-N)),F=y;N!==v;)$[F++]=E[N++];return $}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Cne=Dne,jne=Cne,$ne=jne,Lje=new Uint8Array(0),Mne=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},KI=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},One=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Bne=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return QU(this,t)}},Nne=class{constructor(t){this.decoders=t}or(t){return QU(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},QU=(t,e)=>new Nne({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Une=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new One(t,e,r),this.decoder=new Bne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},XU=({name:t,prefix:e,encode:r,decode:n})=>new Une(t,e,r,n),eL=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=$ne(r,e);return XU({prefix:t,name:e,encode:n,decode:a=>KI(s(a))})},Lne=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Kne=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},go=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>XU({prefix:e,name:t,encode(s){return Kne(s,n,r)},decode(s){return Lne(s,n,r,t)}}),x1=go({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Kje=go({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zje=go({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qje=go({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fje=go({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gje=go({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wje=go({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vje=go({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),SN=go({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Go=eL({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hje=eL({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Jje=go({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zje=go({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),md=go({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yje=go({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function zne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function qne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function yI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Hg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},EN=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(o){return new Promise(function(i,c){o=t[a](o),s(i,c,o.done,o.value)})}}function s(a,o,i,c){Promise.resolve(c).then(function(u){a({value:u,done:i})},o)}},h1=new TextEncoder,gf=new TextDecoder,Qe=class Ui{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ui(e,"ArrayBuffer")}static asyncIterable(e){if(!qne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ui(e,"AsyncIterable")}static base32Z(e){return new Ui(e,"Base32Z")}static base58Btc(e){return new Ui(e,"Base58Btc")}static base64Url(e){return new Ui(e,"Base64Url")}static bufferSource(e){return new Ui(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 Ui(e,"Hex")}static multibase(e){return new Ui(e,"Multibase")}static object(e){return new Ui(e,"Object")}static string(e){return new Ui(e,"String")}static uint8Array(e){return new Ui(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Go.baseDecode(this.data).buffer;case"Base64Url":return md.baseDecode(this.data).buffer;case"BufferSource":{if(yI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return zne(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 Hg(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 SN.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 Go.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Go.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 md.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return md.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=h1.encode(e);return md.baseEncode(r)}case"String":{let e=h1.encode(this.data);return md.baseEncode(e)}case"Uint8Array":return md.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Hg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=EN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;c.push(u)}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return Ui.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ui.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}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=md.baseDecode(this.data),r=gf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=gf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Hg(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 gf.decode(this.data);case"Base64Url":{let e=md.baseDecode(this.data);return gf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return gf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Hg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=EN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;typeof u=="string"?c+=u:c+=gf.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return c+=gf.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return SN.baseDecode(this.data);case"Base58Btc":return Go.baseDecode(this.data);case"Base64Url":return md.baseDecode(this.data);case"BufferSource":{let e=yI(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 r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return h1.encode(e)}case"String":return h1.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Hg(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.`)}})}},yw;(function(t){t.Debug="debug",t.Silent="silent"})(yw||(yw={}));var Fne=class{constructor(){this.logLevel=yw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==yw.Silent&&console.info(t)}error(t){this.logLevel!==yw.Silent&&console.error(t)}},Gne=new Fne;typeof window<"u"&&(window.enboxLogger=Gne);var tw={};NI(tw,{decode:()=>q1,encodeTo:()=>ww,encodingLength:()=>vw});var Wne=tL,kN=128,Vne=127,Hne=~Vne,Jne=Math.pow(2,31);function tL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Jne;)e[r++]=t&255|kN,t/=128;for(;t&Hne;)e[r++]=t&255|kN,t>>>=7;return e[r]=t|0,tL.bytes=r-n+1,e}var Zne=gI,Yne=128,_N=127;function gI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw gI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&_N)<<s:(o&_N)*Math.pow(2,s),s+=7}while(o>=Yne);return gI.bytes=a-n,r}var Qne=Math.pow(2,7),Xne=Math.pow(2,14),ese=Math.pow(2,21),tse=Math.pow(2,28),rse=Math.pow(2,35),nse=Math.pow(2,42),sse=Math.pow(2,49),ise=Math.pow(2,56),ose=Math.pow(2,63),ase=function(t){return t<Qne?1:t<Xne?2:t<ese?3:t<tse?4:t<rse?5:t<nse?6:t<sse?7:t<ise?8:t<ose?9:10},cse={encode:Wne,decode:Zne,encodingLength:ase},dse=cse,z1=dse,q1=(t,e=0)=>[z1.decode(t,e),z1.decode.bytes],ww=(t,e,r=0)=>(z1.encode(t,e,r),e),vw=t=>z1.encodingLength(t),use=(t,e)=>{let r=e.byteLength,n=vw(t),s=n+vw(r),a=new Uint8Array(s+r);return ww(t,a,0),ww(r,a,n),a.set(e,s),new zI(t,r,e,a)},lse=t=>{let e=KI(t),[r,n]=q1(e),[s,a]=q1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new zI(r,s,o,e)},fse=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Mne(t.bytes,r.bytes)}},zI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},TN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return hse(r,wI(t),e||Go.encoder);default:return mse(r,wI(t),e||x1.encoder)}},IN=new WeakMap,wI=t=>{let e=IN.get(t);if(e==null){let r=new Map;return IN.set(t,r),r}return e},Qje=class Xs{constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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:r}=this;if(e!==Jg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Xs.createV0(r)}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:r}=this.multihash,n=use(e,r);return Xs.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 Xs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&fse(e.multihash,n.multihash)}toString(e){return TN(this,e)}toJSON(){return{"/":TN(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 r=e;if(r instanceof Xs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Xs(n,s,a,o||AN(n,s,a.bytes))}else if(r[gse]===!0){let{version:n,multihash:s,code:a}=r,o=lse(s);return Xs.create(n,a,o)}else return null}static create(e,r,n){if(typeof r!="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(r!==Jg)throw new Error(`Version 0 CID must use dag-pb (code: ${Jg}) block encoding`);return new Xs(e,r,n,n.bytes)}case 1:{let s=AN(e,r,n.bytes);return new Xs(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Xs.create(0,Jg,e)}static createV1(e,r){return Xs.create(1,e,r)}static decode(e){let[r,n]=Xs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Xs.inspectBytes(e),n=r.size-r.multihashSize,s=KI(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=s.subarray(r.multihashSize-r.digestSize),o=new zI(r.multihashCode,r.digestSize,a,s);return[r.version===0?Xs.createV0(o):Xs.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=q1(e.subarray(r));return r+=f,l},s=n(),a=Jg;if(s===18?(s=0,r=0):a=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=r,i=n(),c=n(),u=r+c,d=u-o;return{version:s,codec:a,multihashCode:i,digestSize:c,multihashSize:d,size:u}}static parse(e,r){let[n,s]=pse(e,r),a=Xs.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return wI(a).set(n,e),a}},pse=(t,e)=>{switch(t[0]){case"Q":{let r=e||Go;return[Go.prefix,r.decode(`${Go.prefix}${t}`)]}case Go.prefix:{let r=e||Go;return[Go.prefix,r.decode(t)]}case x1.prefix:{let r=e||x1;return[x1.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},hse=(t,e,r)=>{let{prefix:n}=r;if(n!==Go.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return s},mse=(t,e,r)=>{let{prefix:n}=r,s=e.get(n);if(s==null){let a=r.encode(t);return e.set(n,a),a}else return s},Jg=112,yse=18,AN=(t,e,r)=>{let n=vw(t),s=n+vw(e),a=new Uint8Array(s+r.byteLength);return ww(t,a,0),ww(e,a,n),a.set(r,s),a},gse=Symbol.for("@ipld/js-cid/CID"),Jo=class Lu{static addPrefix(e){var r;let{code:n,data:s,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=Lu.codeToName.has(n)?n:Lu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=tw.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),tw.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=tw.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Lu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Lu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Lu.codeToName.set(e.code,e.name),Lu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=tw.decode(r),a=Lu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Jo.codeToName=new Map;Jo.nameToCode=new Map;Jo.registerCodec({code:237,name:"ed25519-pub"});Jo.registerCodec({code:4864,name:"ed25519-priv"});Jo.registerCodec({code:236,name:"x25519-pub"});Jo.registerCodec({code:4866,name:"x25519-priv"});Jo.registerCodec({code:231,name:"secp256k1-pub"});Jo.registerCodec({code:4865,name:"secp256k1-priv"});function rL(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&rL(t[e])})}var Xje=Df(VU(),1),Ru=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},wse=class{constructor(){this.store=new Map}clear(){return Ru(this,void 0,void 0,function*(){this.store.clear()})}open(){return Ru(this,void 0,void 0,function*(){})}close(){return Ru(this,void 0,void 0,function*(){})}delete(t){return Ru(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Ru(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Ru(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Ru(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Ru(this,void 0,void 0,function*(){this.store.set(t,e)})}},rP=class{},nL={};NI(nL,{bitGet:()=>kse,bitLen:()=>Ese,bitMask:()=>FI,bitSet:()=>_se,bytesToHex:()=>If,bytesToNumberBE:()=>kf,bytesToNumberLE:()=>Gu,concatBytes:()=>Af,createHmacDrbg:()=>oL,ensureBytes:()=>Cn,equalBytes:()=>xse,hexToBytes:()=>Fh,hexToNumber:()=>qI,isBytes:()=>Sc,numberToBytesBE:()=>Ec,numberToBytesLE:()=>Gh,numberToHexUnpadded:()=>iL,numberToVarBytesBE:()=>Pse,utf8ToBytes:()=>Sse,validateObject:()=>Cf});var sL=BigInt(0),nP=BigInt(1),vse=BigInt(2);function Sc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var bse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function If(t){if(!Sc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=bse[t[r]];return e}function iL(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function qI(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var yd={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function RN(t){if(t>=yd._0&&t<=yd._9)return t-yd._0;if(t>=yd._A&&t<=yd._F)return t-(yd._A-10);if(t>=yd._a&&t<=yd._f)return t-(yd._a-10)}function Fh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let s=0,a=0;s<r;s++,a+=2){let o=RN(t.charCodeAt(a)),i=RN(t.charCodeAt(a+1));if(o===void 0||i===void 0){let c=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[s]=o*16+i}return n}function kf(t){return qI(If(t))}function Gu(t){if(!Sc(t))throw new Error("Uint8Array expected");return qI(If(Uint8Array.from(t).reverse()))}function Ec(t,e){return Fh(t.toString(16).padStart(e*2,"0"))}function Gh(t,e){return Ec(t,e).reverse()}function Pse(t){return Fh(iL(t))}function Cn(t,e,r){let n;if(typeof e=="string")try{n=Fh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(Sc(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(`${t} expected ${r} bytes, got ${s}`);return n}function Af(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!Sc(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let s=0;s<t.length;s++){let a=t[s];r.set(a,n),n+=a.length}return r}function xse(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Sse(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Ese(t){let e;for(e=0;t>sL;t>>=nP,e+=1);return e}function kse(t,e){return t>>BigInt(e)&nP}var _se=(t,e,r)=>t|(r?nP:sL)<<BigInt(e),FI=t=>(vse<<BigInt(t-1))-nP,oI=t=>new Uint8Array(t),DN=t=>Uint8Array.from(t);function oL(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=oI(t),s=oI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=oI())=>{s=i(DN([0]),d),n=i(),d.length!==0&&(s=i(DN([1]),d),n=i())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,l=[];for(;d<e;){n=i();let f=n.slice();l.push(f),d+=n.length}return Af(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var Tse={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Sc(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Cf(t,e,r={}){let n=(s,a,o)=>{let i=Tse[a];if(typeof i!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=t[s];if(!(o&&c===void 0)&&!i(c,t))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${a}`)};for(let[s,a]of Object.entries(e))n(s,a,!1);for(let[s,a]of Object.entries(r))n(s,a,!0);return t}function CN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Ise(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function aL(t,...e){if(!Ise(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Ase(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");CN(t.outputLen),CN(t.blockLen)}function F1(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Rse(t,e){aL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var aI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function cL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var cI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,Dse=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Dse)throw new Error("Non little-endian hardware is not supported");function dL(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function GI(t){if(typeof t=="string"&&(t=dL(t)),!cL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function uL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!cL(s))throw new Error("Uint8Array expected");e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let a=t[n];r.set(a,s),s+=a.length}return r}var lL=class{clone(){return this._cloneInto()}},e$e={}.toString;function fL(t){let e=n=>t().update(GI(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function WI(t=32){if(aI&&typeof aI.getRandomValues=="function")return aI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Cse(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var pL=class extends lL{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=cI(this.buffer)}update(t){F1(this);let{view:e,buffer:r,blockLen:n}=this;t=GI(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=cI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){F1(this),Rse(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let d=a;d<n;d++)e[d]=0;Cse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=cI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},jse=(t,e,r)=>t&e^~t&r,$se=(t,e,r)=>t&e^t&r^e&r,Mse=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]),Du=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cu=new Uint32Array(64),Ose=class extends pL{constructor(){super(64,32,8,!1),this.A=Du[0]|0,this.B=Du[1]|0,this.C=Du[2]|0,this.D=Du[3]|0,this.E=Du[4]|0,this.F=Du[5]|0,this.G=Du[6]|0,this.H=Du[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)Cu[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Cu[d-15],f=Cu[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;Cu[d]=p+Cu[d-7]+h+Cu[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=mc(o,6)^mc(o,11)^mc(o,25),f=u+l+jse(o,i,c)+Mse[d]+Cu[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+$se(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){Cu.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},hL=fL(()=>new Ose),Yn=BigInt(0),nn=BigInt(1),bf=BigInt(2),Bse=BigInt(3),vI=BigInt(4),jN=BigInt(5),$N=BigInt(8),t$e=BigInt(9),Nse=BigInt(16);function Kr(t,e){let r=t%e;return r>=Yn?r:e+r}function mL(t,e,r){if(r<=Yn||e<Yn)throw new Error("Expected power/modulo > 0");if(r===nn)return Yn;let n=nn;for(;e>Yn;)e&nn&&(n=n*t%r),t=t*t%r,e>>=nn;return n}function un(t,e,r){let n=t;for(;e-- >Yn;)n*=n,n%=r;return n}function bI(t,e){if(t===Yn||e<=Yn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Kr(t,e),n=e,s=Yn,a=nn,o=nn,i=Yn;for(;r!==Yn;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}if(n!==nn)throw new Error("invert: does not exist");return Kr(s,e)}function Use(t){let e=(t-nn)/bf,r,n,s;for(r=t-nn,n=0;r%bf===Yn;r/=bf,n++);for(s=bf;s<t&&mL(s,e,t)!==t-nn;s++);if(n===1){let o=(t+nn)/vI;return function(i,c){let u=i.pow(c,o);if(!i.eql(i.sqr(u),c))throw new Error("Cannot find square root");return u}}let a=(r+nn)/bf;return function(o,i){if(o.pow(i,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,s),r),d=o.pow(i,a),l=o.pow(i,r);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(l);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(u,nn<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function Lse(t){if(t%vI===Bse){let e=(t+nn)/vI;return function(r,n){let s=r.pow(n,e);if(!r.eql(r.sqr(s),n))throw new Error("Cannot find square root");return s}}if(t%$N===jN){let e=(t-jN)/$N;return function(r,n){let s=r.mul(n,bf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,bf),a),c=r.mul(o,r.sub(i,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return t%Nse,Use(t)}var Kse=(t,e)=>(Kr(t,e)&nn)===nn,zse=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qse(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=zse.reduce((n,s)=>(n[s]="function",n),e);return Cf(t,r)}function Fse(t,e,r){if(r<Yn)throw new Error("Expected power > 0");if(r===Yn)return t.ONE;if(r===nn)return e;let n=t.ONE,s=e;for(;r>Yn;)r&nn&&(n=t.mul(n,s)),s=t.sqr(s),r>>=nn;return n}function Gse(t,e){let r=new Array(e.length),n=e.reduce((a,o,i)=>t.is0(o)?a:(r[i]=a,t.mul(a,o)),t.ONE),s=t.inv(n);return e.reduceRight((a,o,i)=>t.is0(o)?a:(r[i]=t.mul(a,r[i]),t.mul(a,o)),s),r}function yL(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function VI(t,e,r=!1,n={}){if(t<=Yn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=yL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Lse(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:FI(s),ZERO:Yn,ONE:nn,create:c=>Kr(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Yn<=c&&c<t},is0:c=>c===Yn,isOdd:c=>(c&nn)===nn,neg:c=>Kr(-c,t),eql:(c,u)=>c===u,sqr:c=>Kr(c*c,t),add:(c,u)=>Kr(c+u,t),sub:(c,u)=>Kr(c-u,t),mul:(c,u)=>Kr(c*u,t),pow:(c,u)=>Fse(i,c,u),div:(c,u)=>Kr(c*bI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>bI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>Gse(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Gh(c,a):Ec(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Gu(c):kf(c)}});return Object.freeze(i)}function Wse(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function gL(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function wL(t){let e=gL(t);return e+Math.ceil(e/2)}function Vse(t,e,r=!1){let n=t.length,s=gL(e),a=wL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?kf(t):Gu(t),i=Kr(o,e-nn)+nn;return r?Gh(i,s):Ec(i,s)}var Hse=BigInt(0),dI=BigInt(1);function vL(t,e){let r=(s,a)=>{let o=a.negate();return s?o:a},n=s=>{let a=Math.ceil(e/s)+1,o=2**(s-1);return{windows:a,windowSize:o}};return{constTimeNegate:r,unsafeLadder(s,a){let o=t.ZERO,i=s;for(;a>Hse;)a&dI&&(o=o.add(i)),i=i.double(),a>>=dI;return o},precomputeWindow(s,a){let{windows:o,windowSize:i}=n(a),c=[],u=s,d=u;for(let l=0;l<o;l++){d=u,c.push(d);for(let f=1;f<i;f++)d=d.add(u),c.push(d);u=d.double()}return c},wNAF(s,a,o){let{windows:i,windowSize:c}=n(s),u=t.ZERO,d=t.BASE,l=BigInt(2**s-1),f=2**s,h=BigInt(s);for(let p=0;p<i;p++){let m=p*c,y=Number(o&l);o>>=h,y>c&&(y-=f,o+=dI);let S=m,v=m+Math.abs(y)-1,E=p%2!==0,_=y<0;y===0?d=d.add(r(E,a[S])):u=u.add(r(_,a[v]))}return{p:u,f:d}},wNAFCached(s,a,o,i){let c=s._WINDOW_SIZE||1,u=a.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&a.set(s,i(u))),this.wNAF(c,u,o)}}}function HI(t){return qse(t.Fp),Cf(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Jse(t){let e=HI(t);Cf(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Zse,hexToBytes:Yse}=nL,Sf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=Sf;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:Zse(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=Sf,r=typeof t=="string"?Yse(t):t;if(!Sc(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:s,l:a}=Sf._parseInt(r.subarray(2)),{d:o,l:i}=Sf._parseInt(a);if(i.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),s=e(r(t.r)),a=n.length/2,o=s.length/2,i=r(a),c=r(o);return`30${r(o+a+4)}02${c}${s}02${i}${n}`}},xd=BigInt(0),Fo=BigInt(1),r$e=BigInt(2),MN=BigInt(3),n$e=BigInt(4);function Qse(t){let e=Jse(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return Af(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),s=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),S=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:S}});function a(p){let{a:m,b:y}=e,S=r.sqr(p),v=r.mul(S,p);return r.add(r.add(v,r.mul(p,m)),y)}if(!r.eql(r.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function o(p){return typeof p=="bigint"&&xd<p&&p<e.n}function i(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:S,n:v}=e;if(m&&typeof p!="bigint"){if(Sc(p)&&(p=If(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:kf(Cn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Kr(E,v)),i(E),E}let u=new Map;function d(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,S){if(this.px=m,this.py=y,this.pz=S,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(m){let{x:y,y:S}=m||{};if(!m||!r.isValid(y)||!r.isValid(S))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let v=E=>r.eql(E,r.ZERO);return v(y)&&v(S)?l.ZERO:new l(y,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(S=>S.pz));return m.map((S,v)=>S.toAffine(y[v])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(s(Cn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let S=r.sqr(y),v=a(m);if(!r.eql(S,v))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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:_,pz:I}=m,R=r.eql(r.mul(y,I),r.mul(E,v)),N=r.eql(r.mul(S,I),r.mul(_,v));return R&&N}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,MN),{px:v,py:E,pz:_}=this,I=r.ZERO,R=r.ZERO,N=r.ZERO,$=r.mul(v,v),F=r.mul(E,E),z=r.mul(_,_),B=r.mul(v,E);return B=r.add(B,B),N=r.mul(v,_),N=r.add(N,N),I=r.mul(m,N),R=r.mul(S,z),R=r.add(I,R),I=r.sub(F,R),R=r.add(F,R),R=r.mul(I,R),I=r.mul(B,I),N=r.mul(S,N),z=r.mul(m,z),B=r.sub($,z),B=r.mul(m,B),B=r.add(B,N),N=r.add($,$),$=r.add(N,$),$=r.add($,z),$=r.mul($,B),R=r.add(R,$),z=r.mul(E,_),z=r.add(z,z),$=r.mul(z,B),I=r.sub(I,$),N=r.mul(z,F),N=r.add(N,N),N=r.add(N,N),new l(I,R,N)}add(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:_,pz:I}=m,R=r.ZERO,N=r.ZERO,$=r.ZERO,F=e.a,z=r.mul(e.b,MN),B=r.mul(y,E),W=r.mul(S,_),X=r.mul(v,I),D=r.add(y,S),C=r.add(E,_);D=r.mul(D,C),C=r.add(B,W),D=r.sub(D,C),C=r.add(y,v);let b=r.add(E,I);return C=r.mul(C,b),b=r.add(B,X),C=r.sub(C,b),b=r.add(S,v),R=r.add(_,I),b=r.mul(b,R),R=r.add(W,X),b=r.sub(b,R),$=r.mul(F,C),R=r.mul(z,X),$=r.add(R,$),R=r.sub(W,$),$=r.add(W,$),N=r.mul(R,$),W=r.add(B,B),W=r.add(W,B),X=r.mul(F,X),C=r.mul(z,C),W=r.add(W,X),X=r.sub(B,X),X=r.mul(F,X),C=r.add(C,X),B=r.mul(W,C),N=r.add(N,B),B=r.mul(b,C),R=r.mul(D,R),R=r.sub(R,B),B=r.mul(D,W),$=r.mul(b,$),$=r.add($,B),new l(R,N,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let S=r.invertBatch(y.map(v=>v.pz));return y.map((v,E)=>v.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===xd)return y;if(i(m),m===Fo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:v,k1:E,k2neg:_,k2:I}=S.splitScalar(m),R=y,N=y,$=this;for(;E>xd||I>xd;)E&Fo&&(R=R.add($)),I&Fo&&(N=N.add($)),$=$.double(),E>>=Fo,I>>=Fo;return v&&(R=R.negate()),_&&(N=N.negate()),N=new l(r.mul(N.px,S.beta),N.py,N.pz),R.add(N)}multiply(m){i(m);let y=m,S,v,{endo:E}=e;if(E){let{k1neg:_,k1:I,k2neg:R,k2:N}=E.splitScalar(y),{p:$,f:F}=this.wNAF(I),{p:z,f:B}=this.wNAF(N);$=h.constTimeNegate(_,$),z=h.constTimeNegate(R,z),z=new l(r.mul(z.px,E.beta),z.py,z.pz),S=$.add(z),v=F.add(B)}else{let{p:_,f:I}=this.wNAF(y);S=_,v=I}return l.normalizeZ([S,v])[0]}multiplyAndAddUnsafe(m,y,S){let v=l.BASE,E=(I,R)=>R===xd||R===Fo||!I.equals(v)?I.multiplyUnsafe(R):I.multiply(R),_=E(this,y).add(E(m,S));return _.is0()?void 0:_}toAffine(m){let{px:y,py:S,pz:v}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(v));let _=r.mul(y,m),I=r.mul(S,m),R=r.mul(v,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(R,r.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Fo)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Fo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return If(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=vL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function Xse(t){let e=HI(t);return Cf(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function eie(t){let e=Xse(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o(C){return xd<C&&C<r.ORDER}function i(C){return Kr(C,n)}function c(C){return bI(C,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=Qse({...e,toBytes(C,b,x){let P=b.toAffine(),k=r.toBytes(P.x),A=Af;return x?A(Uint8Array.from([b.hasEvenY()?2:3]),k):A(Uint8Array.from([4]),k,r.toBytes(P.y))},fromBytes(C){let b=C.length,x=C[0],P=C.subarray(1);if(b===s&&(x===2||x===3)){let k=kf(P);if(!o(k))throw new Error("Point is not on curve");let A=l(k),O=r.sqrt(A),q=(O&Fo)===Fo;return(x&1)===1!==q&&(O=r.neg(O)),{x:k,y:O}}else if(b===a&&x===4){let k=r.fromBytes(P.subarray(0,r.BYTES)),A=r.fromBytes(P.subarray(r.BYTES,2*r.BYTES));return{x:k,y:A}}else throw new Error(`Point of length ${b} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=C=>If(Ec(C,e.nByteLength));function p(C){let b=n>>Fo;return C>b}function m(C){return p(C)?i(-C):C}let y=(C,b,x)=>kf(C.slice(b,x));class S{constructor(b,x,P){this.r=b,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(b){let x=e.nByteLength;return b=Cn("compactSignature",b,x*2),new S(y(b,0,x),y(b,x,2*x))}static fromDER(b){let{r:x,s:P}=Sf.toSig(Cn("DER",b));return new S(x,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(b){return new S(this.r,this.s,b)}recoverPublicKey(b){let{r:x,s:P,recovery:k}=this,A=N(Cn("msgHash",b));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let O=k===2||k===3?x+e.n:x;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=k&1?"03":"02",G=u.fromHex(q+h(O)),V=c(O),H=i(-A*V),Y=i(P*V),K=u.BASE.multiplyAndAddUnsafe(G,H,Y);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Fh(this.toDERHex())}toDERHex(){return Sf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Fh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let v={isValidPrivateKey(C){try{return d(C),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let C=wL(e.n);return Vse(e.randomBytes(C),e.n)},precompute(C=8,b=u.BASE){return b._setWindowSize(C),b.multiply(BigInt(3)),b}};function E(C,b=!0){return u.fromPrivateKey(C).toRawBytes(b)}function _(C){let b=Sc(C),x=typeof C=="string",P=(b||x)&&C.length;return b?P===s||P===a:x?P===2*s||P===2*a:C instanceof u}function I(C,b,x=!0){if(_(C))throw new Error("first arg must be private key");if(!_(b))throw new Error("second arg must be public key");return u.fromHex(b).multiply(d(C)).toRawBytes(x)}let R=e.bits2int||function(C){let b=kf(C),x=C.length*8-e.nBitLength;return x>0?b>>BigInt(x):b},N=e.bits2int_modN||function(C){return i(R(C))},$=FI(e.nBitLength);function F(C){if(typeof C!="bigint")throw new Error("bigint expected");if(!(xd<=C&&C<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ec(C,e.nByteLength)}function z(C,b,x=B){if(["recovered","canonical"].some(se=>se in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:k}=e,{lowS:A,prehash:O,extraEntropy:q}=x;A==null&&(A=!0),C=Cn("msgHash",C),O&&(C=Cn("prehashed msgHash",P(C)));let G=N(C),V=d(b),H=[F(V),F(G)];if(q!=null){let se=q===!0?k(r.BYTES):q;H.push(Cn("extraEntropy",se))}let Y=Af(...H),K=G;function Q(se){let re=R(se);if(!f(re))return;let Z=c(re),de=u.BASE.multiply(re).toAffine(),le=i(de.x);if(le===xd)return;let pe=i(Z*i(K+le*V));if(pe===xd)return;let ve=(de.x===le?0:2)|Number(de.y&Fo),ce=pe;return A&&p(pe)&&(ce=m(pe),ve^=1),new S(le,ce,ve)}return{seed:Y,k2sig:Q}}let B={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function X(C,b,x=B){let{seed:P,k2sig:k}=z(C,b,x),A=e;return oL(A.hash.outputLen,A.nByteLength,A.hmac)(P,k)}u.BASE._setWindowSize(8);function D(C,b,x,P=W){let k=C;if(b=Cn("msgHash",b),x=Cn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:O}=P,q,G;try{if(typeof k=="string"||Sc(k))try{q=S.fromDER(k)}catch(Z){if(!(Z instanceof Sf.Err))throw Z;q=S.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Z,s:de}=k;q=new S(Z,de)}else throw new Error("PARSE");G=u.fromHex(x)}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;O&&(b=e.hash(b));let{r:V,s:H}=q,Y=N(b),K=c(H),Q=i(Y*K),se=i(V*K),re=u.BASE.multiplyAndAddUnsafe(G,Q,se)?.toAffine();return re?i(re.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:I,sign:X,verify:D,ProjectivePoint:u,Signature:S,utils:v}}var bL=class extends lL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ase(t);let r=GI(e);if(this.iHash=t.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,s=new Uint8Array(n);s.set(r.length>n?t.create().update(r).digest():r);for(let a=0;a<s.length;a++)s[a]^=54;this.iHash.update(s),this.oHash=t.create();for(let a=0;a<s.length;a++)s[a]^=106;this.oHash.update(s),s.fill(0)}update(t){return F1(this),this.iHash.update(t),this}digestInto(t){F1(this),aL(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:r,finished:n,destroyed:s,blockLen:a,outputLen:o}=this;return t=t,t.finished=n,t.destroyed=s,t.blockLen=a,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},PL=(t,e,r)=>new bL(t,e).update(r).digest();PL.create=(t,e)=>new bL(t,e);function tie(t){return{hash:t,hmac:(e,...r)=>PL(t,e,uL(...r)),randomBytes:WI}}function xL(t,e){let r=n=>eie({...t,...tie(n)});return Object.freeze({...r(e),create:r})}var SL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ON=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),rie=BigInt(1),PI=BigInt(2),BN=(t,e)=>(t+e/PI)/e;function nie(t){let e=SL,r=BigInt(3),n=BigInt(6),s=BigInt(11),a=BigInt(22),o=BigInt(23),i=BigInt(44),c=BigInt(88),u=t*t*t%e,d=u*u*t%e,l=un(d,r,e)*d%e,f=un(l,r,e)*d%e,h=un(f,PI,e)*u%e,p=un(h,s,e)*h%e,m=un(p,a,e)*p%e,y=un(m,i,e)*m%e,S=un(y,c,e)*y%e,v=un(S,i,e)*m%e,E=un(v,r,e)*d%e,_=un(E,o,e)*p%e,I=un(_,n,e)*u%e,R=un(I,PI,e);if(!xI.eql(xI.sqr(R),t))throw new Error("Cannot find square root");return R}var xI=VI(SL,void 0,void 0,{sqrt:nie}),po=xL({a:BigInt(0),b:BigInt(7),Fp:xI,n:ON,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=ON,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-rie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=BN(a*t,e),c=BN(-n*t,e),u=Kr(t-i*r-c*s,e),d=Kr(-i*n-c*a,e),l=u>o,f=d>o;if(l&&(u=e-u),f&&(d=e-d),u>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:f,k2:d}}}},hL),s$e=BigInt(0),i$e=po.ProjectivePoint;function sie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function EL(t,...e){if(!sie(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function NN(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function iie(t,e){EL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var S1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,uI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),yc=(t,e)=>t<<32-e|t>>>e,o$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function oie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function kL(t){return typeof t=="string"&&(t=oie(t)),EL(t),t}var aie=class{clone(){return this._cloneInto()}},a$e={}.toString;function cie(t){let e=n=>t().update(kL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function die(t=32){if(S1&&typeof S1.getRandomValues=="function")return S1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function uie(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var lie=(t,e,r)=>t&e^~t&r,fie=(t,e,r)=>t&e^t&r^e&r,pie=class extends aie{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=uI(this.buffer)}update(t){NN(this);let{view:e,buffer:r,blockLen:n}=this;t=kL(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=uI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){NN(this),iie(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let d=a;d<n;d++)e[d]=0;uie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=uI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},hie=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]),ju=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$u=new Uint32Array(64),mie=class extends pie{constructor(){super(64,32,8,!1),this.A=ju[0]|0,this.B=ju[1]|0,this.C=ju[2]|0,this.D=ju[3]|0,this.E=ju[4]|0,this.F=ju[5]|0,this.G=ju[6]|0,this.H=ju[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)$u[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=$u[d-15],f=$u[d-2],h=yc(l,7)^yc(l,18)^l>>>3,p=yc(f,17)^yc(f,19)^f>>>10;$u[d]=p+$u[d-7]+h+$u[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=yc(o,6)^yc(o,11)^yc(o,25),f=u+l+lie(o,i,c)+hie[d]+$u[d]|0,h=(yc(r,2)^yc(r,13)^yc(r,22))+fie(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){$u.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},bw=cie(()=>new mie);function yie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort(),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var gie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},_L=class{static digest(t){return gie(this,arguments,void 0,function*({data:e}){return bw(e)})}},wie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},UN="urn:jwk:";function pr(t){return wie(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);rL(n);let s=yie(n),a=Qe.string(s).toUint8Array(),o=yield _L.digest({data:a});return Qe.uint8Array(o).toBase64Url()})}function _f(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function JI(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function kd(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function ZI(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function vie(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var Rs=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},bie=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},$s=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=po.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return po.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){let n=yield wc.privateKeyToBytes({privateKey:r}),s=yield wc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return po.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return po.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=po.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=bie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(this,arguments,void 0,function*({publicKey:r}){if(!(JI(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Rs(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield wc.privateKeyToBytes({privateKey:r}),a=yield wc.publicKeyToBytes({publicKey:n});return po.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Rs(this,arguments,void 0,function*({data:r,key:n}){let s=yield wc.privateKeyToBytes({privateKey:n}),a=bw(r);return po.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return po.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{po.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Rs(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield wc.publicKeyToBytes({publicKey:r}),o=bw(s);return po.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=po.getPublicKey(r));let n=po.ProjectivePoint.fromHex(r),s=Ec(n.x,32),a=Ec(n.y,32);return{x:s,y:a}})}},TL=VI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Pie=TL.create(BigInt("-3")),xie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Sie=xL({a:Pie,b:xie,Fp:TL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hL),Uo=Sie,Ds=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Eie=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},ei=class vc{static adjustSignatureToLowS(e){return Ds(this,arguments,void 0,function*({signature:r}){let n=Uo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ds(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield vc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield vc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static compressPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){return Uo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ds(this,arguments,void 0,function*({key:r}){let n=yield vc.privateKeyToBytes({privateKey:r}),s=yield vc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertDerToCompactSignature(e){return Ds(this,arguments,void 0,function*({derSignature:r}){return Uo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){return Uo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ds(this,void 0,void 0,function*(){let e=Uo.utils.randomPrivateKey(),r=yield vc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Ds(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=Eie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Ds(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ds(this,arguments,void 0,function*({publicKey:r}){if(!(JI(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Ds(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield vc.privateKeyToBytes({privateKey:r}),a=yield vc.publicKeyToBytes({publicKey:n});return Uo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Ds(this,arguments,void 0,function*({data:r,key:n}){let s=yield vc.privateKeyToBytes({privateKey:n}),a=bw(r);return Uo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Ds(this,arguments,void 0,function*({privateKeyBytes:r}){return Uo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ds(this,arguments,void 0,function*({publicKeyBytes:r}){try{Uo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ds(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield vc.publicKeyToBytes({publicKey:r}),o=bw(s);return Uo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Ds(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Uo.getPublicKey(r));let n=Uo.ProjectivePoint.fromHex(r),s=Ec(n.x,32),a=Ec(n.y,32);return{x:s,y:a}})}},gd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},LN=class extends rP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ei.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ei.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield $s.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ei.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield $s.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield ei.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield $s.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ei.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield $s.sign({key:e,data:r});case"P-256":return yield ei.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return gd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!JI(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield $s.verify({key:e,signature:r,data:n});case"P-256":return yield ei.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return gd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield $s.privateKeyToBytes({privateKey:e});case"P-256":return yield ei.privateKeyToBytes({privateKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield $s.publicKeyToBytes({publicKey:e});case"P-256":return yield ei.publicKeyToBytes({publicKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m1=BigInt(4294967295),SI=BigInt(32);function IL(t,e=!1){return e?{h:Number(t&m1),l:Number(t>>SI&m1)}:{h:Number(t>>SI&m1)|0,l:Number(t&m1)|0}}function kie(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:a,l:o}=IL(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var _ie=(t,e)=>BigInt(t>>>0)<<SI|BigInt(e>>>0),Tie=(t,e,r)=>t>>>r,Iie=(t,e,r)=>t<<32-r|e>>>r,Aie=(t,e,r)=>t>>>r|e<<32-r,Rie=(t,e,r)=>t<<32-r|e>>>r,Die=(t,e,r)=>t<<64-r|e>>>r-32,Cie=(t,e,r)=>t>>>r-32|e<<64-r,jie=(t,e)=>e,$ie=(t,e)=>t,Mie=(t,e,r)=>t<<r|e>>>32-r,Oie=(t,e,r)=>e<<r|t>>>32-r,Bie=(t,e,r)=>e<<r-32|t>>>64-r,Nie=(t,e,r)=>t<<r-32|e>>>64-r;function Uie(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var Lie=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Kie=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,zie=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),qie=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,Fie=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),Gie=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,Wie={fromBig:IL,split:kie,toBig:_ie,shrSH:Tie,shrSL:Iie,rotrSH:Aie,rotrSL:Rie,rotrBH:Die,rotrBL:Cie,rotr32H:jie,rotr32L:$ie,rotlSH:Mie,rotlSL:Oie,rotlBH:Bie,rotlBL:Nie,add:Uie,add3L:Lie,add3H:Kie,add4L:zie,add4H:qie,add5H:Gie,add5L:Fie},Rt=Wie,[Vie,Hie]=Rt.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(t=>BigInt(t))),Mu=new Uint32Array(80),Ou=new Uint32Array(80),Jie=class extends pL{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:t,Al:e,Bh:r,Bl:n,Ch:s,Cl:a,Dh:o,Dl:i,Eh:c,El:u,Fh:d,Fl:l,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m]}set(t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=i|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let v=0;v<16;v++,e+=4)Mu[v]=t.getUint32(e),Ou[v]=t.getUint32(e+=4);for(let v=16;v<80;v++){let E=Mu[v-15]|0,_=Ou[v-15]|0,I=Rt.rotrSH(E,_,1)^Rt.rotrSH(E,_,8)^Rt.shrSH(E,_,7),R=Rt.rotrSL(E,_,1)^Rt.rotrSL(E,_,8)^Rt.shrSL(E,_,7),N=Mu[v-2]|0,$=Ou[v-2]|0,F=Rt.rotrSH(N,$,19)^Rt.rotrBH(N,$,61)^Rt.shrSH(N,$,6),z=Rt.rotrSL(N,$,19)^Rt.rotrBL(N,$,61)^Rt.shrSL(N,$,6),B=Rt.add4L(R,z,Ou[v-7],Ou[v-16]),W=Rt.add4H(B,I,F,Mu[v-7],Mu[v-16]);Mu[v]=W|0,Ou[v]=B|0}let{Ah:r,Al:n,Bh:s,Bl:a,Ch:o,Cl:i,Dh:c,Dl:u,Eh:d,El:l,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:S}=this;for(let v=0;v<80;v++){let E=Rt.rotrSH(d,l,14)^Rt.rotrSH(d,l,18)^Rt.rotrBH(d,l,41),_=Rt.rotrSL(d,l,14)^Rt.rotrSL(d,l,18)^Rt.rotrBL(d,l,41),I=d&f^~d&p,R=l&h^~l&m,N=Rt.add5L(S,_,R,Hie[v],Ou[v]),$=Rt.add5H(N,y,E,I,Vie[v],Mu[v]),F=N|0,z=Rt.rotrSH(r,n,28)^Rt.rotrBH(r,n,34)^Rt.rotrBH(r,n,39),B=Rt.rotrSL(r,n,28)^Rt.rotrBL(r,n,34)^Rt.rotrBL(r,n,39),W=r&s^r&o^s&o,X=n&a^n&i^a&i;y=p|0,S=m|0,p=f|0,m=h|0,f=d|0,h=l|0,{h:d,l}=Rt.add(c|0,u|0,$|0,F|0),c=o|0,u=i|0,o=s|0,i=a|0,s=r|0,a=n|0;let D=Rt.add3L(F,B,X);r=Rt.add3H(D,$,z,W),n=D|0}({h:r,l:n}=Rt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Rt.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Rt.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Rt.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Rt.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Rt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Rt.add(this.Hh|0,this.Hl|0,y|0,S|0),this.set(r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S)}roundClean(){Mu.fill(0),Ou.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)}},AL=fL(()=>new Jie),Ta=BigInt(0),lo=BigInt(1),y1=BigInt(2),Zie=BigInt(8),Yie={zip215:!0};function Qie(t){let e=HI(t);return Cf(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function YI(t){let e=Qie(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=y1<<BigInt(i*8)-lo,d=r.create,l=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:r.sqrt(x*r.inv(P))}}catch{return{isValid:!1,value:Ta}}}),f=e.adjustScalarBytes||(x=>x),h=e.domain||((x,P,k)=>{if(P.length||k)throw new Error("Contexts/pre-hash are not supported");return x}),p=x=>typeof x=="bigint"&&Ta<x,m=(x,P)=>p(x)&&p(P)&&x<P,y=x=>x===Ta||m(x,u);function S(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function v(x){return x===Ta?x:S(x,n)}let E=new Map;function _(x){if(!(x instanceof I))throw new Error("ExtendedPoint expected")}class I{constructor(P,k,A,O){if(this.ex=P,this.ey=k,this.ez=A,this.et=O,!y(P))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(A))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof I)throw new Error("extended point not allowed");let{x:k,y:A}=P||{};if(!y(k)||!y(A))throw new Error("invalid affine point");return new I(k,A,lo,d(k*A))}static normalizeZ(P){let k=r.invertBatch(P.map(A=>A.ez));return P.map((A,O)=>A.toAffine(k[O])).map(I.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:O,ez:q,et:G}=this,V=d(A*A),H=d(O*O),Y=d(q*q),K=d(Y*Y),Q=d(V*P),se=d(Y*d(Q+H)),re=d(K+d(k*d(V*H)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Z=d(A*O),de=d(q*G);if(Z!==de)throw new Error("bad point: equation left != right (2)")}equals(P){_(P);let{ex:k,ey:A,ez:O}=this,{ex:q,ey:G,ez:V}=P,H=d(k*V),Y=d(q*O),K=d(A*V),Q=d(G*O);return H===Y&&K===Q}is0(){return this.equals(I.ZERO)}negate(){return new I(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:k,ey:A,ez:O}=this,q=d(k*k),G=d(A*A),V=d(y1*d(O*O)),H=d(P*q),Y=k+A,K=d(d(Y*Y)-q-G),Q=H+G,se=Q-V,re=H-G,Z=d(K*se),de=d(Q*re),le=d(K*re),pe=d(se*Q);return new I(Z,de,pe,le)}add(P){_(P);let{a:k,d:A}=e,{ex:O,ey:q,ez:G,et:V}=this,{ex:H,ey:Y,ez:K,et:Q}=P;if(k===BigInt(-1)){let Et=d((q-O)*(Y+H)),Se=d((q+O)*(Y-H)),et=d(Se-Et);if(et===Ta)return this.double();let wt=d(G*y1*Q),St=d(V*y1*K),Mt=St+wt,T=Se+Et,M=St-wt,L=d(Mt*et),te=d(T*M),ae=d(Mt*M),he=d(et*T);return new I(L,te,he,ae)}let se=d(O*H),re=d(q*Y),Z=d(V*A*Q),de=d(G*K),le=d((O+q)*(H+Y)-se-re),pe=de-Z,ve=de+Z,ce=d(re-k*se),ge=d(le*pe),Me=d(ve*ce),Le=d(le*ce),qe=d(pe*ve);return new I(ge,Me,qe,Le)}subtract(P){return this.add(P.negate())}wNAF(P){return $.wNAFCached(this,E,P,I.normalizeZ)}multiply(P){let{p:k,f:A}=this.wNAF(S(P,n));return I.normalizeZ([k,A])[0]}multiplyUnsafe(P){let k=v(P);return k===Ta?N:this.equals(N)||k===lo?this:this.equals(R)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(P){let{ex:k,ey:A,ez:O}=this,q=this.is0();P==null&&(P=q?Zie:r.inv(O));let G=d(k*P),V=d(A*P),H=d(O*P);if(q)return{x:Ta,y:lo};if(H!==lo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:P}=e;return P===lo?this:this.multiplyUnsafe(P)}static fromHex(P,k=!1){let{d:A,a:O}=e,q=r.BYTES;P=Cn("pointHex",P,q);let G=P.slice(),V=P[q-1];G[q-1]=V&-129;let H=Gu(G);H===Ta||(k?S(H,u):S(H,r.ORDER));let Y=d(H*H),K=d(Y-lo),Q=d(A*Y-O),{isValid:se,value:re}=l(K,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Z=(re&lo)===lo,de=(V&128)!==0;if(!k&&re===Ta&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Z&&(re=d(-re)),I.fromAffine({x:re,y:H})}static fromPrivateKey(P){return B(P).point}toRawBytes(){let{x:P,y:k}=this.toAffine(),A=Gh(k,r.BYTES);return A[A.length-1]|=P&lo?128:0,A}toHex(){return If(this.toRawBytes())}}I.BASE=new I(e.Gx,e.Gy,lo,d(e.Gx*e.Gy)),I.ZERO=new I(Ta,lo,lo,Ta);let{BASE:R,ZERO:N}=I,$=vL(I,i*8);function F(x){return Kr(x,n)}function z(x){return F(Gu(x))}function B(x){let P=i;x=Cn("private key",x,P);let k=Cn("hashed private key",a(x),2*P),A=f(k.slice(0,P)),O=k.slice(P,2*P),q=z(A),G=R.multiply(q),V=G.toRawBytes();return{head:A,prefix:O,scalar:q,point:G,pointBytes:V}}function W(x){return B(x).pointBytes}function X(x=new Uint8Array,...P){let k=Af(...P);return z(a(h(k,Cn("context",x),!!s)))}function D(x,P,k={}){x=Cn("message",x),s&&(x=s(x));let{prefix:A,scalar:O,pointBytes:q}=B(P),G=X(k.context,A,x),V=R.multiply(G).toRawBytes(),H=X(k.context,V,q,x),Y=F(G+H*O);v(Y);let K=Af(V,Gh(Y,r.BYTES));return Cn("result",K,i*2)}let C=Yie;function b(x,P,k,A=C){let{context:O,zip215:q}=A,G=r.BYTES;x=Cn("signature",x,2*G),P=Cn("message",P),s&&(P=s(P));let V=Gu(x.slice(G,2*G)),H,Y,K;try{H=I.fromHex(k,q),Y=I.fromHex(x.slice(0,G),q),K=R.multiplyUnsafe(V)}catch{return!1}if(!q&&H.isSmallOrder())return!1;let Q=X(O,Y.toRawBytes(),H.toRawBytes(),P);return Y.add(H.multiplyUnsafe(Q)).subtract(K).clearCofactor().equals(I.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:D,verify:b,ExtendedPoint:I,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(r.BYTES),precompute(x=8,P=I.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}var Zg=BigInt(0),lI=BigInt(1);function Xie(t){return Cf(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function eoe(t){let e=Xie(t),{P:r}=e,n=E=>Kr(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>mL(E,r-BigInt(2),r));function u(E,_,I){let R=n(E*(_-I));return _=n(_-R),I=n(I+R),[_,I]}function d(E){if(typeof E=="bigint"&&Zg<=E&&E<r)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(e.a-BigInt(2))/BigInt(4);function f(E,_){let I=d(E),R=d(_),N=I,$=lI,F=Zg,z=I,B=lI,W=Zg,X;for(let C=BigInt(s-1);C>=Zg;C--){let b=R>>C&lI;W^=b,X=u(W,$,z),$=X[0],z=X[1],X=u(W,F,B),F=X[0],B=X[1],W=b;let x=$+F,P=n(x*x),k=$-F,A=n(k*k),O=P-A,q=z+B,G=z-B,V=n(G*x),H=n(q*k),Y=V+H,K=V-H;z=n(Y*Y),B=n(N*n(K*K)),$=n(P*A),F=n(O*(P+n(l*O)))}X=u(W,$,z),$=X[0],z=X[1],X=u(W,F,B),F=X[0],B=X[1];let D=c(F);return n($*D)}function h(E){return Gh(n(E),a)}function p(E){let _=Cn("u coordinate",E,a);return o===32&&(_[31]&=127),Gu(_)}function m(E){let _=Cn("scalar",E),I=_.length;if(I!==a&&I!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${I}`);return Gu(i(_))}function y(E,_){let I=p(_),R=m(E),N=f(I,R);if(N===Zg)throw new Error("Invalid private or public key received");return h(N)}let S=h(e.Gu);function v(E){return y(E,S)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>v(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Pw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),KN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c$e=BigInt(0),toe=BigInt(1),EI=BigInt(2),roe=BigInt(5),zN=BigInt(10),noe=BigInt(20),soe=BigInt(40),qN=BigInt(80);function RL(t){let e=Pw,r=t*t%e*t%e,n=un(r,EI,e)*r%e,s=un(n,toe,e)*t%e,a=un(s,roe,e)*s%e,o=un(a,zN,e)*a%e,i=un(o,noe,e)*o%e,c=un(i,soe,e)*i%e,u=un(c,qN,e)*c%e,d=un(u,qN,e)*c%e,l=un(d,zN,e)*a%e;return{pow_p_5_8:un(l,EI,e)*t%e,b2:r}}function DL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ioe(t,e){let r=Pw,n=Kr(e*e*e,r),s=Kr(n*n*e,r),a=RL(t*s).pow_p_5_8,o=Kr(t*n*a,r),i=Kr(e*o*o,r),c=o,u=Kr(o*KN,r),d=i===t,l=i===Kr(-t,r),f=i===Kr(-t*KN,r);return d&&(o=c),(l||f)&&(o=u),Kse(o,r)&&(o=Kr(-o,r)),{isValid:d||l,value:o}}var Ho=VI(Pw,void 0,!0),xw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ho,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:AL,randomBytes:WI,adjustScalarBytes:DL,uvRatio:ioe},wf=YI(xw);function CL(t,e,r){if(e.length>255)throw new Error("Context is too big");return uL(dL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var d$e=YI({...xw,domain:CL}),u$e=YI({...xw,domain:CL,prehash:AL}),rw=eoe({P:Pw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Pw,{pow_p_5_8:r,b2:n}=RL(t);return Kr(un(r,BigInt(3),e)*n,e)},adjustScalarBytes:DL,randomBytes:WI});function ooe(t){let{y:e}=wf.ExtendedPoint.fromHex(t),r=BigInt(1);return Ho.toBytes(Ho.create((r+e)*Ho.inv(r-e)))}function aoe(t){let e=xw.hash(t.subarray(0,32));return xw.adjustScalarBytes(e).subarray(0,32)}var coe=(Ho.ORDER+BigInt(3))/BigInt(8),l$e=Ho.pow(EI,coe),f$e=Ho.sqrt(Ho.neg(Ho.ONE)),p$e=(Ho.ORDER-BigInt(5))/BigInt(8),h$e=BigInt(486662),m$e=Wse(Ho,Ho.neg(BigInt(486664))),y$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),g$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),w$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),v$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),b$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Lo=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},doe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Ms=class Ku{static bytesToPrivateKey(e){return Lo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=wf.getPublicKey(r),s={crv:"Ed25519",d:Qe.uint8Array(r).toBase64Url(),kty:"OKP",x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Lo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield pr({jwk:n}),n})}static computePublicKey(e){return Lo(this,arguments,void 0,function*({key:r}){let n=yield Ku.privateKeyToBytes({privateKey:r}),s=wf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Lo(this,arguments,void 0,function*({privateKey:r}){let n=yield Ku.privateKeyToBytes({privateKey:r}),s=aoe(n),a=rw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Qe.uint8Array(s).toBase64Url(),x:Qe.uint8Array(a).toBase64Url()};return o.kid=yield pr({jwk:o}),o})}static convertPublicKeyToX25519(e){return Lo(this,arguments,void 0,function*({publicKey:r}){let n=yield Ku.publicKeyToBytes({publicKey:r});if(!(yield Ku.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=ooe(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static generateKey(){return Lo(this,void 0,void 0,function*(){let e=wf.utils.randomPrivateKey(),r=yield Ku.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Lo(this,arguments,void 0,function*({key:r}){var n;if(!(kd(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=doe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Lo(this,arguments,void 0,function*({privateKey:r}){if(!kd(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Lo(this,arguments,void 0,function*({publicKey:r}){if(!ZI(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sign(e){return Lo(this,arguments,void 0,function*({key:r,data:n}){let s=yield Ku.privateKeyToBytes({privateKey:r});return wf.sign(n,s)})}static validatePublicKey(e){return Lo(this,arguments,void 0,function*({publicKeyBytes:r}){try{wf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Lo(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Ku.publicKeyToBytes({publicKey:r});return wf.verify(n,s,a)})}},wd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},uoe=class extends rP{bytesToPrivateKey(t){return wd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Ms.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return wd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Ms.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return wd(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Ms.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return wd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield Ms.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return wd(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Ms.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return wd(this,arguments,void 0,function*({key:e,data:r}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield Ms.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return wd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!ZI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield Ms.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return wd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield Ms.privateKeyToBytes({privateKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return wd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield Ms.publicKeyToBytes({publicKey:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},loe=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},foe=class extends rP{digest(t){return loe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield _L.digest({data:r})}})}},Bu=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},poe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},jh=class nw{static bytesToPrivateKey(e){return Bu(this,arguments,void 0,function*({privateKeyBytes:r}){let n=rw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield pr({jwk:s}),s})}static bytesToPublicKey(e){return Bu(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield pr({jwk:n}),n})}static computePublicKey(e){return Bu(this,arguments,void 0,function*({key:r}){let n=yield nw.privateKeyToBytes({privateKey:r}),s=rw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield pr({jwk:a}),a})}static generateKey(){return Bu(this,void 0,void 0,function*(){let e=rw.utils.randomPrivateKey(),r=yield nw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield pr({jwk:r}),r})}static getPublicKey(e){return Bu(this,arguments,void 0,function*({key:r}){var n;if(!(kd(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=poe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield pr({jwk:a})),a})}static privateKeyToBytes(e){return Bu(this,arguments,void 0,function*({privateKey:r}){if(!kd(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Bu(this,arguments,void 0,function*({publicKey:r}){if(!ZI(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Bu(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let s=yield nw.privateKeyToBytes({privateKey:r}),a=yield nw.publicKeyToBytes({publicKey:n});return rw.getSharedSecret(s,a)})}},Yg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},hoe=class extends rP{bytesToPrivateKey(t){return Yg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return jh.bytesToPrivateKey({privateKeyBytes:r});default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Yg(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return jh.computePublicKey({key:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Yg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return jh.generateKey();default:throw new Vo(Ki.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Yg(this,arguments,void 0,function*({key:e}){if(!kd(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return jh.getPublicKey({key:e});default:throw new Vo(Ki.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Yg(this,arguments,void 0,function*({privateKey:e}){return jh.privateKeyToBytes({privateKey:e})})}},vd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},fI={Ed25519:{implementation:uoe,names:["Ed25519"]},secp256k1:{implementation:LN,names:["ES256K","secp256k1"]},secp256r1:{implementation:LN,names:["ES256","secp256r1"]},"SHA-256":{implementation:foe,names:["SHA-256"]},X25519:{implementation:hoe,names:["X25519"]}},Ra=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new wse}digest(t){return vd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return vd(this,arguments,void 0,function*({algorithm:e}){let r=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(r?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${UN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return vd(this,arguments,void 0,function*({key:e}){let r=yield pr({jwk:e});return`${UN}${r}`})}getPublicKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){let r=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:r})})}importKey(t){return vd(this,arguments,void 0,function*({key:e}){var r;if(!vie(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(r=n.kid)!==null&&r!==void 0||(n.kid=yield pr({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return vd(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),s=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:s}).sign({data:r,key:n})})}verify(t){return vd(this,arguments,void 0,function*({key:e,signature:r,data:n}){let s=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:s}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=fI[t])===null||e===void 0?void 0:e.implementation;if(!r)throw new Error(`Algorithm not supported: ${t}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:t}){let e=t.alg,r=t.crv;for(let n in fI){let s=fI[n];if(e&&s.names.includes(e)||r&&s.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return vd(this,arguments,void 0,function*({keyUri:e}){let r=yield this._keyStore.get(e);if(!r)throw new Error(`Key not found: ${e}`);return r})}},moe=class kI{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return die(e)}static randomUuid(){return S1.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 r=Math.pow(10,e)-1,n;if(e<=6){let s=Math.pow(10,e);do{let a=kI.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%s}while(n>r)}else{let s=Math.pow(10,10);do{let a=kI.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%s}while(n>r)}return n.toString().padStart(e,"0")}},yoe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function goe(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(t)?"Array":t instanceof Uint8Array?"Uint8Array":t.constructor===Object?"Object":woe(t)||"Object"}function woe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(yoe.includes(e))return e}var Pe=class{constructor(t,e,r){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,e){return t===e||t.major===e.major&&t.name===e.name}};Pe.uint=new Pe(0,"uint",!0);Pe.negint=new Pe(1,"negint",!0);Pe.bytes=new Pe(2,"bytes",!0);Pe.string=new Pe(3,"string",!0);Pe.array=new Pe(4,"array",!1);Pe.map=new Pe(5,"map",!1);Pe.tag=new Pe(6,"tag",!1);Pe.float=new Pe(7,"float",!0);Pe.false=new Pe(7,"false",!0);Pe.true=new Pe(7,"true",!0);Pe.null=new Pe(7,"null",!0);Pe.undefined=new Pe(7,"undefined",!0);Pe.break=new Pe(7,"break",!0);var Je=class{constructor(t,e,r){this.type=t,this.value=e,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},Iw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",voe=new TextEncoder;function G1(t){return Iw&&globalThis.Buffer.isBuffer(t)}function jL(t){return t instanceof Uint8Array?G1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var boe=24,Poe=200,xoe=Iw?t=>t.length>=boe?globalThis.Buffer.from(t):FN(t):t=>t.length>=Poe?voe.encode(t):FN(t),bd=t=>Uint8Array.from(t),Soe=Iw?(t,e,r)=>G1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Eoe=Iw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),jL(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let s of t)n+s.length>r.length&&(s=s.subarray(0,r.length-n)),r.set(s,n),n+=s.length;return r},koe=Iw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function $L(t,e){if(G1(t)&&G1(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function FN(t){let e=[],r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=s&63|128):(s&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}return e}var _oe=256,ML=class{constructor(t=_oe){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let r=e.length-(this.maxCursor-this.cursor)-1;e.set(t,r)}else{if(e){let r=e.length-(this.maxCursor-this.cursor)-1;r<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,r),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=koe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=Soe(r,0,this.cursor)}else e=Eoe(this.chunks,this.cursor);return t&&this.reset(),e}},Toe=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let e=this.dest.subarray(0,this.cursor);return t&&this.reset(),e}},ln="CBOR decode error:",OL="CBOR encode error:",Aw=[];Aw[23]=1;Aw[24]=2;Aw[25]=3;Aw[26]=5;Aw[27]=9;function Zh(t,e,r){if(t.length-e<r)throw new Error(`${ln} not enough data for type`)}var Os=[24,256,65536,4294967296,BigInt("18446744073709551616")];function jf(t,e,r){Zh(t,e,1);let n=t[e];if(r.strict===!0&&n<Os[0])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Zh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Os[1])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function Mf(t,e,r){Zh(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Os[2])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);return n}function Of(t,e,r){Zh(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],s=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(s);if(r.strict===!0&&a<Os[3])throw new Error(`${ln} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(r.allowBigInt===!0)return a;throw new Error(`${ln} integers outside of the safe integer range are not supported`)}function Ioe(t,e,r,n){return new Je(Pe.uint,jf(t,e+1,n),2)}function Aoe(t,e,r,n){return new Je(Pe.uint,$f(t,e+1,n),3)}function Roe(t,e,r,n){return new Je(Pe.uint,Mf(t,e+1,n),5)}function Doe(t,e,r,n){return new Je(Pe.uint,Of(t,e+1,n),9)}function Bf(t,e){return Zo(t,0,e.value)}function Zo(t,e,r){if(r<Os[0]){let n=Number(r);t.push([e|n])}else if(r<Os[1]){let n=Number(r);t.push([e|24,n])}else if(r<Os[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Os[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<Os[4]){let s=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=a&255,a=a>>8,s[7]=a&255,a=a>>8,s[6]=a&255,a=a>>8,s[5]=a&255,s[4]=o&255,o=o>>8,s[3]=o&255,o=o>>8,s[2]=o&255,o=o>>8,s[1]=o&255,t.push(s)}else throw new Error(`${ln} encountered BigInt larger than allowable range`)}}Bf.encodedSize=function(t){return Zo.encodedSize(t.value)};Zo.encodedSize=function(t){return t<Os[0]?1:t<Os[1]?2:t<Os[2]?3:t<Os[3]?5:9};Bf.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Coe(t,e,r,n){return new Je(Pe.negint,-1-jf(t,e+1,n),2)}function joe(t,e,r,n){return new Je(Pe.negint,-1-$f(t,e+1,n),3)}function $oe(t,e,r,n){return new Je(Pe.negint,-1-Mf(t,e+1,n),5)}var QI=BigInt(-1),BL=BigInt(1);function Moe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s!="bigint"){let a=-1-s;if(a>=Number.MIN_SAFE_INTEGER)return new Je(Pe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${ln} integers outside of the safe integer range are not supported`);return new Je(Pe.negint,QI-BigInt(s),9)}function XI(t,e){let r=e.value,n=typeof r=="bigint"?r*QI-BL:r*-1-1;Zo(t,e.type.majorEncoded,n)}XI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*QI-BL:e*-1-1;return r<Os[0]?1:r<Os[1]?2:r<Os[2]?3:r<Os[3]?5:9};XI.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Rw(t,e,r,n){Zh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Je(Pe.bytes,s,r+n)}function Ooe(t,e,r,n){return Rw(t,e,1,r)}function Boe(t,e,r,n){return Rw(t,e,2,jf(t,e+1,n))}function Noe(t,e,r,n){return Rw(t,e,3,$f(t,e+1,n))}function Uoe(t,e,r,n){return Rw(t,e,5,Mf(t,e+1,n))}function Loe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer bytes lengths not supported`);return Rw(t,e,9,s)}function W1(t){return t.encodedBytes===void 0&&(t.encodedBytes=Pe.equals(t.type,Pe.string)?xoe(t.value):t.value),t.encodedBytes}function sP(t,e){let r=W1(e);Zo(t,e.type.majorEncoded,r.length),t.push(r)}sP.encodedSize=function(t){let e=W1(t);return Zo.encodedSize(e.length)+e.length};sP.compareTokens=function(t,e){return Koe(W1(t),W1(e))};function Koe(t,e){return t.length<e.length?-1:t.length>e.length?1:$L(t,e)}var GN=new TextDecoder,zoe=32;function qoe(t,e,r){if(r-e<zoe){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return GN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return GN.decode(t.subarray(e,r))}function Dw(t,e,r,n,s){let a=r+n;Zh(t,e,a);let o=new Je(Pe.string,qoe(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function Foe(t,e,r,n){return Dw(t,e,1,r,n)}function Goe(t,e,r,n){return Dw(t,e,2,jf(t,e+1,n),n)}function Woe(t,e,r,n){return Dw(t,e,3,$f(t,e+1,n),n)}function Voe(t,e,r,n){return Dw(t,e,5,Mf(t,e+1,n),n)}function Hoe(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer string lengths not supported`);return Dw(t,e,9,s,n)}var Joe=sP;function Yh(t,e,r,n){return new Je(Pe.array,n,r)}function Zoe(t,e,r,n){return Yh(t,e,1,r)}function Yoe(t,e,r,n){return Yh(t,e,2,jf(t,e+1,n))}function Qoe(t,e,r,n){return Yh(t,e,3,$f(t,e+1,n))}function Xoe(t,e,r,n){return Yh(t,e,5,Mf(t,e+1,n))}function eae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer array lengths not supported`);return Yh(t,e,9,s)}function tae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function eA(t,e){Zo(t,Pe.array.majorEncoded,e.value)}eA.compareTokens=Bf.compareTokens;eA.encodedSize=function(t){return Zo.encodedSize(t.value)};function Qh(t,e,r,n){return new Je(Pe.map,n,r)}function rae(t,e,r,n){return Qh(t,e,1,r)}function nae(t,e,r,n){return Qh(t,e,2,jf(t,e+1,n))}function sae(t,e,r,n){return Qh(t,e,3,$f(t,e+1,n))}function iae(t,e,r,n){return Qh(t,e,5,Mf(t,e+1,n))}function oae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${ln} 64-bit integer map lengths not supported`);return Qh(t,e,9,s)}function aae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return Qh(t,e,1,1/0)}function tA(t,e){Zo(t,Pe.map.majorEncoded,e.value)}tA.compareTokens=Bf.compareTokens;tA.encodedSize=function(t){return Zo.encodedSize(t.value)};function cae(t,e,r,n){return new Je(Pe.tag,r,1)}function dae(t,e,r,n){return new Je(Pe.tag,jf(t,e+1,n),2)}function uae(t,e,r,n){return new Je(Pe.tag,$f(t,e+1,n),3)}function lae(t,e,r,n){return new Je(Pe.tag,Mf(t,e+1,n),5)}function fae(t,e,r,n){return new Je(Pe.tag,Of(t,e+1,n),9)}function rA(t,e){Zo(t,Pe.tag.majorEncoded,e.value)}rA.compareTokens=Bf.compareTokens;rA.encodedSize=function(t){return Zo.encodedSize(t.value)};var NL=20,UL=21,LL=22,KL=23;function pae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${ln} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Je(Pe.null,null,1):new Je(Pe.undefined,void 0,1)}function hae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${ln} indefinite length items not allowed`);return new Je(Pe.break,void 0,1)}function nA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${ln} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${ln} Infinity values are not supported`)}return new Je(Pe.float,t,e)}function mae(t,e,r,n){return nA(iA(t,e+1),3,n)}function yae(t,e,r,n){return nA(oA(t,e+1),5,n)}function gae(t,e,r,n){return nA(GL(t,e+1),9,n)}function sA(t,e,r){let n=e.value;if(n===!1)t.push([Pe.float.majorEncoded|NL]);else if(n===!0)t.push([Pe.float.majorEncoded|UL]);else if(n===null)t.push([Pe.float.majorEncoded|LL]);else if(n===void 0)t.push([Pe.float.majorEncoded|KL]);else{let s,a=!1;(!r||r.float64!==!0)&&(qL(n),s=iA(Ia,1),n===s||Number.isNaN(n)?(Ia[0]=249,t.push(Ia.slice(0,3)),a=!0):(FL(n),s=oA(Ia,1),n===s&&(Ia[0]=250,t.push(Ia.slice(0,5)),a=!0))),a||(wae(n),s=GL(Ia,1),Ia[0]=251,t.push(Ia.slice(0,9)))}}sA.encodedSize=function(t,e){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!e||e.float64!==!0){qL(r);let n=iA(Ia,1);if(r===n||Number.isNaN(r))return 3;if(FL(r),n=oA(Ia,1),r===n)return 5}return 9};var zL=new ArrayBuffer(9),zo=new DataView(zL,1),Ia=new Uint8Array(zL,0);function qL(t){if(t===1/0)zo.setUint16(0,31744,!1);else if(t===-1/0)zo.setUint16(0,64512,!1);else if(Number.isNaN(t))zo.setUint16(0,32256,!1);else{zo.setFloat32(0,t);let e=zo.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)zo.setUint16(0,31744,!1);else if(r===0)zo.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?zo.setUint16(0,0):s<-14?zo.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):zo.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function iA(t,e){if(t.length-e<2)throw new Error(`${ln} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,s=r&1023,a;return n===0?a=s*2**-24:n!==31?a=(s+1024)*2**(n-25):a=s===0?1/0:NaN,r&32768?-a:a}function FL(t){zo.setFloat32(0,t,!1)}function oA(t,e){if(t.length-e<4)throw new Error(`${ln} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function wae(t){zo.setFloat64(0,t,!1)}function GL(t,e){if(t.length-e<8)throw new Error(`${ln} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}sA.compareTokens=Bf.compareTokens;function sr(t,e,r){throw new Error(`${ln} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function iP(t){return()=>{throw new Error(`${ln} ${t}`)}}var Ce=[];for(let t=0;t<=23;t++)Ce[t]=sr;Ce[24]=Ioe;Ce[25]=Aoe;Ce[26]=Roe;Ce[27]=Doe;Ce[28]=sr;Ce[29]=sr;Ce[30]=sr;Ce[31]=sr;for(let t=32;t<=55;t++)Ce[t]=sr;Ce[56]=Coe;Ce[57]=joe;Ce[58]=$oe;Ce[59]=Moe;Ce[60]=sr;Ce[61]=sr;Ce[62]=sr;Ce[63]=sr;for(let t=64;t<=87;t++)Ce[t]=Ooe;Ce[88]=Boe;Ce[89]=Noe;Ce[90]=Uoe;Ce[91]=Loe;Ce[92]=sr;Ce[93]=sr;Ce[94]=sr;Ce[95]=iP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)Ce[t]=Foe;Ce[120]=Goe;Ce[121]=Woe;Ce[122]=Voe;Ce[123]=Hoe;Ce[124]=sr;Ce[125]=sr;Ce[126]=sr;Ce[127]=iP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)Ce[t]=Zoe;Ce[152]=Yoe;Ce[153]=Qoe;Ce[154]=Xoe;Ce[155]=eae;Ce[156]=sr;Ce[157]=sr;Ce[158]=sr;Ce[159]=tae;for(let t=160;t<=183;t++)Ce[t]=rae;Ce[184]=nae;Ce[185]=sae;Ce[186]=iae;Ce[187]=oae;Ce[188]=sr;Ce[189]=sr;Ce[190]=sr;Ce[191]=aae;for(let t=192;t<=215;t++)Ce[t]=cae;Ce[216]=dae;Ce[217]=uae;Ce[218]=lae;Ce[219]=fae;Ce[220]=sr;Ce[221]=sr;Ce[222]=sr;Ce[223]=sr;for(let t=224;t<=243;t++)Ce[t]=iP("simple values are not supported");Ce[244]=sr;Ce[245]=sr;Ce[246]=sr;Ce[247]=pae;Ce[248]=iP("simple values are not supported");Ce[249]=mae;Ce[250]=yae;Ce[251]=gae;Ce[252]=sr;Ce[253]=sr;Ce[254]=sr;Ce[255]=hae;var Td=[];for(let t=0;t<24;t++)Td[t]=new Je(Pe.uint,t,1);for(let t=-1;t>=-24;t--)Td[31-t]=new Je(Pe.negint,t,1);Td[64]=new Je(Pe.bytes,new Uint8Array(0),1);Td[96]=new Je(Pe.string,"",1);Td[128]=new Je(Pe.array,0,1);Td[160]=new Je(Pe.map,0,1);Td[244]=new Je(Pe.false,!1,1);Td[245]=new Je(Pe.true,!0,1);Td[246]=new Je(Pe.null,null,1);function vae(t){switch(t.type){case Pe.false:return bd([244]);case Pe.true:return bd([245]);case Pe.null:return bd([246]);case Pe.bytes:return t.value.length?void 0:bd([64]);case Pe.string:return t.value===""?bd([96]):void 0;case Pe.array:return t.value===0?bd([128]):void 0;case Pe.map:return t.value===0?bd([160]):void 0;case Pe.uint:return t.value<24?bd([Number(t.value)]):void 0;case Pe.negint:if(t.value>=-24)return bd([31-Number(t.value)])}}var bae=Object.freeze({float64:!0,mapSorter:kae,quickEncodeToken:vae});function Pae(){let t=[];return t[Pe.uint.major]=Bf,t[Pe.negint.major]=XI,t[Pe.bytes.major]=sP,t[Pe.string.major]=Joe,t[Pe.array.major]=eA,t[Pe.map.major]=tA,t[Pe.tag.major]=rA,t[Pe.float.major]=sA,t}var xae=Pae(),Sae=new ML,WN=class WL{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${OL} object contains circular references`);return new WL(r,e)}},Nu={null:new Je(Pe.null,null),undefined:new Je(Pe.undefined,void 0),true:new Je(Pe.true,!0),false:new Je(Pe.false,!1),emptyArray:new Je(Pe.array,0),emptyMap:new Je(Pe.map,0)},Vu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Je(Pe.float,t):t>=0?new Je(Pe.uint,t):new Je(Pe.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Je(Pe.uint,t):new Je(Pe.negint,t)},Uint8Array(t,e,r,n){return new Je(Pe.bytes,t)},string(t,e,r,n){return new Je(Pe.string,t)},boolean(t,e,r,n){return t?Nu.true:Nu.false},null(t,e,r,n){return Nu.null},undefined(t,e,r,n){return Nu.undefined},ArrayBuffer(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Nu.emptyArray,new Je(Pe.break)]:Nu.emptyArray;n=WN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=E1(o,r,n);return r.addBreakTokens?[new Je(Pe.array,t.length),s,new Je(Pe.break)]:[new Je(Pe.array,t.length),s]},Object(t,e,r,n){let s=e!=="Object",a=s?t.keys():Object.keys(t),o=s?t.size:a.length,i;if(o){i=new Array(o),n=WN.createCheck(n,t);let c=!s&&r.ignoreUndefinedProperties,u=0;for(let d of a){let l=s?t.get(d):t[d];c&&l===void 0||(i[u++]=[E1(d,r,n),E1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(Eae(i,r),r.addBreakTokens?[new Je(Pe.map,i.length),i,new Je(Pe.break)]:[new Je(Pe.map,i.length),i]):r.addBreakTokens===!0?[Nu.emptyMap,new Je(Pe.break)]:Nu.emptyMap}};Vu.Map=Vu.Object;Vu.Buffer=Vu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Vu[`${t}Array`]=Vu.DataView;function E1(t,e={},r){let n=goe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Vu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Vu[n];if(!a)throw new Error(`${OL} unsupported type: ${n}`);return a(t,n,e,r)}function Eae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function kae(t,e){if(t[0]instanceof Je&&e[0]instanceof Je){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=VN(r.value)),n._keyBytes||(n._keyBytes=VN(n.value)),$L(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function VN(t){return _ae(t,xae,bae)}function VL(t,e,r,n){if(Array.isArray(e))for(let s of e)VL(t,s,r,n);else r[e.type.major](t,e,n)}var P$e=Pe.uint.majorEncoded,x$e=Pe.negint.majorEncoded,S$e=Pe.bytes.majorEncoded,E$e=Pe.string.majorEncoded,k$e=Pe.array.majorEncoded,_$e=Pe.float.majorEncoded|NL,T$e=Pe.float.majorEncoded|UL,I$e=Pe.float.majorEncoded|LL,A$e=Pe.float.majorEncoded|KL,R$e=BigInt(-1),D$e=BigInt(1);function _ae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new Toe(n):Sae,o=E1(t,r);if(!Array.isArray(o)&&r.quickEncodeToken){let i=r.quickEncodeToken(o);if(i)return s?(a.push(i),a.toBytes()):i;let c=e[o.type.major];if(c.encodedSize){let u=c.encodedSize(o,r);if(s||(a=new ML(u)),c(a,o,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return s?a.toBytes():jL(a.chunks[0])}}return a.reset(),VL(a,o,e,r),a.toBytes(!0)}var C$e=Symbol.for("DONE"),j$e=Symbol.for("BREAK"),HN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(HN||(HN={}));var ti;(function(t){t[t.P256=1]="P256",t[t.P384=2]="P384",t[t.P521=3]="P521",t[t.X25519=4]="X25519",t[t.X448=5]="X448",t[t.Ed25519=6]="Ed25519",t[t.Ed448=7]="Ed448",t[t.Secp256k1=8]="Secp256k1"})(ti||(ti={}));var Wo;(function(t){t[t.EdDSA=-8]="EdDSA",t[t.ES256=-7]="ES256",t[t.ES384=-35]="ES384",t[t.ES512=-36]="ES512",t[t.ES256K=-47]="ES256K"})(Wo||(Wo={}));var JN;(function(t){t[t.Kty=1]="Kty",t[t.Kid=2]="Kid",t[t.Alg=3]="Alg",t[t.KeyOps=4]="KeyOps",t[t.BaseIv=5]="BaseIv"})(JN||(JN={}));var ZN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(ZN||(ZN={}));var $$e={"P-256":ti.P256,"P-384":ti.P384,"P-521":ti.P521,X25519:ti.X25519,Ed25519:ti.Ed25519,Ed448:ti.Ed448,secp256k1:ti.Secp256k1},M$e={[ti.P256]:"P-256",[ti.P384]:"P-384",[ti.P521]:"P-521",[ti.X25519]:"X25519",[ti.Ed25519]:"Ed25519",[ti.Ed448]:"Ed448",[ti.Secp256k1]:"secp256k1"},O$e={EdDSA:Wo.EdDSA,ES256:Wo.ES256,ES384:Wo.ES384,ES512:Wo.ES512,ES256K:Wo.ES256K},B$e={[Wo.EdDSA]:"EdDSA",[Wo.ES256]:"ES256",[Wo.ES384]:"ES384",[Wo.ES512]:"ES512",[Wo.ES256K]:"ES256K"},YN;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(YN||(YN={}));var QN;(function(t){t[t.Iss=1]="Iss",t[t.Sub=2]="Sub",t[t.Aud=3]="Aud",t[t.Exp=4]="Exp",t[t.Nbf=5]="Nbf",t[t.Iat=6]="Iat",t[t.Cti=7]="Cti",t[t.Nonce=10]="Nonce",t[t.Ueid=256]="Ueid",t[t.Sueids=257]="Sueids",t[t.Oemid=258]="Oemid",t[t.Hwmodel=259]="Hwmodel",t[t.Hwversion=260]="Hwversion",t[t.Secboot=262]="Secboot",t[t.Dbgstat=263]="Dbgstat",t[t.Location=264]="Location",t[t.Profile=265]="Profile",t[t.Submods=266]="Submods",t[t.Measres=272]="Measres",t[t.Intuse=268]="Intuse"})(QN||(QN={}));var XN;(function(t){t[t.Enabled=0]="Enabled",t[t.Disabled=1]="Disabled",t[t.DisabledSinceBoot=2]="DisabledSinceBoot",t[t.DisabledPermanently=3]="DisabledPermanently",t[t.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(XN||(XN={}));var eU;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(eU||(eU={}));var Tae={};NI(Tae,{extractDidFragment:()=>ki,getServices:()=>Iae,getVerificationMethodByKey:()=>Aae,getVerificationMethodTypes:()=>HL,getVerificationMethods:()=>oP,getVerificationRelationshipsById:()=>JL,isDidService:()=>ZL,isDidVerificationMethod:()=>V1,isDwnDidService:()=>Rae,isPortableDid:()=>Dae,keyBytesToMultibaseId:()=>YL,multibaseIdToKeyBytes:()=>QL});function ki(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Iae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Aae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=oP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await pr({jwk:e})===await pr({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function oP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(V1)??[]),Object.keys(tP).forEach(r=>{e.push(...t[r]?.filter(V1)??[])}),e}function HL({didDocument:t}){let e=oP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function JL({didDocument:t,methodId:e}){let r=[];return Object.keys(tP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=ki(e);s.some(o=>{let i=ki(o)===a,c=V1(o)&&ki(o.id)===a;return i||c})&&r.push(n)}}),r}function ZL(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Rae(t){return!(!ZL(t)||t.type!=="DecentralizedWebNode")}function V1(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Dae(t){return!(!t||typeof t!="object"||t===null)&&"uri"in t&&"document"in t&&"metadata"in t&&(!("keyManager"in t)||t.keyManager===void 0)}function YL({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Jo.addPrefix({code:e,data:t,name:r}),s=Qe.uint8Array(n).toBase58Btc();return Qe.base58Btc(s).toMultibase()}function QL({multibaseKeyId:t}){try{let e=Qe.multibase(t).toBase58Btc(),r=Qe.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Jo.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new Ze("invalidDid",`Invalid multibase identifier: ${t}`)}}var kc=class XL{constructor({uri:e,document:r,metadata:n,keyManager:s}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=s}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 r=[];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 s=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:s});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(o=>ki(o.id)===(ki(e?.methodId)??ki(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),s=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:moe.getJoseSignatureAlgorithmFromPublicKey(s),keyId:r.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:i}){return await a.verify({data:o,key:s,signature:i})}}}static async import({portableDid:e,keyManager:r=new Ra}){let n=oP({didDocument:e.document});if(n.length===0)throw new Ze("invalidDidDocument","At least one verification method is required but 0 were given");for(let s of e.privateKeys??[]){let a=await r.getKeyUri({key:s});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.importKey({key:s})}for(let s of n){if(!s.publicKeyJwk)throw new Error(`Verification method '${s.id}' does not contain a public key in JWK format`);let a=await r.getKeyUri({key:s.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new XL({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Cw=class{static async getSigningMethod(t){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(t,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},eK=(t=>(t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution",t))(eK||{}),aA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(aA||{}),tK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(tK||{}),tU="0123456789abcdef",rK=[],rU=[];for(let t=0;t<256;t++)rK[t]=tU[t>>4&15]+tU[t&15],t<16&&(t<10?rU[48+t]=t:rU[87+t]=t);var Cae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=rK[t[n++]];return r},jae=(t,e=0)=>{let r=t.length||0;if(!e){let o=r;for(;o--;)e+=t[o].length}let n=new Uint8Array(e),s=e,a=r;for(;a--;)s-=t[a].length,n.set(t[a],s);return n},nU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$ae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Qg=0;Qg<nU.length;Qg++)$ae[nU.charCodeAt(Qg)]=Qg;var Qg,Mae=new TextDecoder,nK=(t,e)=>e?new TextDecoder(e).decode(t):Mae.decode(t),Oae=new TextEncoder,_d=t=>Oae.encode(t),sU=typeof window<"u"?window:self,iU=sU.crypto||sU.msCrypto||{},N$e=iU.subtle||iU.webkitSubtle;function jw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function sK(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function dr(t,e,r){let n=[],s=null;return dr._encode(n,t),s=jae(n),dr.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}dr.bytes=-1;dr._floatConversionDetected=!1;dr._encode=function(t,e){if(e!=null)switch(sK(e)){case"object":dr.dict(t,e);break;case"map":dr.dictMap(t,e);break;case"array":dr.list(t,e);break;case"set":dr.listSet(t,e);break;case"string":dr.string(t,e);break;case"number":dr.number(t,e);break;case"boolean":dr.number(t,e);break;case"arraybufferview":dr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":dr.buffer(t,new Uint8Array(e));break}};var aP=new Uint8Array([101]),iK=new Uint8Array([100]),oK=new Uint8Array([108]);dr.buffer=function(t,e){t.push(_d(e.length+":"),e)};dr.string=function(t,e){t.push(_d(_d(e).byteLength+":"+e))};dr.number=function(t,e){if(Number.isInteger(e))return t.push(_d("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(_d("i"+a+"e")),a!==e&&!dr._floatConversionDetected&&(dr._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};dr.dict=function(t,e){t.push(iK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(dr.string(t,n),dr._encode(t,e[n]));t.push(aP)};dr.dictMap=function(t,e){t.push(iK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?dr._encode(t,n):dr.string(t,String(n)),dr._encode(t,e.get(n)));t.push(aP)};dr.list=function(t,e){let r=0,n=e.length;for(t.push(oK);r<n;r++)e[r]!=null&&dr._encode(t,e[r]);t.push(aP)};dr.listSet=function(t,e){t.push(oK);for(let r of e)r!=null&&dr._encode(t,r);t.push(aP)};var Bae=dr,Nae=105,Uae=58,Lae=100,Kae=108,cA=101;function aK(t,e,r){let n=0,s=1;for(let a=e;a<r;a++){let o=t[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){s=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*s}function lt(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),lt.position=0,lt.encoding=n||null,lt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):_d(t),lt.bytes=lt.data.length,lt.next())}lt.bytes=0;lt.position=0;lt.data=null;lt.encoding=null;lt.next=function(){switch(lt.data[lt.position]){case Lae:return lt.dictionary();case Kae:return lt.list();case Nae:return lt.integer();default:return lt.buffer()}};lt.find=function(t){let e=lt.position,r=lt.data.length,n=lt.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};lt.dictionary=function(){lt.position++;let t={};for(;lt.data[lt.position]!==cA;){let e=lt.buffer(),r=nK(e);r.includes("\uFFFD")&&(r=Cae(e)),t[r]=lt.next()}return lt.position++,t};lt.list=function(){lt.position++;let t=[];for(;lt.data[lt.position]!==cA;)t.push(lt.next());return lt.position++,t};lt.integer=function(){let t=lt.find(cA),e=aK(lt.data,lt.position+1,t);return lt.position+=t+1-lt.position,e};lt.buffer=function(){let t=lt.find(Uae),e=aK(lt.data,lt.position,t),r=++t+e;return lt.position=r,lt.encoding?nK(lt.data.slice(t,r)):lt.data.slice(t,r)};var zae=lt;function qae(t){let e=2;for(let r of t)e+=cP(r);return e}function Fae(t){let e=2;for(let[r,n]of t){let s=_d(r).byteLength;e+=jw(s)+1+s,e+=cP(n)}return e}function Gae(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=_d(r[n]).byteLength;e+=jw(s)+1+s,e+=cP(t[r[n]])}return e}function Wae(t){let e=_d(t).byteLength;return jw(e)+1+e}function Vae(t){let e=t.byteLength-t.byteOffset;return jw(e)+1+e}function cP(t){if(t==null)return 0;let e=sK(t);switch(e){case"arraybufferview":return Vae(t);case"string":return Wae(t);case"array":case"set":return qae(t);case"number":return 1+jw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return Gae(t);case"map":return Fae(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var cK=cP,Hae=cK,dK={encode:Bae,decode:zae,byteLength:cK,encodingLength:Hae},Jae=/^(\d{1,3}\.){3,3}\d{1,3}$/,Zae=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,xc={name:"v4",size:4,isFormat:t=>Jae.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,s=0;for(let a=0;a<n;){let o=t.charCodeAt(a++);o===46?(e[r++]=s,s=0):s=s*10+(o-48)}return e[r]=s,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},Wu={name:"v6",size:16,isFormat:t=>t.length>0&&Zae.test(t),encode(t,e,r){r=~~r;let n=r+16,s=-1,a=0,o=0,i=!0,c=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(i?s!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(s=r):(c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,o=0),i=!0,c=!1):d===46?(r<n&&(e[r]=o),r++,o=0,a=0,i=!1,c=!0):(i=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(i===!1)c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(s===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(s!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=s+2;u--)e[u]=e[u-2];e[s]=0,e[s+1]=0,s=r}if(s!==r&&s!==-1)for(r>n-2&&(r=n-2);n>s;)e[--n]=r<n&&r>s?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function uK(t){if(xc.isFormat(t))return xc.size;if(Wu.isFormat(t))return Wu.size;throw Error(`Invalid ip address: ${t}`)}function Yae(t){return uK(t)===xc.size?1:2}function Qae(t,e,r){r=~~r;let n=uK(t);return typeof e=="function"&&(e=e(r+n)),n===xc.size?xc.encode(t,e,r):Wu.encode(t,e,r)}function Xae(t,e,r){if(e=~~e,r=r||t.length-e,r===xc.size)return xc.decode(t,e,r);if(r===Wu.size)return Wu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${xc.size} for v4 or ${Wu.size} for v6.`)}function dP(t){switch(t){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_"+t}function Sw(t){switch(t.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 t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}function ece(t){switch(t){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_"+t}function tce(t){switch(t){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_"+t}function lK(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function fK(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function rce(t){switch(t){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 t<0?null:`OPTION_${t}`}function oU(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.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=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function pK(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let s=t.charCodeAt(n);if(s<=127)e+=1;else if(s<=2047)e+=2;else if((s&63488)!==55296)e+=3;else{let a=n+1;a===r||s>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Ew(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(pK(t)+r));let s=r;for(let a=0;a<n;a+=1){let o=t.charCodeAt(a);if(o<=127)e[s++]=o;else if(o<=2047)e[s++]=192|(o&1984)>>6,e[s++]=128|o&63;else if((o&63488)!==55296)e[s++]=224|(o&61440)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63;else{let i=a+1;if(i===n||o>=56320)e[s++]=239,e[s++]=191,e[s++]=189;else{let c=t.charCodeAt(i);(c&64512)!==56320?(e[s++]=239,e[s++]=191,e[s++]=189):(a=i,o=65536|(o&1023)<<10|c&1023,e[s++]=240|(o&1835008)>>18,e[s++]=128|(o&258048)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63)}}}return Ew.bytes=s-r,e}Ew.bytes=0;function $w(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let s=e;s<r;){let a=t[s++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|t[s++]&63;else if(a>239&&a<365){o=((a&7)<<18|(t[s++]&63)<<12|(t[s++]&63)<<6|t[s++]&63)-65536;let i=55296|o>>10&1023;n+=String.fromCharCode(i),o=56320|o&1023}else o=(a&15)<<12|(t[s++]&63)<<6|t[s++]&63;n+=String.fromCharCode(o)}return $w.bytes=r-e,n}$w.bytes=0;var Rf=t=>t instanceof Uint8Array;function Hu(t){return typeof t=="string"?pK(t):t.byteLength}function dA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Ew(t)}function uA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Ew(e,t,r),Ew.bytes}var sw={},hK=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let s=n.toString(16),a=s.toUpperCase(),o=t<<4|n,i=`${e}${s}`;hK[o]=i,sw[i]=o,sw[`${r}${s}`]=o,sw[`${e}${a}`]=o,sw[`${r}${a}`]=o}}function nce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=hK[a]}return n}function aU(t){return t.length>>>1}function sce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=sw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var ice=Math.pow(2,24),oce=Math.pow(2,16),ace=Math.pow(2,8),Sd=(t,e)=>t[e]*ice+t[e+1]*oce+t[e+2]*ace+t[e+3],Dt=(t,e)=>t[e]<<8|t[e+1],Ed=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),Xe=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function yo(t,e,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=e.length||n>=s?0:cce(t,e,r,n,s)}function cce(t,e,r,n,s){s-n>e.length-r&&(s=n+e.length-r);let a=s-n,o=t.length-n;return a>o&&(a=o),(n!==0||s<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}var dce=0,cU=32768,_I=32768,uce=~_I,mK=32768,lce=~mK;function Mr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Fe=Mr({encode(t,e,r){e||(e=new Uint8Array(Fe.encodingLength(t))),r||(r=0);let n=r,s=t.replace(/^\.|\.$/gm,"");if(s.length){let a=s.split(".");for(let o=0;o<a.length;o++){let i=uA(e,a[o],r+1);e[r]=i,r+=i+1}}return e[r++]=0,Fe.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,s=0,a=0,o=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let i=t[e++];if(a+=o?0:1,i===0)break;if(i&192)if((i&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let c=Dt(t,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+i>t.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=i+1,s>254)throw new Error("Cannot decode name (name too long)");r.push($w(t,e,e+i)),e+=i,a+=o?0:i}}return Fe.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Hu(t.replace(/^\.|\.$/gm,""))+2}}),Zn=Mr({encode(t,e,r){e||(e=new Uint8Array(Zn.encodingLength(t))),r||(r=0);let n=uA(e,t,r+1);return e[r]=n,Zn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=$w(t,e+1,e+1+r);return Zn.decode.bytes=r+1,n},encodingLength(t){return Hu(t)+1}}),$h=Mr({bytes:12,encode(t,e,r){e||(e=new Uint8Array($h.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?cU:dce;return Xe(e,t.id||0,r),Xe(e,n|s,r+2),Xe(e,t.questions.length,r+4),Xe(e,t.answers.length,r+6),Xe(e,t.authorities.length,r+8),Xe(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=Dt(t,e+2);return{id:Dt(t,e),type:r&cU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:tce(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:ece(r&15),questions:new Array(Dt(t,e+4)),answers:new Array(Dt(t,e+6)),authorities:new Array(Dt(t,e+8)),additionals:new Array(Dt(t,e+10))}},encodingLength(){return 12}}),k1=Mr({encode(t,e,r){e||(e=new Uint8Array(k1.encodingLength(t))),r||(r=0);let n=t.length;return Xe(e,n,r),yo(t,e,r+2,0,n),k1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=t.slice(e+2,e+2+r);return k1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),_1=Mr({encode(t,e,r){return e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),_1.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=Fe.decode(t,e+2);return _1.decode.bytes=r+2,n},encodingLength(t){return Fe.encodingLength(t)+2}}),T1=Mr({encode(t,e,r){e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mname,e,r),r+=Fe.encode.bytes,Fe.encode(t.rname,e,r),r+=Fe.encode.bytes,Ed(e,t.serial||0,r),r+=4,Ed(e,t.refresh||0,r),r+=4,Ed(e,t.retry||0,r),r+=4,Ed(e,t.expire||0,r),r+=4,Ed(e,t.minimum||0,r),r+=4,Xe(e,r-n-2,n),T1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Fe.decode(t,e),e+=Fe.decode.bytes,n.rname=Fe.decode(t,e),e+=Fe.decode.bytes,n.serial=Sd(t,e),e+=4,n.refresh=Sd(t,e),e+=4,n.retry=Sd(t,e),e+=4,n.expire=Sd(t,e),e+=4,n.minimum=Sd(t,e),e+=4,T1.decode.bytes=e-r,n},encodingLength(t){return 22+Fe.encodingLength(t.mname)+Fe.encodingLength(t.rname)}}),I1=Mr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let s=0;s<t.length;s++)if(typeof t[s]=="string"&&(t[s]=dA(t[s])),!Rf(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,yo(s,e,r,0,s.length),r+=s.length}),Xe(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");s.push(t.slice(e,e+a)),e+=a,n-=a}return I1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Hu(r)+1:e+=r.length+1}),e}}),A1=Mr({encode(t,e,r){e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=dA(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let s=t.length;return yo(t,e,r,0,s),r+=s,Xe(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,A1.decode.bytes=e-r,s},encodingLength(t){return t?(Rf(t)?t.length:Hu(t))+2:2}}),R1=Mr({encode(t,e,r){e||(e=new Uint8Array(R1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Zn.encode(t.cpu,e,r),r+=Zn.encode.bytes,Zn.encode(t.os,e,r),r+=Zn.encode.bytes,Xe(e,r-n-2,n),R1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Zn.decode(t,e),e+=Zn.decode.bytes,n.os=Zn.decode(t,e),e+=Zn.decode.bytes,R1.decode.bytes=e-r,n},encodingLength(t){return Zn.encodingLength(t.cpu)+Zn.encodingLength(t.os)+2}}),Kh=Mr({encode(t,e,r){return e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),Kh.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Fe.decode(t,e+2);return Kh.decode.bytes=Fe.decode.bytes+2,r},encodingLength(t){return Fe.encodingLength(t)+2}}),D1=Mr({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0),Xe(e,t.priority||0,r+2),Xe(e,t.weight||0,r+4),Xe(e,t.port||0,r+6),Fe.encode(t.target,e,r+8);let n=Fe.encode.bytes+6;return Xe(e,n,r),D1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n={};return n.priority=Dt(t,e+2),n.weight=Dt(t,e+4),n.port=Dt(t,e+6),n.target=Fe.decode(t,e+8),D1.decode.bytes=r+2,n},encodingLength(t){return 8+Fe.encodingLength(t.target)}}),qu=Mr({encode(t,e,r){let n=qu.encodingLength(t);return e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=qu.ISSUER_CRITICAL),Xe(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Zn.encode(t.tag,e,r),r+=Zn.encode.bytes,uA(e,t.value,r),r+=Hu(t.value),qu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Dt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Zn.decode(t,e),e+=Zn.decode.bytes,s.value=$w(t,e,n+r),s.issuerCritical=!!(s.flags&qu.ISSUER_CRITICAL),qu.decode.bytes=r+2,s},encodingLength(t){return Zn.encodingLength(t.tag)+Zn.encodingLength(t.value)+2}});qu.ISSUER_CRITICAL=128;var C1=Mr({encode(t,e,r){e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Xe(e,t.preference||0,r),r+=2,Fe.encode(t.exchange,e,r),r+=Fe.encode.bytes,Xe(e,r-n-2,n),C1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Dt(t,e),e+=2,n.exchange=Fe.decode(t,e),e+=Fe.decode.bytes,C1.decode.bytes=e-r,n},encodingLength(t){return 4+Fe.encodingLength(t.exchange)}}),yK=Mr({encode(t,e,r){return e||(e=new Uint8Array(yK.encodingLength(t))),r||(r=0),Xe(e,4,r),r+=2,xc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,xc.decode(t,e)},bytes:6}),j1=Mr({encode(t,e,r){return e||(e=new Uint8Array(j1.encodingLength(t))),r||(r=0),Xe(e,16,r),r+=2,Wu.encode(t,e,r),j1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Wu.decode(t,e);return j1.decode.bytes=18,r},bytes:18}),dU=t=>new Uint8Array(t),Pd=Mr({encode(t,e,r){e||(e=new Uint8Array(Pd.encodingLength(t))),r||(r=0);let n=r,s=oU(t.code);if(Xe(e,s,r),r+=2,t.data)Xe(e,t.data.length,r),r+=2,yo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||Yae(t.ip,dU),i=Qae(t.ip,dU),c=Math.ceil(a/8);Xe(e,c+4,r),r+=2,Xe(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,yo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Xe(e,2,r),r+=2,Xe(e,t.timeout,r),r+=2):(Xe(e,0,r),r+=2);break;case 12:{let a=t.length||0;Xe(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Xe(e,a,r),r+=2;for(let o of t.tags)Xe(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Pd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Dt(t,e),r.type=rce(r.code),e+=2;let n=Dt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Dt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);yo(t,s,0,e,e+n-4),r.ip=Xae(s)}break;case 11:n>0&&(r.timeout=Dt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(Dt(t,e)),e+=2}return Pd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(oU(t.code)){case 8:{let e=t.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),Fu=Mr({encode(t,e,r){e||(e=new Uint8Array(Fu.encodingLength(t))),r||(r=0);let n=r,s=Uh(t,Pd);return Xe(e,s,r),r=uw(t,Pd,e,r+2),Fu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=Dt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=Pd.decode(t,e),e+=Pd.decode.bytes,s-=Pd.decode.bytes;return Fu.decode.bytes=e-r,n},encodingLength(t){return 2+Uh(t||[],Pd)}}),Pc=Mr({encode(t,e,r){e||(e=new Uint8Array(Pc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Rf(s))throw new Error("Key must be a Buffer");return r+=2,Xe(e,t.flags,r),r+=2,e[r]=Pc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,yo(s,e,r,0,s.length),r+=s.length,Pc.encode.bytes=r-n,Xe(e,Pc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);if(e+=2,n.flags=Dt(t,e),e+=2,t[e]!==Pc.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+s+2),e+=n.key.length,Pc.decode.bytes=e-r,n},encodingLength(t){return 6+Hu(t.key)}});Pc.PROTOCOL_DNSSEC=3;Pc.ZONE_KEY=128;Pc.SECURE_ENTRYPOINT=32768;var iw=Mr({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Rf(s))throw new Error("Signature must be a Buffer");return r+=2,Xe(e,Sw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Ed(e,t.originalTTL,r),r+=4,Ed(e,t.expiration,r),r+=4,Ed(e,t.inception,r),r+=4,Xe(e,t.keyTag,r),r+=2,Fe.encode(t.signersName,e,r),r+=Fe.encode.bytes,yo(s,e,r,0,s.length),r+=s.length,iw.encode.bytes=r-n,Xe(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.typeCovered=dP(Dt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=Sd(t,e),e+=4,n.expiration=Sd(t,e),e+=4,n.inception=Sd(t,e),e+=4,n.keyTag=Dt(t,e),e+=2,n.signersName=Fe.decode(t,e),e+=Fe.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,iw.decode.bytes=e-r,n},encodingLength(t){return 20+Fe.encodingLength(t.signersName)+Hu(t.signature)}}),ow=Mr({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mbox||".",e,r),r+=Fe.encode.bytes,Fe.encode(t.txt||".",e,r),r+=Fe.encode.bytes,ow.encode.bytes=r-n,Xe(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Fe.decode(t,e)||".",e+=Fe.decode.bytes,n.txt=Fe.decode(t,e)||".",e+=Fe.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.mbox||".")+Fe.encodingLength(t.txt||".")}}),mo=Mr({encode(t,e,r){e||(e=new Uint8Array(mo.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=Sw(t[a]);s[o>>8]===void 0&&(s[o>>8]=[]),s[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<s.length;a++)if(s[a]!==void 0){let o=dA(s[a]);e[r]=a,r+=1,e[r]=o.length,r+=1,yo(o,e,r,0,o.length),r+=o.length}return mo.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,s=[];for(;e-n<r;){let a=t[e];e+=1;let o=t[e];e+=1;for(let i=0;i<o;i++){let c=t[e+i];for(let u=0;u<8;u++)if(c&1<<7-u){let d=dP(a<<8|i<<3|u);s.push(d)}}e+=o}return mo.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=Sw(t[n]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),aw=Mr({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.nextDomain,e,r),r+=Fe.encode.bytes,mo.encode(t.rrtypes,e,r),r+=mo.encode.bytes,aw.encode.bytes=r-n,Xe(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.nextDomain=Fe.decode(t,e),e+=Fe.decode.bytes,n.rrtypes=mo.decode(t,e,s-(e-r)),e+=mo.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.nextDomain)+mo.encodingLength(t.rrtypes)}}),cw=Mr({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Rf(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Rf(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Xe(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,yo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,yo(a,e,r,0,a.length),r+=a.length,mo.encode(t.rrtypes,e,r),r+=mo.encode.bytes,cw.encode.bytes=r-n,Xe(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Dt(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let o=t[e];return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=mo.decode(t,e,s-(e-r)),e+=mo.decode.bytes,cw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+mo.encodingLength(t.rrtypes)}}),dw=Mr({encode(t,e,r){e||(e=new Uint8Array(dw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Rf(s))throw new Error("Digest must be a Buffer");return r+=2,Xe(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,yo(s,e,r,0,s.length),r+=s.length,dw.encode.bytes=r-n,Xe(e,dw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.keyTag=Dt(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+s+2),e+=n.digest.length,dw.decode.bytes=e-r,n},encodingLength(t){return 6+Hu(t.digest)}}),Nh=Mr({encode(t,e,r){e||(e=new Uint8Array(Nh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=aU(t.fingerprint),a=TI(t.hash);if(s!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${s} != ${a}`);return sce(e,t.fingerprint,r,r+=s),Nh.encode.bytes=r-n,Xe(e,Nh.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let s=TI(n.hash);return n.fingerprint=nce(t,e,e+s),e+=s,Nh.decode.bytes=e-r,n},encodingLength(t){return 4+aU(t.fingerprint)}});function TI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Nh.getFingerprintLengthForHashType=TI;function pI(t){switch(t.toUpperCase()){case"A":return yK;case"PTR":return Kh;case"CNAME":return Kh;case"DNAME":return Kh;case"TXT":return I1;case"NULL":return A1;case"AAAA":return j1;case"SRV":return D1;case"HINFO":return R1;case"CAA":return qu;case"NS":return _1;case"SOA":return T1;case"MX":return C1;case"OPT":return Fu;case"DNSKEY":return Pc;case"RRSIG":return iw;case"RP":return ow;case"NSEC":return aw;case"NSEC3":return cw;case"SSHFP":return Nh;case"DS":return dw}return k1}var qo=Mr({encode(t,e,r){e||(e=new Uint8Array(qo.encodingLength(t))),r||(r=0);let n=r;if(Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,Sw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Xe(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Xe(e,t.flags||0,r+6),r+=8,Fu.encode(t.options||[],e,r),r+=Fu.encode.bytes}else{let s=fK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Xe(e,s,r+2),Ed(e,t.ttl||0,r+4),r+=8;let a=pI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return qo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Fe.decode(t,e),e+=Fe.decode.bytes,r.type=dP(Dt(t,e)),r.type==="OPT")r.udpPayloadSize=Dt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Dt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=Fu.decode(t,e+8),e+=8+Fu.decode.bytes;else{let s=Dt(t,e+2);r.ttl=Sd(t,e+4),r.class=lK(s&uce),r.flush=!!(s&_I);let a=pI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return qo.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Fe.encodingLength(t.name)+8+pI(t.type).encodingLength(e)}}),zh=Mr({encode(t,e,r){e||(e=new Uint8Array(zh.encodingLength(t))),r||(r=0);let n=r;return Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,Sw(t.type),r),r+=2,Xe(e,fK(t.class===void 0?"IN":t.class),r),r+=2,zh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Fe.decode(t,e),e+=Fe.decode.bytes,n.type=dP(Dt(t,e)),e+=2,n.class=lK(Dt(t,e)),e+=2,n.class&mK&&(n.class&=lce),zh.decode.bytes=e-r,n},encodingLength(t){return Fe.encodingLength(t.name)+4}}),fce=1024,Bs={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(pce(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),$h.encode(t,e,r),r+=$h.encode.bytes,r=uw(t.questions,zh,e,r),r=uw(t.answers,qo,e,r),r=uw(t.authorities,qo,e,r),r=uw(t.additionals,qo,e,r),Bs.encode.bytes=r-s,n&&Y1.bytes!==e.length?e.slice(0,Y1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=$h.decode(t,e);return e+=$h.decode.bytes,e=g1(n.questions,zh,t,e),e=g1(n.answers,qo,t,e),e=g1(n.authorities,qo,t,e),e=g1(n.additionals,qo,t,e),Bs.decode.bytes=e-r,n},encodingLength:function(t){return $h.encodingLength(t)+Uh(t.questions||[],zh)+Uh(t.answers||[],qo)+Uh(t.authorities||[],qo)+Uh(t.additionals||[],qo)}};Bs.encode.bytes=0;Bs.decode.bytes=0;function H1(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var J1={encode:function(t,e,r){return e=Bs.encode(H1(t,"query"),e,r),J1.encode.bytes=Bs.encode.bytes,e},decode:function(t,e){let r=Bs.decode(t,e);return J1.decode.bytes=Bs.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Bs.encodingLength(H1(t,"query"))}};J1.encode.bytes=0;J1.decode.bytes=0;var Z1={encode:function(t,e,r){return e=Bs.encode(H1(t,"response"),e,r),Z1.encode.bytes=Bs.encode.bytes,e},decode:function(t,e){let r=Bs.decode(t,e);return Z1.decode.bytes=Bs.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Bs.encodingLength(H1(t,"response"))}};Z1.encode.bytes=0;Z1.decode.bytes=0;var Y1=Bs.encode,II=Bs.decode,pce=Bs.encodingLength;function gK(t){let e=Y1(t),r=new Uint8Array(2+e.byteLength);return Xe(r,e.byteLength),yo(e,r,2,0,e.length),gK.bytes=r.byteLength,r}gK.bytes=0;function wK(t){let e=Dt(t,0);if(t.byteLength<e+2)return null;let r=II(t.slice(2));return wK.bytes=II.bytes,r}wK.bytes=0;function Uh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function uw(t,e,r,n){for(let s=0;s<t.length;s++)e.encode(t[s],r,n),n+=e.encode.bytes;return n}function g1(t,e,r,n){for(let s=0;s<t.length;s++)t[s]=e.decode(r,n),n+=e.decode.bytes;return n}function vK(t,e){let r=Qe.uint8Array(t).toBase32Z();return new URL(r,e).href}async function hce({gatewayUri:t,publicKeyBytes:e}){let r=Qe.uint8Array(e).toBase32Z(),n=vK(e,t),s;try{if(s=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!s.ok)throw new Ze("notFound",`Pkarr record not found for: ${r}`)}catch(o){throw o instanceof Ze?o:new Ze("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await s.arrayBuffer();if(!a)throw new Ze("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new Ze("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new Ze("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function mce({gatewayUri:t,bep44Message:e}){let r=Qe.uint8Array(e.k).toBase32Z(),n=vK(e.k,t),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 a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)})}catch(o){throw new Ze("internalError",`Failed to put Pkarr record for identifier ${r}: ${o.message}`)}return a.ok}async function yce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Y1(t),a=dK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new Ze("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:s}}async function gce({bep44Message:t}){let e=await Ms.bytesToPublicKey({publicKeyBytes:t.k}),r=dK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await Ms.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new Ze("invalidSignature","Invalid signature for DHT BEP44 message");return II(t.v)}var bK="dht";async function PK({didUri:t}){let e=lA({didUri:t});return await Ms.bytesToPublicKey({publicKeyBytes:e})}function lA({didUri:t}){let e=ls.parse(t);if(!e)throw new Ze("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==bK)throw new Ze("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Qe.base32Z(e.id).toUint8Array()}catch{throw new Ze("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new Ze("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function wce({identityKey:t}){let e=await Ms.publicKeyToBytes({publicKey:t}),r=Qe.uint8Array(e).toBase32Z();return`did:${bK}:${r}`}function fA(t){let e={Ed25519:Ms,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await ei.publicKeyToBytes({publicKey:r});return await ei.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ei.bytesToPublicKey,privateKeyToBytes:ei.privateKeyToBytes,bytesToPrivateKey:ei.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await $s.publicKeyToBytes({publicKey:r});return await $s.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:$s.bytesToPublicKey,privateKeyToBytes:$s.privateKeyToBytes,bytesToPrivateKey:$s.bytesToPrivateKey},X25519:jh}[t];if(!e)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function xK({newDid:t,previousDidProof:e}){let r=await PK({didUri:e.previousDid}),n=lA({didUri:t}),s=Qe.base64Url(e.signature).toUint8Array();if(!await Ms.verify({key:r,data:n,signature:s}))throw new Ze("invalidPreviousDidProof","The previous DID proof is invalid.")}var vce=0,Uu=7200,$1=";",Ei=",",SK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},EK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function kw(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Qe.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>kw(e)).join("");throw new Ze("internalError","Pkarr returned DNS TXT record with invalid data type")}function lw(t){return kw(t).split($1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function kK(t){if(t.length<=255)return t;let e=[];for(let r=0;r<t.length;r+=255)e.push(t.slice(r,r+255));return e}async function bce({didUri:t,dnsPacket:e}){let r={id:t},n={published:!0},s=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let i=kw(a.data);r.alsoKnownAs=i.split(Ei);break}case o.startsWith("cnt"):{let i=kw(a.data);r.controller=i.includes(Ei)?i.split(Ei):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=lw(a.data),f=Qe.base64Url(u).toUint8Array(),h=aA[Number(c)],p=await fA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||EK[Number(c)];let m=o==="k0"?"0":i!==void 0?i:await pr({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??t,publicKeyJwk:p}),s.set(o,y);break}case o.startsWith("s"):{let{id:i,t:c,se:u,...d}=lw(a.data),l=u.includes(Ei)?u.split(Ei):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(Ei)?p.split(Ei):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=lw(a.data);n.types=i.split(Ei).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(Ei).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=lw(a.data);c&&(r.authentication=i(c)),u&&(r.assertionMethod=i(u)),d&&(r.capabilityDelegation=i(d)),l&&(r.capabilityInvocation=i(l)),f&&(r.keyAgreement=i(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function Pce({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let s=[],a=[],o=new Map,i=[],c=[];if(n!==void 0){let{signature:d,previousDid:l}=n;await xK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Uu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Uu,data:t.alsoKnownAs.join(Ei)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(Ei):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Uu,data:d})}for(let[d,l]of t.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let h=l.id.split("#").pop();o.set(h,f);let p=l.publicKeyJwk;if(!(p?.crv&&p.crv in SK))throw new Ze("invalidPublicKeyType",`Verification method '${l.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=aA[p.crv],y=await fA(p.crv).publicKeyToBytes({publicKey:p}),S=Qe.uint8Array(y).toBase64Url(),v=[`t=${m}`,`k=${S}`];h!=="0"&&await pr({jwk:p})!==h&&v.unshift(`id=${h}`),p.alg!==EK[m]&&v.push(`a=${p.alg}`),l.controller!==t.id&&v.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Uu,data:v.join($1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=ki(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,_])=>`${E}=${_}`).join($1),v=kK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Uu,data:v})});let u=[`v=${vce}`];if(c.length&&u.push(`vm=${c.join(Ei)}`),Object.keys(tP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=tK[d];u.push(`${f}=${l.join(Ei)}`)}}),i.length&&u.push(`svc=${i.join(Ei)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?eK[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Uu,data:`id=${d.join(Ei)}`})}s.push({type:"TXT",name:"_did."+uU(t.id)+".",ttl:Uu,data:u.join($1)});for(let d of r||[])a.push({type:"NS",name:"_did."+uU(t.id)+".",ttl:Uu,data:d+"."});return{id:0,type:"response",flags:fce,answers:[...s,...a]}}function uU(t){return t.split(":")[2]}var lU=U.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",_K=class AI extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in SK)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let s=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:s}),o=await Lh.identityKeyToIdentifier({identityKey:a}),i={id:o,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},c=[...r.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let l=d.id&&d.id.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await pr({jwk:f});h=`${o}#${ki(h)}`,i.verificationMethod??=[],i.verificationMethod.push({id:h,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let p of d.purposes??[])i[p]??=[],i[p].push(h)}r.services?.forEach(d=>{i.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,i.service.push(d)});let u=new kc({uri:o,document:i,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let d=await AI.publish({did:u,gatewayUri:r.gatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==AI.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new Ze("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>ki(a.id)===(ki(r)??ki(e.assertionMethod?.[0])));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r=lU}){return await fU.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??lU;try{await Lh.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:a}=await fU.get({didUri:e,gatewayUri:n});return{...us,didDocument:s,didDocumentMetadata:a}}catch(s){if(!(s instanceof Ze))throw new Error(s);return{...us,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};_K.methodName="dht";var TK=_K,fU=class fw{static async get({didUri:e,gatewayUri:r}){let n=Lh.identifierToIdentityKeyBytes({didUri:e}),s=await fw.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await Lh.parseBep44GetMessage({bep44Message:s}),o=await fw.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=s.seq.toString(),o}static async put({did:e,gatewayUri:r}){let n=await fw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),s=await Lh.createBep44PutMessage({dnsPacket:n,publicKeyBytes:Lh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await fw.pkarrPut({gatewayUri:r,bep44Message:s});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return hce(e)}static async pkarrPut(e){return mce(e)}static async fromDnsPacket(e){return bce(e)}static async toDnsPacket(e){return Pce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Lh=class{static async createBep44PutMessage(t){return yce(t)}static async identifierToIdentityKey(t){return PK(t)}static identifierToIdentityKeyBytes(t){return lA(t)}static async identityKeyToIdentifier(t){return wce(t)}static keyConverter(t){return fA(t)}static async parseBep44GetMessage(t){return gce(t)}static parseTxtDataToObject(t){return lw(t)}static parseTxtDataToString(t){return kw(t)}static async validatePreviousDidProof(t){return xK(t)}static chunkDataIfNeeded(t){return kK(t)}},Rn={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"},Dn=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},U$e=new Uint8Array(0),xce=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Sce=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ece=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return IK(this,t)}},kce=class{constructor(t){this.decoders=t}or(t){return IK(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},IK=(t,e)=>new kce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),_ce=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Sce(t,e,r),this.decoder=new Ece(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},Tce=({name:t,prefix:e,encode:r,decode:n})=>new _ce(t,e,r,n),Ice=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Ace=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},uP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Tce({prefix:e,name:t,encode(s){return Ace(s,n,r)},decode(s){return Ice(s,n,r,t)}}),L$e=uP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),K$e=uP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pU=uP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),z$e=uP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Wh=class M1{static encode(e){return pU.baseEncode(e)}static decodeAsBytes(e,r){if(!M1.isBase64UrlString(e))throw new Dn(Rn.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return pU.baseDecode(e)}static decodeAsString(e,r){let n=M1.decodeAsBytes(e,r);return M1.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)}},Rce=Df(Tne(),1),RI;(function(t){t.Public="public",t.Private="private"})(RI||(RI={}));var bc=RI,fo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===bc.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new Dn(Rn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new Dn(Rn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new Dn(Rn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===bc.Private&&(t.d===void 0||t.d.length!==43))throw new Dn(Rn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new Dn(Rn.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!Wh.isBase64UrlString(t))throw new Dn(Rn.IdNotUsingBase64UrlCharacterSet,`Key ID '${t}' is not a Base64URL string.`)}static validatePublicKeyPurposes(t){if(t===void 0)return;let e=new Set;for(let r of t){if(e.has(r))throw new Dn(Rn.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},pA=class{};pA.hashAlgorithmInMultihashCode=18;pA.maxCanonicalizedDeltaSizeInBytes=1e3;var Aa=pA,Dce=Df(Ine(),1),_w=class DI{static canonicalizeAsBytes(e){let r=DI.removeAllUndefinedProperties(e),n=Dce.default(r);return Wh.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?DI.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},Cce=AK,hU=128,jce=127,$ce=~jce,Mce=Math.pow(2,31);function AK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Mce;)e[r++]=t&255|hU,t/=128;for(;t&$ce;)e[r++]=t&255|hU,t>>>=7;return e[r]=t|0,AK.bytes=r-n+1,e}var Oce=CI,Bce=128,mU=127;function CI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&mU)<<s:(o&mU)*Math.pow(2,s),s+=7}while(o>=Bce);return CI.bytes=a-n,r}var Nce=Math.pow(2,7),Uce=Math.pow(2,14),Lce=Math.pow(2,21),Kce=Math.pow(2,28),zce=Math.pow(2,35),qce=Math.pow(2,42),Fce=Math.pow(2,49),Gce=Math.pow(2,56),Wce=Math.pow(2,63),Vce=function(t){return t<Nce?1:t<Uce?2:t<Lce?3:t<Kce?4:t<zce?5:t<qce?6:t<Fce?7:t<Gce?8:t<Wce?9:10},Hce={encode:Cce,decode:Oce,encodingLength:Vce},Jce=Hce,Q1=Jce,yU=(t,e=0)=>[Q1.decode(t,e),Q1.decode.bytes],gU=(t,e,r=0)=>(Q1.encode(t,e,r),e),wU=t=>Q1.encodingLength(t),vU=(t,e)=>{let r=e.byteLength,n=wU(t),s=n+wU(r),a=new Uint8Array(s+r);return gU(t,a,0),gU(r,a,n),a.set(e,s),new RK(t,r,e,a)},Zce=t=>{let e=xce(t),[r,n]=yU(e),[s,a]=yU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new RK(r,s,o,e)},RK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},DK=({name:t,code:e,encode:r})=>new Yce(t,e,r),Yce=class{constructor(t,e,r){this.name=t,this.code=e,this.encode=r}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?vU(this.code,e):e.then(r=>vU(this.code,r))}else throw Error("Unknown type, must be binary type")}},CK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),bU=DK({name:"sha2-256",code:18,encode:CK("SHA-256")}),q$e=DK({name:"sha2-512",code:19,encode:CK("SHA-512")}),Xg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},ho=class pw{static hash(e,r){return Xg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield bU.digest(e)).bytes;break;default:throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Xg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield bU.encode(e);break;default:throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e);return yield pw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e),s=yield pw.hashAsNonMultihashBytes(n,r);return yield pw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Xg(this,void 0,void 0,function*(){let n=yield pw.hash(e,r);return Wh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Wh.decodeAsBytes(e,r);try{n=Zce(s)}catch{throw new Dn(Rn.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Aa.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Dn(Rn.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}},jI;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(jI||(jI={}));var w1=jI,$I;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})($I||($I={}));var Ch=$I,v1=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},jK=class Ko{static createCreateRequest(e){return v1(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,s=e.document.publicKeys,a=e.document.services;fo.validateEs256kOperationKey(r,bc.Public),fo.validateEs256kOperationKey(n,bc.Public),Ko.validateDidDocumentKeys(s),Ko.validateServices(a);let o=Aa.hashAlgorithmInMultihashCode,i=[{action:Ch.Replace,document:e.document}],c={updateCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Ko.validateDeltaSize(c);let u={deltaHash:yield ho.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:w1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return v1(this,void 0,void 0,function*(){Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.recoveryPublicKey,bc.Public);let r=Aa.hashAlgorithmInMultihashCode,n=yield ho.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},s);return{type:w1.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return v1(this,void 0,void 0,function*(){Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.recoveryPublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextRecoveryPublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextUpdatePublicKey,bc.Public),Ko.validateDidDocumentKeys(e.document.publicKeys),Ko.validateServices(e.document.services);let r=Aa.hashAlgorithmInMultihashCode,n=yield ho.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Ch.Replace,document:e.document}],a=yield ho.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield ho.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield ho.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:i},u=yield e.signer.sign({alg:"ES256K"},c);return{type:w1.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:u}})}static createUpdateRequest(e){return v1(this,void 0,void 0,function*(){if(Ko.validateDidSuffix(e.didSuffix),fo.validateEs256kOperationKey(e.updatePublicKey,bc.Public),fo.validateEs256kOperationKey(e.nextUpdatePublicKey,bc.Public),Ko.validateServices(e.servicesToAdd),Ko.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)fo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)fo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Ch.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Ch.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Ch.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Ch.RemovePublicKeys,ids:o};r.push(p)}let i=Aa.hashAlgorithmInMultihashCode,c=yield ho.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield ho.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield ho.canonicalizeThenHashThenEncode(d,i),f={updateKey:e.updatePublicKey,deltaHash:l},h=yield e.signer.sign({alg:"ES256K"},f);return{type:w1.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:h}})}static validateDidSuffix(e){ho.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Dn(Rn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(fo.validateId(n.id),r.has(n.id))throw new Dn(Rn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),fo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Ko.validateService(n),r.has(n.id))throw new Dn(Rn.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){fo.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Dn(Rn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Dn(Rn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Rce.parse(e.serviceEndpoint).error!==void 0)throw new Dn(Rn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=_w.canonicalizeAsBytes(e);if(r.length>Aa.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Aa.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Dn(Rn.DeltaExceedsMaximumSize,n)}}},PU=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Qce=class $K{static createLongFormDid(e){return PU(this,void 0,void 0,function*(){let r=yield jK.createCreateRequest(e),n=yield $K.computeDidUniqueSuffix(r.suffixData),s;Aa.network===void 0||Aa.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Aa.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=_w.canonicalizeAsBytes(a),i=Wh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return PU(this,void 0,void 0,function*(){let r=_w.canonicalizeAsBytes(e),n=yield ho.hash(r,Aa.hashAlgorithmInMultihashCode);return Wh.encode(n)})}},js=2n**255n-19n,O1=2n**252n+27742317777372353535851937790883648493n,MI=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,OI=0x6666666666666666666666666666666666666666666666666666666666666658n,b1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:js,n:O1,h:8,Gx:MI,Gy:OI},Li=(t="")=>{throw new Error(t)},MK=t=>typeof t=="string",hA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Li("Uint8Array expected"):t,Vh=t=>new Uint8Array(t),Xce=(t,e)=>hA(MK(t)?yA(t):Vh(t),e),nt=(t,e=js)=>{let r=t%e;return r>=0n?r:e+r},xU=t=>t instanceof Hh?t:Li("Point expected"),SU,Hh=class Mh{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new Mh(e.x,e.y,1n,nt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=b1;e=Xce(e,32);let s=e.slice();s[31]=e[31]&-129;let a=tde(s);a===0n||(r&&!(0n<a&&a<js)&&Li("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Li("bad y coord 2"));let o=nt(a*a),i=nt(o-1n),c=nt(n*o+1n),{isValid:u,value:d}=nde(i,c);u||Li("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=nt(-d)),new Mh(d,a,1n,nt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:s}=this,{ex:a,ey:o,ez:i}=xU(e),c=nt(r*i),u=nt(a*s),d=nt(n*i),l=nt(o*s);return c===u&&d===l}is0(){return this.equals(B1)}negate(){return new Mh(nt(-this.ex),this.ey,this.ez,nt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=b1,a=nt(e*e),o=nt(r*r),i=nt(2n*nt(n*n)),c=nt(s*a),u=e+r,d=nt(nt(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=nt(d*f),m=nt(l*h),y=nt(d*h),S=nt(f*l);return new Mh(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=xU(e),{a:d,d:l}=b1,f=nt(r*o),h=nt(n*i),p=nt(a*l*u),m=nt(s*c),y=nt((r+n)*(o+i)-f-h),S=nt(m-p),v=nt(m+p),E=nt(h-d*f),_=nt(y*S),I=nt(v*E),R=nt(y*E),N=nt(S*v);return new Mh(_,I,N,R)}mul(e,r=!0){if(e===0n)return r===!0?Li("cannot multiply by 0"):B1;if(typeof e=="bigint"&&0n<e&&e<O1||Li("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(X1))return ode(e).p;let n=B1,s=X1;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(b1.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(O1/2n,!1).double();return O1%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:r,ez:n}=this;if(this.is0())return{x:0n,y:0n};let s=BK(n);return nt(n*s)!==1n&&Li("invalid inverse"),{x:nt(e*s),y:nt(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=ede(r);return n[31]|=e&1n?128:0,n}toHex(){return mA(this.toRawBytes())}};Hh.BASE=new Hh(MI,OI,1n,nt(MI*OI));Hh.ZERO=new Hh(0n,1n,1n,0n);var{BASE:X1,ZERO:B1}=Hh,OK=(t,e)=>t.toString(16).padStart(e,"0"),mA=t=>Array.from(t).map(e=>OK(e,2)).join(""),yA=t=>{let e=t.length;(!MK(t)||e%2)&&Li("hex invalid 1");let r=Vh(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Li("hex invalid 2"),r[n]=o}return r},ede=t=>yA(OK(t,32*2)).reverse(),tde=t=>BigInt("0x"+mA(Vh(hA(t)).reverse())),EU=(...t)=>{let e=Vh(t.reduce((n,s)=>n+hA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},BK=(t,e=js)=>{(t===0n||e<=0n)&&Li("no inverse n="+t+" mod="+e);let r=nt(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?nt(s,e):Li("no inverse")},gc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=js;return r},rde=t=>{let e=t*t%js*t%js,r=gc(e,2n)*e%js,n=gc(r,1n)*t%js,s=gc(n,5n)*n%js,a=gc(s,10n)*s%js,o=gc(a,20n)*a%js,i=gc(o,40n)*o%js,c=gc(i,80n)*i%js,u=gc(c,80n)*i%js,d=gc(u,10n)*s%js;return{pow_p_5_8:gc(d,2n)*t%js,b2:e}},kU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,nde=(t,e)=>{let r=nt(e*e*e),n=nt(r*r*e),s=rde(t*n).pow_p_5_8,a=nt(t*r*s),o=nt(e*a*a),i=a,c=nt(a*kU),u=o===t,d=o===nt(-t),l=o===nt(-t*kU);return u&&(a=i),(d||l)&&(a=c),(nt(a)&1n)===1n&&(a=nt(-a)),{isValid:u||d,value:a}},hI,_U=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,sde={bytesToHex:mA,hexToBytes:yA,concatBytes:EU,mod:nt,invert:BK,randomBytes:t=>{let e=_U();return e||Li("crypto.getRandomValues must be defined"),e.getRandomValues(Vh(t))},sha512Async:async(...t)=>{let e=_U();e||Li("crypto.subtle or etc.sha512Async must be defined");let r=EU(...t);return Vh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(sde,{sha512Sync:{configurable:!1,get(){return hI},set(t){hI||(hI=t)}}});var Pf=8,ide=()=>{let t=[],e=256/Pf+1,r=X1,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(Pf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},ode=t=>{let e=SU||(SU=ide()),r=(d,l)=>{let f=l.negate();return d?f:l},n=B1,s=X1,a=1+256/Pf,o=2**(Pf-1),i=BigInt(2**Pf-1),c=2**Pf,u=BigInt(Pf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},gA=2n**256n,Tf=gA-0x1000003d1n,wA=gA-0x14551231950b75fc4402da1732fc9bebfn,NK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,UK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,LK={p:Tf,n:wA,a:0n,b:7n,Gx:NK,Gy:UK},qh=32,TU=t=>He(He(t*t)*t+LK.b),ds=(t="")=>{throw new Error(t)},lP=t=>typeof t=="bigint",KK=t=>typeof t=="string",mI=t=>lP(t)&&0n<t&&t<Tf,zK=t=>lP(t)&&0n<t&&t<wA,qK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?ds("Uint8Array expected"):t,Tw=t=>new Uint8Array(t),vA=(t,e)=>qK(KK(t)?fP(t):Tw(t),e),He=(t,e=Tf)=>{let r=t%e;return r>=0n?r:e+r},IU=t=>t instanceof Jh?t:ds("Point expected"),AU,Jh=class Oh{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new Oh(e.x,e.y,1n)}static fromHex(e){e=vA(e);let r,n=e[0],s=e.subarray(1),a=RU(s,0,qh),o=e.length;if(o===33&&[2,3].includes(n)){mI(a)||ds("Point hex invalid: x not FE");let i=ade(TU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=He(-i)),r=new Oh(a,i,1n)}return o===65&&n===4&&(r=new Oh(a,RU(s,qh,2*qh),1n)),r?r.ok():ds("Point is not on curve")}static fromPrivateKey(e){return gw.mul(cde(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=IU(e),c=He(r*i),u=He(a*s),d=He(n*i),l=He(o*s);return c===u&&d===l}negate(){return new Oh(this.px,He(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=IU(e),{a:c,b:u}=LK,d=0n,l=0n,f=0n,h=He(u*3n),p=He(r*a),m=He(n*o),y=He(s*i),S=He(r+n),v=He(a+o);S=He(S*v),v=He(p+m),S=He(S-v),v=He(r+s);let E=He(a+i);return v=He(v*E),E=He(p+y),v=He(v-E),E=He(n+s),d=He(o+i),E=He(E*d),d=He(m+y),E=He(E-d),f=He(c*v),d=He(h*y),f=He(d+f),d=He(m-f),f=He(m+f),l=He(d*f),m=He(p+p),m=He(m+p),y=He(c*y),v=He(h*v),m=He(m+y),y=He(p-y),y=He(c*y),v=He(v+y),p=He(m*v),l=He(l+p),p=He(E*v),d=He(S*d),d=He(d-p),p=He(S*m),f=He(E*f),f=He(f+p),new Oh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return N1;if(zK(e)||ds("invalid scalar"),this.equals(gw))return fde(e).p;let n=N1,s=gw;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}mulAddQUns(e,r,n){return this.mul(r,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:r,pz:n}=this;if(this.equals(N1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=GK(n);return He(n*s)!==1n&&ds("invalid inverse"),{x:He(e*s),y:He(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!mI(e)||!mI(r))&&ds("Point invalid: x or y"),He(r*r)===TU(e)?this:ds("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:r,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+DU(r)+(e?"":DU(n))}toRawBytes(e=!0){return fP(this.toHex(e))}};Jh.BASE=new Jh(NK,UK,1n);Jh.ZERO=new Jh(0n,1n,0n);var{BASE:gw,ZERO:N1}=Jh,FK=(t,e)=>t.toString(16).padStart(e,"0"),bA=t=>Array.from(t).map(e=>FK(e,2)).join(""),fP=t=>{let e=t.length;(!KK(t)||e%2)&&ds("hex invalid 1");let r=Tw(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&ds("hex invalid 2"),r[n]=o}return r},pP=t=>BigInt("0x"+(bA(t)||"0")),RU=(t,e,r)=>pP(t.slice(e,r)),PA=t=>lP(t)&&t>=0n&&t<gA?fP(FK(t,2*qh)):ds("bigint expected"),DU=t=>bA(PA(t)),CU=(...t)=>{let e=Tw(t.reduce((n,s)=>n+qK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},GK=(t,e=Tf)=>{(t===0n||e<=0n)&&ds("no inverse n="+t+" mod="+e);let r=He(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?He(s,e):ds("no inverse")},ade=t=>{let e=1n;for(let r=t,n=(Tf+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%Tf),r=r*r%Tf;return He(e*e)===t?e:ds("sqrt invalid")},cde=t=>(lP(t)||(t=pP(vA(t,qh))),zK(t)?t:ds("private key out of range")),jU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,U1;function dde(t){t=vA(t);let e=qh+8;(t.length<e||t.length>1024)&&ds("expected proper params");let r=He(pP(t),wA-1n)+1n;return PA(r)}var ude={hexToBytes:fP,bytesToHex:bA,concatBytes:CU,bytesToNumberBE:pP,numberToBytesBE:PA,mod:He,invert:GK,hmacSha256Async:async(t,...e)=>{let r=jU();if(!r)return ds("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Tw(await n.sign("HMAC",s,CU(...e)))},hmacSha256Sync:U1,hashToPrivateKey:dde,randomBytes:t=>{let e=jU();return e||ds("crypto.getRandomValues must be defined"),e.getRandomValues(Tw(t))}};Object.defineProperties(ude,{hmacSha256Sync:{configurable:!1,get(){return U1},set(t){U1||(U1=t)}}});var xf=8,lde=()=>{let t=[],e=256/xf+1,r=gw,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(xf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},fde=t=>{let e=AU||(AU=lde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=N1,s=gw,a=1+256/xf,o=2**(xf-1),i=BigInt(2**xf-1),c=2**xf,u=BigInt(xf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},$U;(function(t){t.Mainnet="mainnet",t.Testnet="test"})($U||($U={}));var MU;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(MU||(MU={}));var ew=class vf{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:r,services:n,verificationMethods:s}){let a=await vf.createIonDocument({services:n,verificationMethods:s}),o=vf.normalizeJwk(e),i=vf.normalizeJwk(r);return await Qce.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await jK.createCreateRequest({document:e,recoveryKey:vf.normalizeJwk(r),updateKey:vf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await pr({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:vf.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(i)}let s=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:s}}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}},pde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(pde||{}),hde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},OU="https://ion.tbd.engineering",mde=class hw extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in hde)))throw new Error("One or more verification method algorithms are not supported");let n=r.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(r.services?.some(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let s={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[s]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let o=await e.generateKey({algorithm:"secp256k1"}),i=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),u=await e.getPublicKey({keyUri:c}),d=await ew.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await hw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new kc({uri:d,document:l,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:i,updateKey:u},keyManager:e});if(r.publish??!0){let p=await hw.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==hw.methodName)throw new Ze("methodNotSupported","Method not supported");return await kc.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=OU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:JL({didDocument:e.document,methodId:o.id})}))??[],s=await ew.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await ew.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=ew.appendPathToUrl({baseUrl:r,path:"/operations"}),i=await fetch(o,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:i.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,r={}){let n=ls.parse(e);if(!n)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??OU;try{let a=ew.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new Ze("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...us,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Ze))throw new Error(a);return{...us,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};mde.methodName="ion";var WK=class mw extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=Qe.object(a).toBase64Url(),i=`did:${mw.methodName}:${o}`,c=(await mw.resolve(i)).didDocument;return new kc({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=ls.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==mw.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=ls.parse(e),s;try{s=n?Qe.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==mw.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:s}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],s.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...us,didDocument:a}}};WK.methodName="jwk";var VK=WK,yde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},L1=class Bh{static async jwkToMulticodec({jwk:e}){let r=[];e.crv&&(r.push(e.crv),e.d?r.push("private"):r.push("public"));let n=r.join(":"),s=Bh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Jo.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":ei.compressPublicKey,secp256k1:$s.compressPublicKey}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:Ms,"P-256":ei,secp256k1:$s}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static async multicodecToJwk({code:e,name:r}){if(!(r?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");r=r===void 0?Jo.getNameFromCode({code:e}):r;let n=r,s=Bh.MULTICODEC_TO_JWK[n];if(s===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...s}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in yde))throw new Ze("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Bh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Bh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Bh.jwkToMulticodec({jwk:e});return YL({keyBytes:r,multicodecName:n})}};L1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},L1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},L1.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:""}};var P1=L1,gde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(gde||{}),BU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},HK=class zu extends Cw{static async create({keyManager:e=new Ra,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=await P1.publicKeyToMultibaseId({publicKey:a}),i=`did:${zu.methodName}:${o}`,c=(await zu.resolve(i,r)).didDocument;return new kc({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=ls.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==zu.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await kc.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await zu.createDocument({didUri:e,options:r});return{...us,didDocument:n}}catch(n){if(!(n instanceof Ze))throw new Error(n);return{...us,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:r={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:a="JsonWebKey2020"}=r,o={id:""},i=ls.parse(e);if(!i)throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==zu.methodName)throw new Ze("methodNotSupported",`Method not supported: ${i.method}`);if(!zu.validateIdentifier(i))throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let u=await zu.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}});o.id=i.uri,o.verificationMethod=[u],o.authentication=[u.id],o.assertionMethod=[u.id],o.capabilityInvocation=[u.id],o.capabilityDelegation=[u.id];let d=[n];return HL({didDocument:o}).forEach(l=>{let f=BU[l];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:i,multicodecCode:c,multicodecName:u}=QL({multibaseKeyId:r}),d=i.byteLength,l=P1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new Ze("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await Ms.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new Ze("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new Ze("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in BU))throw new Ze("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Ze("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await P1.multicodecToJwk({code:c});o.publicKeyJwk=await P1.keyConverter(h).bytesToPublicKey({publicKeyBytes:i})}return o}static validateIdentifier(e){let{method:r,id:n}=e,[s]=e.uri.split(":",1);return s==="did"&&r==="key"&&!0&&yI(n)==="String"&&n.startsWith("z")}};HK.methodName="key";var Mw=HK,wde=3e4;function vde(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let s=r.map(Number);if(s.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=s;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var JK=class K1 extends Cw{static async create({keyManager:e=new Ra,options:r}){if(!r.domain)throw new Ze("invalidDid","The 'domain' option is required for did:web creation");if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=r.path?`${r.domain}:${r.path}`:r.domain,s=`did:${K1.methodName}:${n}`;if(!ls.parse(s))throw new Ze("invalidDid",`The constructed DID URI is invalid: ${s}`);let a=r.verificationMethods??[{algorithm:r.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:s};for(let i=0;i<a.length;i++){let c=a[i],u=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:u}),l=c.id?.split("#").pop()??`key-${i}`,f=`${s}#${l}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:d});for(let h of c.purposes??[])o[h]??=[],o[h].push(f)}return r.services&&(o.service=r.services.map(i=>({...i,id:`${s}#${i.id.split("#").pop()}`}))),new kc({uri:s,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=ls.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=ki(r)??ki(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>ki(o.id)===s):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:r=new Ra}){if(ls.parse(e.uri)?.method!==K1.methodName)throw new Ze("methodNotSupported","Method not supported");return await kc.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=ls.parse(e);if(!n)return{...us,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==K1.methodName)return{...us,didResolutionMetadata:{error:"methodNotSupported"}};let s=`https://${n.id.replace(/:/g,"/")}`;s=decodeURIComponent(s);let a=n.id.includes(":")?`${s}/did.json`:`${s}/.well-known/did.json`;try{let o=new URL(a);if(vde(o.hostname))return{...us,didResolutionMetadata:{error:"notFound"}};let i=await fetch(a,{signal:AbortSignal.timeout(wde)});if(!i.ok)throw new Error("HTTP error status code returned");let c=await i.json();return{...us,didDocument:c}}catch{return{...us,didResolutionMetadata:{error:"notFound"}}}}};JK.methodName="web";var ZK=JK,F$e=Df(VU(),1),G$e=Df(HU(),1);var bde=Df(HU(),1),YK=class{constructor({ttl:t="15m"}={}){this.cache=new Rne.default({ttl:(0,bde.default)(t)})}async open(){}async get(t){if(!t)throw new Error("Key cannot be null or undefined");return this.cache.get(t)}async set(t,e){this.cache.set(t,e)}async delete(t){this.cache.delete(t)}async clear(){this.cache.clear()}async close(){}},Pde={open(){return Promise.resolve()},get(t){return Promise.resolve(void 0)},set(t,e){return Promise.resolve()},delete(t){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},QK=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||Pde;for(let r of e)this.didResolvers.set(r.methodName,r)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(t,e){let r=ls.parse(t);if(!r)return{...us,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...us,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let s=await this.cache.get(r.uri);if(s)return s;{let a=await n.resolve(r.uri,e);return a.didResolutionMetadata.error||await this.cache.set(r.uri,a),a}}async dereference(t,e){let r=ls.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:s,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:s.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:i=[]}=n,c=new Set([t,r.fragment,`#${r.fragment}`]),u;for(let d of i)if(c.has(d.id)){u=d;break}for(let d of o)if(c.has(d.id)){u=d;break}return u?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:u,contentMetadata:s}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};Xt();var xA=class t{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 Dh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new c1(e.resumableTaskStore,this.storageController),this._coreProtocols=new cg,this._coreProtocols.register(new Ir);let r={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={["MessagesRead"]:new bb(r),["MessagesSubscribe"]:new xb(r),["MessagesSync"]:new Sb(r),["ProtocolsConfigure"]:new i1(r),["ProtocolsQuery"]:new o1(r),["RecordsCount"]:new a1(r),["RecordsDelete"]:new d1(r),["RecordsQuery"]:new u1(r),["RecordsRead"]:new l1(r),["RecordsSubscribe"]:new f1(r),["RecordsWrite"]:new p1(r)}}static async create(e){e.didResolver||(e.didResolver=new QK({didResolvers:[TK,VK,Mw,ZK],cache:new YK}),e.ownsResolver=!0),e.tenantGate??=new dg;let r=new t(e);return await r.open(),r}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,r,n={}){let s=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(s!==void 0)return s;let{dataStream:a,subscriptionHandler:o}=n,i=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[i].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:o})}async validateTenant(e){let r=await this.tenantGate.isActiveTenant(e);if(!r.isActiveTenant)return{status:{code:401,detail:r.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let r=e?.descriptor?.interface,n=e?.descriptor?.method;if(r===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${r}, method: ${n}`}};try{we.validateJsonSchema(e)}catch(s){return ut(s,400)}}};ht();Xt();hn();Cy();bi();w();function xde(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function Nn(t,e){return e?Promise.race([t,xde(e)]):t}Na();or();pa();T0();On();d0();t2();Ya();Hs();qE();Al();w();ey();w();import{Level as Sde}from"level";async function zi(t,e){return new Sde(t,{...e,keyEncoding:"utf8"})}var Da=class t{config;db;constructor(e,r){this.config={createLevelDatabase:zi,...e},this.db=r}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,r)=>{let n=()=>{this.db.open().then(e).catch(r)};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,r)=>{let n=()=>{this.db.close().then(e).catch(r)};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 t(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,r){r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal);try{return await Nn(this.db.get(String(e)),r?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,r){return!!await this.get(e,r)}async*keys(e){e?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),e?.signal);for await(let r of this.db.keys())e?.signal?.throwIfAborted(),yield r}async*iterator(e,r){r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal);for await(let n of this.db.iterator(e))r?.signal?.throwIfAborted(),yield n}async put(e,r,n){return n?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),n?.signal),Nn(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal),Nn(this.db.del(String(e)),r?.signal)}async isEmpty(e){for await(let r of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,r){return r?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),r?.signal),Nn(this.db.batch(e),r?.signal)}createPartitionOperation(e,r){return{...r,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Nn(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Nn(n.db.compactRange?.(...r),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let r=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,r]}get root(){let e=this.db;for(let r=e.db;r&&r!==e;)e=r;return new t(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}};var Nf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:zi,...e},this.db=r??new Da({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let r=await this.db.partition(e);return new t({...this.config,location:""},r)}async put(e,r,n){return await this.db.put(String(e),r,n),qt.parse(e.toString())}async get(e,r){return await this.db.get(String(e),r)}async has(e,r){return this.db.has(String(e),r)}async delete(e,r){return this.db.delete(String(e),r)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,r){for await(let n of e)await this.put(n.cid,n.block,r),yield n.cid}async*getMany(e,r){for await(let n of e)yield{cid:n,block:await this.get(n,r)}}async*getAll(e){let r=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,s]of r)yield{cid:qt.decode(n),block:s}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}};w();Hd();w();var TP=Ln(To(),1);w();function Ede(t){return t[Symbol.asyncIterator]!=null}function kde(t){if(Ede(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var XK=kde;Gc();w();Ip();Io();var M9=Ln(To(),1);py();w();Xu();np();var e9=0,_de="identity",t9=Qo,Tde=t=>il(e9,t9(t)),r9={code:e9,name:_de,encode:t9,digest:Tde};w();Ip();var n9=Ln(To(),1);Gc();var Ide=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=F2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=qt.asCID(d[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}},next:{cid:h,name:f,path:l,toResolve:n}};d=d[f]}else throw(0,n9.default)(new Error(`No property named ${f} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}}}},s9=Ide;w();var i9=Ln(To(),1);np();Vc();w();function Ade(t,e,r,n){let s=BigInt(t.length),a=BigInt(e+s);return r>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(t=t.subarray(0,Number(n-e))),r>=e&&r<a&&(t=t.subarray(Number(r-e))),t)}var Uf=Ade;w();var Ow=Ln(To(),1),Rde=(t,e=0,r=t)=>{let n=BigInt(t),s=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=s+a),a>n&&(a=n),s<0n)throw(0,Ow.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,Ow.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,Ow.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,Ow.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:s,end:a}},Xh=Rde;var Dde=t=>{async function*e(r={}){let{start:n,end:s}=Xh(t.length,r.offset,r.length),a=Uf(t,0n,n,s);r.onProgress?.(new gn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Cde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,i9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=c0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Dde(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},o9=Cde;w();var a9=Ln(To(),1);Vc();var jde=t=>{async function*e(r={}){let{start:n,end:s}=Xh(t.length,r.offset,r.length),a=Uf(t,0n,n,s);r.onProgress?.(new gn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},$de=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,a9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=await o.get(t,i);return{entry:{type:"raw",name:e,path:r,cid:t,content:jde(c),depth:a,size:BigInt(c.length),node:c}}},c9=$de;w();Io();var Fw=Ln(To(),1);Yd();w();Io();FS();GS();var Mde=async function(t){return(await uv.encode(t)).slice(0,8).reverse()},Ode=async(t,e,r)=>{await Promise.all(t.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let s=parseInt(n.Name,16);e._putObjectAt(s,new Wa({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},d9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Bde=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},u9=async(t,e,r,n,s)=>{if(n==null){let d=pv({hashFn:Mde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await Ode(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=d9(a.pos),i=Bde(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=d9(n.lastBucket._posAtParent));let c=t.Links.find(d=>{if(d.Name==null)return!1;let l=d.Name.substring(0,2),f=d.Name.substring(2);return!(l!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await r.get(c.Hash,s);return t=Wc(u),u9(t,e,r,n,s)},l9=u9;w();w();w();function Nde(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var hP=Nde;function Ude(t){return t[Symbol.asyncIterator]!=null}function Lde(t,e){let r=0;if(Ude(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=hP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){await o&&(yield s);for(let c of n)await e(c,r++)&&(yield c)}();let i=e;return function*(){o===!0&&(yield s);for(let c of n)i(c,r++)&&(yield c)}()}var f9=Lde;w();function Kde(t){return t[Symbol.asyncIterator]!=null}function zde(t,e){let r=0;if(Kde(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=hP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,r++)}();let i=e;return function*(){yield o;for(let c of n)yield i(c,r++)}()}var em=zde;w();w();function qi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var mP=globalThis.CustomEvent??Event;async function*Lf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=qi(),i=qi(),c=!1,u,d=!1;s.addEventListener("task-complete",()=>{i.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(o=qi(),await o.promise),d)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,s.dispatchEvent(new mP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new mP("task-complete"))})}c=!0,s.dispatchEvent(new mP("task-complete"))}catch(p){u=p,s.dispatchEvent(new mP("task-complete"))}});function l(){return n?a[0]?.done:!!a.find(p=>p.done)}function*f(){for(;a.length>0&&a[0].done;){let p=a[0];if(a.shift(),p.ok)yield p.value;else throw d=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;l();)for(let p=0;p<a.length;p++)if(a[p].done){let m=a[p];if(a.splice(p,1),p--,m.ok)yield m.value;else throw d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(l()||(i=qi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}w();w();w();var yP=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}},tm=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yP(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 r=this.head;this.head=r.next=new yP(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var SA=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function gP(t={}){return qde(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function qde(t,e){e=e??{};let r=e.onEnd,n=new tm,s,a,o,i=qi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=v=>{a=null,n.push(v);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=qi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new tm,a!=null?a({error:y}):(n.push({error:y}),s)),l=y=>{if(o)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},f=y=>o?s:(o=!0,y!=null?d(y):u({done:!0})),h=()=>(n=new tm,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async y=>{let S=y?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let v,E;S!=null&&(v=new Promise((_,I)=>{E=()=>{I(new SA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,v])}finally{E!=null&&S!=null&&S?.removeEventListener("abort",E)}}},r==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(y){return m.end(y),r!=null&&(r(y),r=void 0),s},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},s}w();w();w();function Fde(t){return t.reason}async function p9(t,e,r){if(e==null)return t;let n=r?.translateError??Fde;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([t,new Promise((a,o)=>{s=()=>{o(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var EA=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=qi(),this.haveNext=qi()}[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=qi(),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,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){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=qi(),await p9(this.readNext.promise,r?.signal,r)}};function h9(){return new EA}function Gde(t){return t[Symbol.asyncIterator]!=null}async function Wde(t,e,r){try{await Promise.all(t.map(async n=>{for await(let s of n)await e.push(s,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Vde(t){let e=new AbortController,r=h9();Wde(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Hde(t){for(let e of t)yield*e}function Jde(...t){let e=[];for(let r of t)Gde(r)||e.push(r);return e.length===t.length?Hde(e):Vde(t)}var m9=Jde;function rm(t,...e){if(t==null)throw new Error("Empty pipeline");if(kA(t)){let n=t;t=()=>n.source}else if(g9(t)||y9(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&kA(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)kA(r[n])&&(r[n]=Yde(r[n]));return Zde(...r)}var Zde=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},y9=t=>t?.[Symbol.asyncIterator]!=null,g9=t=>t?.[Symbol.iterator]!=null,kA=t=>t==null?!1:t.sink!=null&&t.source!=null,Yde=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=gP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(y9(a))s=async function*(){yield*a,n.end()};else if(g9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return m9(n,s())}return t.source};Vc();var Qde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=c.offset??0,d=c.length??e.Links.length,l=e.Links.slice(u,d);c.onProgress?.(new gn("unixfs:exporter:walk:directory",{cid:t})),yield*rm(l,f=>em(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Lf(f,{ordered:!0}),f=>f9(f,h=>h!=null))}return i},w9=Qde;w();Io();var zf=Ln(To(),1);Yd();py();w();w();var TA=Ln(b9(),1);w();var Nw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},IA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},P9=t=>globalThis.DOMException===void 0?new IA(t):new DOMException(t),x9=t=>{let e=t.reason===void 0?P9("This operation was aborted."):t.reason;return e instanceof Error?e:P9(e)};function AA(t,e,r,n){let s,a=new Promise((o,i)=>{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(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&i(x9(c)),c.addEventListener("abort",()=>{i(x9(c))})}s=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(d){i(d)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new Nw(c);typeof t.cancel=="function"&&t.cancel(),i(u)},e),(async()=>{try{o(await t)}catch(c){i(c)}finally{n.customTimers.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{clearTimeout(s),s=void 0},a}w();w();function RA(t,e,r){let n=0,s=t.length;for(;s>0;){let a=Math.trunc(s/2),o=n+a;r(t[o],e)<=0?(n=++o,s-=a+1):s=a}return n}var Kf=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Id,DA=class{constructor(){Id.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Kf(this,Id,"f")[this.size-1].priority>=r.priority){Kf(this,Id,"f").push(n);return}let s=RA(Kf(this,Id,"f"),n,(a,o)=>o.priority-a.priority);Kf(this,Id,"f").splice(s,0,n)}dequeue(){let e=Kf(this,Id,"f").shift();return e?.run}filter(e){return Kf(this,Id,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Kf(this,Id,"f").length}};Id=new WeakMap;var S9=DA;var fn=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Ge=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},jn,Lw,Kw,Zu,EP,zw,vP,Ca,Uw,wo,bP,vo,qw,Ju,PP,E9,k9,I9,_9,T9,xP,CA,jA,kP,A9,SP,_P=class extends Error{},$A=class extends TA.default{constructor(e){var r,n,s,a;if(super(),jn.add(this),Lw.set(this,void 0),Kw.set(this,void 0),Zu.set(this,0),EP.set(this,void 0),zw.set(this,void 0),vP.set(this,0),Ca.set(this,void 0),Uw.set(this,void 0),wo.set(this,void 0),bP.set(this,void 0),vo.set(this,0),qw.set(this,void 0),Ju.set(this,void 0),PP.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:S9,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);fn(this,Lw,e.carryoverConcurrencyCount,"f"),fn(this,Kw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),fn(this,EP,e.intervalCap,"f"),fn(this,zw,e.interval,"f"),fn(this,wo,new e.queueClass,"f"),fn(this,bP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,fn(this,PP,e.throwOnTimeout===!0,"f"),fn(this,Ju,e.autoStart===!1,"f")}get concurrency(){return Ge(this,qw,"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})`);fn(this,qw,e,"f"),Ge(this,jn,"m",kP).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ge(this,PP,"f"),...r},new Promise((n,s)=>{Ge(this,wo,"f").enqueue(async()=>{var a,o,i;fn(this,vo,(o=Ge(this,vo,"f"),o++,o),"f"),fn(this,Zu,(i=Ge(this,Zu,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new _P("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=AA(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,Ge(this,jn,"m",A9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ge(this,jn,"m",I9).call(this)}},r),this.emit("add"),Ge(this,jn,"m",xP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ge(this,Ju,"f")?(fn(this,Ju,!1,"f"),Ge(this,jn,"m",kP).call(this),this):this}pause(){fn(this,Ju,!0,"f")}clear(){fn(this,wo,new(Ge(this,bP,"f")),"f")}async onEmpty(){Ge(this,wo,"f").size!==0&&await Ge(this,jn,"m",SP).call(this,"empty")}async onSizeLessThan(e){Ge(this,wo,"f").size<e||await Ge(this,jn,"m",SP).call(this,"next",()=>Ge(this,wo,"f").size<e)}async onIdle(){Ge(this,vo,"f")===0&&Ge(this,wo,"f").size===0||await Ge(this,jn,"m",SP).call(this,"idle")}get size(){return Ge(this,wo,"f").size}sizeBy(e){return Ge(this,wo,"f").filter(e).length}get pending(){return Ge(this,vo,"f")}get isPaused(){return Ge(this,Ju,"f")}};Lw=new WeakMap,Kw=new WeakMap,Zu=new WeakMap,EP=new WeakMap,zw=new WeakMap,vP=new WeakMap,Ca=new WeakMap,Uw=new WeakMap,wo=new WeakMap,bP=new WeakMap,vo=new WeakMap,qw=new WeakMap,Ju=new WeakMap,PP=new WeakMap,jn=new WeakSet,E9=function(){return Ge(this,Kw,"f")||Ge(this,Zu,"f")<Ge(this,EP,"f")},k9=function(){return Ge(this,vo,"f")<Ge(this,qw,"f")},I9=function(){var e;fn(this,vo,(e=Ge(this,vo,"f"),e--,e),"f"),Ge(this,jn,"m",xP).call(this),this.emit("next")},_9=function(){Ge(this,jn,"m",jA).call(this),Ge(this,jn,"m",CA).call(this),fn(this,Uw,void 0,"f")},T9=function(){let e=Date.now();if(Ge(this,Ca,"f")===void 0){let r=Ge(this,vP,"f")-e;if(r<0)fn(this,Zu,Ge(this,Lw,"f")?Ge(this,vo,"f"):0,"f");else return Ge(this,Uw,"f")===void 0&&fn(this,Uw,setTimeout(()=>{Ge(this,jn,"m",_9).call(this)},r),"f"),!0}return!1},xP=function(){if(Ge(this,wo,"f").size===0)return Ge(this,Ca,"f")&&clearInterval(Ge(this,Ca,"f")),fn(this,Ca,void 0,"f"),this.emit("empty"),Ge(this,vo,"f")===0&&this.emit("idle"),!1;if(!Ge(this,Ju,"f")){let e=!Ge(this,jn,"a",T9);if(Ge(this,jn,"a",E9)&&Ge(this,jn,"a",k9)){let r=Ge(this,wo,"f").dequeue();return r?(this.emit("active"),r(),e&&Ge(this,jn,"m",CA).call(this),!0):!1}}return!1},CA=function(){Ge(this,Kw,"f")||Ge(this,Ca,"f")!==void 0||(fn(this,Ca,setInterval(()=>{Ge(this,jn,"m",jA).call(this)},Ge(this,zw,"f")),"f"),fn(this,vP,Date.now()+Ge(this,zw,"f"),"f"))},jA=function(){Ge(this,Zu,"f")===0&&Ge(this,vo,"f")===0&&Ge(this,Ca,"f")&&(clearInterval(Ge(this,Ca,"f")),fn(this,Ca,void 0,"f")),fn(this,Zu,Ge(this,Lw,"f")?Ge(this,vo,"f"):0,"f"),Ge(this,jn,"m",kP).call(this)},kP=function(){for(;Ge(this,jn,"m",xP).call(this););},A9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new _P("The task was aborted."))},{once:!0})})},SP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var R9=$A;Vc();async function D9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Uf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,zf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=ns.unmarshal(e.Data)}catch(u){throw(0,zf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Uf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,zf.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let d=e.Links[u],l=n,f=l+i.blockSizes[u];if((s>=l&&s<f||a>=l&&a<=f||s<l&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await rm(c,u=>em(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Lf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case iy:h=Wc(l);break;case Qd:h=l;break;default:r.end((0,zf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new R9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new gn("unixfs:exporter:walk:file",{cid:d.Hash})),await D9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var tue=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:d,end:l}=Xh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=gP();c.onProgress?.(new gn("unixfs:exporter:walk:file",{cid:t})),D9(o,e,p,0n,d,l,c).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,zf.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(),c.onProgress?.(new gn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,zf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},MA=tue;w();Io();Vc();var rue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new gn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),C9(e,n,s,a,o,c)}return i};async function*C9(t,e,r,n,s,a){let o=t.Links,i=rm(o,c=>em(c,u=>async()=>{let d=u.Name!=null?u.Name.substring(2):null;if(d!=null&&d!==""){let l=await r(u.Hash,d,`${e}/${d}`,[],n+1,s,a);return{entries:l.entry==null?[]:[l.entry]}}else{let l=await s.get(u.Hash,a);return t=Wc(l),a.onProgress?.(new gn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:C9(t,e,r,n,s,a)}}}),c=>Lf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var j9=rue;var nue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,sue={raw:MA,file:MA,directory:w9,"hamt-sharded-directory":j9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},iue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Wc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,Fw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=ns.unmarshal(u.Data)}catch(h){throw(0,Fw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await l9(u,n[0],o):h=nue(u,n[0]),h==null)throw(0,Fw.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;l={cid:h,toResolve:n,name:p??"",path:m}}let f=sue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,Fw.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}},$9=iue;var oue={[iy]:$9,[Qd]:c9,[Vd]:s9,[r9.code]:o9},O9=async(t,e,r,n,s,a,o)=>{let i=oue[t.code];if(i==null)throw(0,M9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,O9,s,a,o)},B9=O9;var aue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),cue=t=>{if(t instanceof Uint8Array)return{cid:qt.decode(t),toResolve:[]};let e=qt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=aue(t);return{cid:qt.parse(r[0]),toResolve:r.slice(1)}}throw(0,TP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*due(t,e,r={}){let{cid:n,toResolve:s}=cue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await B9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,TP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function N9(t,e,r={}){let n=await XK(due(t,e,r));if(n==null)throw(0,TP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}HS();var OA=new TextEncoder,IP=new TextDecoder,BA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:zi,...e},this.blockstore=new Nf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,r,n,s){let a=await this.getRefsPartition(e,r),o=await a.get(n);if(o){await s.cancel();let{dataSize:l}=JSON.parse(IP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(IP.decode(c)):{count:0,dataSize:0},d;if(u.count>0)await s.cancel(),d=u.dataSize;else{let l=await this.getBlocksPartition(n),f=yy([{content:rs.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,OA.encode(JSON.stringify({dataSize:d}))),await i.put(n,OA.encode(JSON.stringify({count:u.count+1,dataSize:d}))),{dataSize:d}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(IP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await N9(n,i)).content(),l=new ReadableStream({async pull(f){let h=await d.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:o,dataStream:l}}async delete(e,r,n){let s=await this.getRefsPartition(e,r);if(!await s.get(n))return;await s.delete(n);let o=await this.getRefcountsPartition(),i=await o.get(n);if(!i)return;let c=JSON.parse(IP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,OA.encode(JSON.stringify({count:u,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,r){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(r)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}};w();ms();ZS();Ya();w();wa();Ya();var AP="";async function U9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function L9(t,e,r,n,s){let a=[];for(let u of r.properties){let d=e[u];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[r.sortProperty];if(o===void 0||Array.isArray(o))return;let i=a.join(AP),c=n(o);return i+AP+c+s+t}function K9(t,e,r){let n=[];for(let s of e.properties){let a=t[s];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join(AP)+AP}function z9(t,e,r,n,s,a){let o=L9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return F9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function q9(t,e,r,n,s,a,o){let i=L9(r,n,s,a,o);if(i!==void 0)return F9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function F9(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function NA(t,e,r){let n,s=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let i of a.properties){let c=t[i];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>s&&(n=a,s=a.properties.length)}return n}async function G9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=K9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await U9(t,e,s),p={};if(d!==void 0){let E=a(d.value),_=f+E+o+d.messageCid;u===1?(p.gt=_,p.lt=f+"\xFF"):(p.lt=_,p.gt=f,p.reverse=!0)}else u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let v=[];for await(let[E,_]of h.iterator(p,c)){if(l!==void 0&&v.length===l)break;let I=JSON.parse(_);S&&!Gt.matchFilter(I.indexes,y)||v.push(I)}return v}async function W9(t,e,r,n,s,a,o){let i=K9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await U9(t,e,n),u=new Set(n.properties),d=!1,l={};for(let p in r)u.has(p)||(l[p]=r[p],d=!0);let f={gt:i,lt:i+"\xFF"},h=0;if(d)for await(let[p,m]of c.iterator(f,o)){let y=JSON.parse(m);Gt.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ht();wa();var V9="index",nm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:zi,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Da({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,r,n,s){if(Il(n))throw new ne("IndexMissingIndexableProperty","Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},o=[];for(let d in n){let l=n[d];if(Array.isArray(l))for(let f of l){let h=this.createPutIndexedItemOperation(e,a,d,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,d,l);o.push(f)}}for(let d of this._compoundIndexes){let l=z9(this.db,e,a,d,t.encodeValue,t.delimiter);l!==void 0&&o.push(l)}let i=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});o.push(i);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,s)}async delete(e,r,n){let s=[],a=await this.getIndexes(e,r);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});s.push(o);for(let u in a){let d=a[u];if(Array.isArray(d))for(let l of d){let f=this.createDeleteIndexedItemOperation(e,r,u,l);s.push(f)}else{let l=this.createDeleteIndexedItemOperation(e,r,u,d);s.push(l)}}for(let u of this._compoundIndexes){let d=q9(this.db,e,r,a,u,t.encodeValue,t.delimiter);d!==void 0&&s.push(d)}let i=await Promise.all(s);await(await this.db.partition(e)).batch(i,n)}async createPutIndexedItemOperation(e,r,n,s){let{messageCid:a}=r,o=t.keySegmentJoin(t.encodeValue(s),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(s),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let s=await this.db.partition(e),a=t.getIndexPartitionName(r);return s.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(V9,r)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,r){let n=t.getIndexPartitionName(r);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(V9)}async query(e,r,n,s){if(r.length===1&&!Il(r[0])){let a=NA(r[0],n,this._compoundIndexes);if(a!==void 0)return G9(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),s)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,s):this.queryWithIteratorPaging(e,r,n,s)}async count(e,r,n,s){if(r.length===1&&!Il(r[0])){let o=NA(r[0],{...n},this._compoundIndexes);if(o!==void 0)return W9(this.db,e,r[0],o,t.encodeValue,this.query.bind(this),s)}return(await this.query(e,r,{...n},s)).length}async queryWithIteratorPaging(e,r,n,s){let{cursor:a,limit:o}=n,i=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let u of this.getIndexIterator(e,i,n,s)){if(o!==void 0&&o===c.length)break;let{indexes:d}=u;Gt.matchAnyFilter(d,r)&&c.push(u)}return c}async*getIndexIterator(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i}=n,c={gt:r};o===-1&&(c.reverse=!0,i!==void 0&&(c.lt=r,delete c.gt));let u=await this.getIndexPartition(e,a);for await(let[d,l]of u.iterator(c,s)){let{indexes:f,messageCid:h}=JSON.parse(l);yield{indexes:f,messageCid:h}}}createStartingKeyFromCursor(e){let{messageCid:r,value:n}=e;return t.keySegmentJoin(t.encodeValue(n),r)}static createCursorFromLastArrayItem(e,r){if(e.length>0)return this.createCursorFromItem(e.at(-1),r)}static createCursorFromItem(e,r){let{messageCid:n,indexes:s}=e,a=s[r];if(a===void 0)throw new ne("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ne("IndexInvalidCursorValueType",`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i,limit:c}=n,u=i?this.createStartingKeyFromCursor(i):void 0,d=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,d,s)}catch(p){if(p.code==="IndexInvalidSortPropertyInMemory")return[]}let l=[...d.values()].sort((p,m)=>this.sortItems(p,m,a,o)),f=u!==void 0?this.findCursorStartingIndex(l,o,a,u):0;if(f<0)return[];let h=c!==void 0?f+c:void 0;return l.slice(f,h)}async executeSingleFilterQuery(e,r,n,s,a){let o=c=>{for(let u of c)if(!(s.has(u.messageCid)||!Gt.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new ne("IndexInvalidSortPropertyInMemory",`invalid sort property ${n}`);s.set(u.messageCid,u)}};if(Il(r)){let c=await this.getAllItems(e,n);o(c);return}let i=$v.reduceFilter(r);for(let c in i){let u=i[c];if(Gt.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Gt.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Gt.isRangeFilter(u)){let d=await this.filterRangeMatches(e,c,u,a);o(d)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),s=[];for await(let[a,o]of n.iterator())s.push(JSON.parse(o));return s}async filterExactMatches(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(n)),o={gt:a},i=await this.getIndexPartition(e,r),c=[];for await(let[u,d]of i.iterator(o,s)){if(!u.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,r,n,s){let a={};for(let c in n){let u=c,d=t.encodeValue(n[u]);u==="lte"?a[u]=d+"\xFF":a[u]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],i=await this.getIndexPartition(e,r);for await(let[c,u]of i.iterator(a,s))"gt"in n&&this.extractIndexValueFromKey(c)===t.encodeValue(n.gt)||o.push(JSON.parse(u));return o}sortItems(e,r,n,s){let a=e.indexes[n],o=r.indexes[n],i=t.encodeValue(a)+e.messageCid,c=t.encodeValue(o)+r.messageCid;return s===1?gy(i,c):gy(c,i)}findCursorStartingIndex(e,r,n,s){let a=c=>{let{messageCid:u,indexes:d}=c,l=d[n],f=t.keySegmentJoin(t.encodeValue(l),u);return r===1?f>s:f<s},o=0,i=e.length;for(;o<i;){let c=o+i>>>1;a(e[c])?i=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,r){let s=await(await this.getIndexesLookupPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}extractIndexValueFromKey(e){let[r]=e.split(t.delimiter);return r}static delimiter="\0";static keySegmentJoin(...e){return e.join(t.delimiter)}static encodeNumberValue(e){let r=Number.MAX_SAFE_INTEGER,n="!",s=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?r:0;return a+String(e+o).padStart(s,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,r){for(let n of e)if(!t.isFilterConcise(n,r))return!1;return!0}static isFilterConcise(e,r){return e.recordId!==void 0?!0:r.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}};w();w();ey();Z2();function RP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*uue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=qt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*UA(n,s))}else{let r=qt.asCID(e);r?yield[t.join("/"),r]:yield*UA(e,t)}}function*UA(t,e){if(t==null||t instanceof Uint8Array)return;let r=qt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*uue(a,s)}}function*lue(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!qt.asCID(n)&&(yield*LA(n,s))}else yield*LA(e,t)}function*LA(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let s=[...e,r];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!qt.asCID(n)&&(yield*lue(s,n))}}function fue(t,e){let r=t;for(let[n,s]of e.entries()){if(r=r[s],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=qt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var DP=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:RP(),bytes:RP(),value:RP(),asBlock:RP()})}links(){return UA(this.value,[])}tree(){return LA(this.value,[])}get(e="/"){return fue(this.value,e.split("/").filter(Boolean))}};async function H9({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),s=await r.digest(n),a=qt.create(1,e.code,s);return new DP({value:t,bytes:n,cid:a})}async function J9({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),s=await r.digest(t),a=qt.create(1,e.code,s);return new DP({value:n,bytes:t,cid:a})}Ip();Hc();Gc();or();Dd();Ya();var hue=[{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"}],KA=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:zi,...e},this.blockstore=new Nf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new nm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??hue})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,r,n){n?.signal?.throwIfAborted();let s=await Nn(this.blockstore.partition(e),n?.signal),a=qt.parse(r),o=await s.get(a,n);return o?(await Nn(J9({bytes:o,codec:Fc,hasher:Sn}),n?.signal)).value:void 0}async query(e,r,n,s,a){a?.signal?.throwIfAborted();let o=t.buildQueryOptions(n,s),i=await this.index.query(e,r,o,a),c;s?.limit!==void 0&&s.limit<i.length&&(i.splice(-1),c=nm.createCursorFromLastArrayItem(i,o.sortProperty));let u=[];for(let d=0;d<i.length;d++){let{messageCid:l}=i[d],f=await this.get(e,l,a);f&&u.push(f)}return{messages:u,cursor:c}}async count(e,r,n,s){s?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,s)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:s}=r,{dateCreated:a,datePublished:o,messageTimestamp:i}=e,c=1,u="messageTimestamp";return a!==void 0?u="dateCreated":o!==void 0?u="datePublished":i!==void 0&&(u="messageTimestamp"),e[u]!==void 0&&(c=e[u]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:u,limit:n,cursor:s}}async delete(e,r,n){n?.signal?.throwIfAborted();let s=await Nn(this.blockstore.partition(e),n?.signal),a=qt.parse(r);await s.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,s){s?.signal?.throwIfAborted();let a=await Nn(this.blockstore.partition(e),s?.signal),o=await Nn(H9({value:r,codec:Fc,hasher:Sn}),s?.signal),i=Dr.parseCid(await we.getCid(r));await a.put(i,o.bytes,s);let c=i.toString();await this.index.put(e,c,n,s)}async clear(){await this.blockstore.clear(),await this.index.clear()}};w();Hc();var zA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:zi,...e},this.db=new Da({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,r){let n=await Dr.computeCid(e),s={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(s)),s}async grab(e){let r=[];for await(let[n,s]of this.db.iterator()){let a=JSON.parse(s);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+t.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),r.push(a)),r.length>=e)break}return r}async read(e){let r=await this.db.get(e);if(r)return JSON.parse(r)}async extend(e,r){let n=await this.db.get(e);if(n){let s=JSON.parse(n);s.timeout=Date.now()+r*1e3,await this.db.put(s.id,JSON.stringify(s))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}};w();w();function Z9(t){return{all:t=t||new Map,on:function(e,r){var n=t.get(e);n?n.push(r):t.set(e,[r])},off:function(e,r){var n=t.get(e);n&&(r?n.splice(n.indexOf(r)>>>0,1):t.set(e,[]))},emit:function(e,r){var n=t.get(e);n&&n.slice().map(function(s){s(r)}),(n=t.get("*"))&&n.slice().map(function(s){s(e,r)})}}}wa();ht();var Y9="events",qA=class t{emitter=Z9();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 r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,r,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(r),messageCid:n}}async validateCursor(e,r){let n=await this.getStreamId(e),s;if(r.streamId!==n)s="stream_mismatch";else if(r.epoch!==this.epoch)s="epoch_mismatch";else{let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let u=c.keys().next().value;if(t.parsePosition(r.position)<u-1)s="token_too_old";else return}else return}let a=await this.getReplayBounds(e),o={requested:r,oldestAvailable:a?.oldest??r,latestAvailable:a?.latest??r,reason:s},i=new ne("EventLogProgressGap",`progress token gap: ${s}`);throw i.gapInfo=o,i}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,r,n,s){if(!this.isOpen){this.errorHandler(new ne("EventLogNotOpenError","a message emitted when EventLog is closed"));return}let o=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,o);let i=this.tenantLogs.get(e);if(i===void 0&&(i=new Map,this.tenantLogs.set(e,i)),i.set(o,{event:r,indexes:n,messageCid:s}),i.size>this.maxEventsPerTenant){let u=i.size-this.maxEventsPerTenant,d=0;for(let l of i.keys()){if(d>=u)break;i.delete(l),d++}}let c=`${e}_${Y9}`;return this.emitter.emit(c,{tenant:e,event:r,indexes:n,seq:o,messageCid:s}),this.buildToken(e,o,s)}async read(e,r={}){let{cursor:n,limit:s,filters:a}=r;n!==void 0&&await this.validateCursor(e,n);let o=n!==void 0?t.parsePosition(n.position):void 0,i=this.tenantLogs.get(e);if(i===void 0||i.size===0)return{events:[],cursor:n};let c=[],u=s??Number.MAX_SAFE_INTEGER;for(let[d,l]of i)if(!(o!==void 0&&d<=o)&&!(a!==void 0&&a.length>0&&!Gt.matchAnyFilter(l.indexes,a))&&(c.push({seq:d,event:l.event,indexes:l.indexes,messageCid:l.messageCid}),c.length>=u))break;if(c.length>0){let d=c[c.length-1],l=await this.buildToken(e,d.seq,d.messageCid);return{events:c,cursor:l}}return{events:c,cursor:n}}static parsePosition(e){try{let r=BigInt(e);if(r<0n)throw new ne("EventLogNotOpenError",`invalid cursor position: '${e}'`);return Number(r)}catch(r){throw r instanceof ne?r:new ne("EventLogNotOpenError",`invalid cursor position: '${e}'`)}}async subscribe(e,r,n,s){let a=`${e}_${Y9}`,{cursor:o,filters:i}=s??{},c=async d=>this.buildToken(e,d.seq,d.messageCid);if(o!==void 0){await this.validateCursor(e,o);let d=t.parsePosition(o.position),l=[],f=!1,h=S=>{i!==void 0&&i.length>0&&!Gt.matchAnyFilter(S.indexes,i)||(f?c(S).then(v=>{n({type:"event",cursor:v,event:S.event})}):l.push({event:S.event,seq:S.seq,messageCid:S.messageCid}))};this.emitter.on(a,h);let p=await this.read(e,{cursor:o,filters:i}),m=p.cursor??o,y=p.cursor!==void 0?t.parsePosition(p.cursor.position):d;for(let S of p.events){let v=await this.buildToken(e,S.seq,S.messageCid??"");n({type:"event",cursor:v,event:S.event})}f=!0;for(let S of l)if(S.seq>y){let v=await this.buildToken(e,S.seq,S.messageCid);n({type:"event",cursor:v,event:S.event})}return n({type:"eose",cursor:m}),{id:r,close:async()=>{this.emitter.off(a,h)}}}let u=d=>{i!==void 0&&i.length>0&&!Gt.matchAnyFilter(d.indexes,i)||c(d).then(l=>{n({type:"event",cursor:l,event:d.event})})};return this.emitter.on(a,u),{id:r,close:async()=>{this.emitter.off(a,u)}}}async getReplayBounds(e){let r=this.tenantLogs.get(e);if(r===void 0||r.size===0)return;let n=[...r.keys()],s=n[0],a=n[n.length-1],o=r.get(s),i=r.get(a),c=await this.buildToken(e,s,o.messageCid),u=await this.buildToken(e,a,i.messageCid);return{oldest:c,latest:u}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let s of n.keys())if(s<r)n.delete(s);else break;else for(let[s,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(s)}};w();bu();w();bu();var Gw=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 r=Jn(e),n=await this.nodesPartition.get(r);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,r){this.ensureInitialized();let n=Jn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Jn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return tf(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Jn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Jn(e.leftHash),rightHash:Jn(e.rightHash)}:{type:"leaf",keyHash:Jn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:tf(e.leftHash),rightHash:tf(e.rightHash)}:{type:"leaf",keyHash:tf(e.keyHash),valueCid:e.valueCid}}};w();bu();var Ww=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await hh()}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 r=await ef(e),n=await lg(r,e),s={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,s);let a=await this.getRoot(),o=await this.insertAtNode(a,r,n,s,0);return await this.store.setRoot(o),o}async delete(e){let r=await ef(e),n=await this.getRoot(),s=await this.deleteAtNode(n,r,0);return await this.store.setRoot(s),s}async has(e){let r=await ef(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await ef(e),n=await this.getRoot();return this.generateProof(n,r,0)}async getSubtreeHash(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(rn(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let s=await this.store.getNode(r);if(s===void 0||s.type==="leaf")return s!==void 0&&s.type==="leaf"?this.computeSubtreeHashForLeaf(s,n,e):this.defaultHashes[e.length];let a=s;e[n]?r=a.rightHash:r=a.leftHash}return r}async getLeaves(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(rn(r,this.defaultHashes[n]))return[];let s=await this.store.getNode(r);if(s===void 0)return[];if(s.type==="leaf")return this.leafMatchesPrefix(s.keyHash,e)?[s.valueCid]:[];let a=s;e[n]?r=a.rightHash:r=a.leftHash}return this.collectLeaves(r,e.length)}async diff(e){let r=await this.getRoot(),n=await e.getRoot();if(rn(r,n))return{onlyLocal:[],onlyRemote:[]};let s=[],a=[];return await this.diffAtNode(r,n,0,this,e,s,a),{onlyLocal:s,onlyRemote:a}}async insertAtNode(e,r,n,s,a){if(a>=Pi||rn(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return rn(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=uo(r,a),u,d;c?(u=i.leftHash,d=await this.insertAtNode(i.rightHash,r,n,s,a+1)):(u=await this.insertAtNode(i.leftHash,r,n,s,a+1),d=i.rightHash);let l=await vu(u,d);if(!rn(l,e)){let f={type:"internal",leftHash:u,rightHash:d};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async splitLeaves(e,r,n,s,a){let o=a;for(;o<Pi&&uo(e.keyHash,o)===uo(n.keyHash,o);)o++;if(o>=Pi)return s;let i=uo(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await vu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=uo(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await vu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=Pi)return this.defaultHashes[Pi];if(rn(e,this.defaultHashes[n]))return e;let s=await this.store.getNode(e);if(s===void 0)return this.defaultHashes[n];if(s.type==="leaf")return rn(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=uo(r,n),i,c;if(o?(i=a.leftHash,c=await this.deleteAtNode(a.rightHash,r,n+1)):(i=await this.deleteAtNode(a.leftHash,r,n+1),c=a.rightHash),rn(i,this.defaultHashes[n+1])&&rn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=rn(i,this.defaultHashes[n+1]),d=rn(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let l=await vu(i,c);if(!rn(l,e)){let f={type:"internal",leftHash:i,rightHash:c};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async existsAtNode(e,r,n){if(n>=Pi||rn(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return rn(s.keyHash,r);let a=s;return uo(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=Pi)return{siblings:[],leafNode:void 0,depth:n};if(rn(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let s=await this.store.getNode(e);if(s===void 0)return{siblings:[],leafNode:void 0,depth:n};if(s.type==="leaf")return{siblings:[],leafNode:s,depth:n};let a=s,o=uo(r,n),i,c;o?(i=a.rightHash,c=a.leftHash):(i=a.leftHash,c=a.rightHash);let u=await this.generateProof(i,r,n+1);return u.siblings.unshift(c),u}async computeSubtreeHashForLeaf(e,r,n){for(let s=r;s<n.length;s++)if(uo(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await lg(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(uo(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=Pi||rn(e,this.defaultHashes[r]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let s=n,a=await this.collectLeaves(s.leftHash,r+1),o=await this.collectLeaves(s.rightHash,r+1);return[...a,...o]}async diffAtNode(e,r,n,s,a,o,i){if(rn(e,r)||n>=Pi)return;let c=rn(e,this.defaultHashes[n]),u=rn(r,this.defaultHashes[n]);if(c&&!u){let f=await a.collectLeaves(r,n);i.push(...f);return}if(!c&&u){let f=await s.collectLeaves(e,n);o.push(...f);return}let d=await s.store.getNode(e),l=await a.store.getNode(r);if(d?.type==="leaf"&&l?.type==="leaf"){rn(d.keyHash,l.keyHash)?d.valueCid!==l.valueCid&&(o.push(d.valueCid),i.push(l.valueCid)):(o.push(d.valueCid),i.push(l.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(r,n),h=d.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&i.push(m);return}if(l?.type==="leaf"){let f=await s.collectLeaves(e,n),h=l.valueCid;new Set(f).has(h)||i.push(h);for(let m of f)m!==h&&o.push(m);return}if(d?.type==="internal"&&l?.type==="internal"){await this.diffAtNode(d.leftHash,l.leftHash,n+1,s,a,o,i),await this.diffAtNode(d.rightHash,l.rightHash,n+1,s,a,o,i);return}if(d===void 0){let f=await a.collectLeaves(r,n);i.push(...f)}if(l===void 0){let f=await s.collectLeaves(e,n);o.push(...f)}}};var FA=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:zi,...e}}async open(){this.db=new Da({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await hh()}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,r,n){await(await this.getGlobalTree(e)).insert(r);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(r),await this.storeIndexes(e,r,n)}async delete(e,r){let n=await this.getGlobalTree(e);for(let s of r){let a=await this.getStoredIndexes(e,s);if(await n.delete(s),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(s)}await this.deleteStoredIndexes(e,s)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,r){return(await this.getProtocolTree(e,r)).getRoot()}async getSubtreeHash(e,r){return(await this.getGlobalTree(e)).getSubtreeHash(r)}async getProtocolSubtreeHash(e,r,n){return(await this.getProtocolTree(e,r)).getSubtreeHash(n)}async getLeaves(e,r){return(await this.getGlobalTree(e)).getLeaves(r)}async getProtocolLeaves(e,r,n){return(await this.getProtocolTree(e,r)).getLeaves(n)}getGlobalTree(e){let r=this.globalTrees.get(e);return r!==void 0||(r=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,r)),r}getProtocolTree(e,r){let n=`${e}\0${r}`,s=this.protocolTrees.get(n);return s!==void 0||(s=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,s)),s}async createTree(e,r){let n=e;for(let o of r)n=await n.partition(o);let s=new Gw(n),a=new Ww(s);return await a.initialize(),a}async storeIndexes(e,r,n){let s=await this.getMetaPartition(e),a={protocol:n.protocol};await s.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let s=await(await this.getMetaPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}};w();bu();var GA=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(Jn(e))}async putNode(e,r){this.nodes.set(Jn(e),r)}async deleteNode(e){this.nodes.delete(Jn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};bu();w();Ip();Gc();Hd();YP();hn();Na();T0();On();bi();ms();d0();Dd();Hs();Lp();Cy();Xt();zp();var mue={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},WA=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),s=e?.keyId??`${r}#${n}`,a=e?.keyPair??await Oa.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await vn.generateKey();o={publicJwk:await vn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ld({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await pd.create({definition:mue,signer:vt.createSigner(r)}),s=await e.processMessage(r.did,n.message);if(s.status.code!==202)throw new Error(`Failed to install default test protocol: ${s.status.code} ${s.status.detail}`)}static async generateProtocolsConfigure(e){let r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let i="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[i]={schema:"test-object",dataFormats:["text/plain"]},n.structure[i]={}}let s=vt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await pd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Ft(s);let a=await mf.create(s);return{author:r,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let r=e?.author??await t.generatePersona(),n=e?.grantedTo??await t.generatePersona(),s=e?.dateExpires??yt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:"Messages",method:"Read"},o=vt.createSigner(r),i=n.did,c={signer:o,grantedTo:i,dateExpires:s,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},u=await Ir.createGrant(c);return{dataStream:rs.fromBytes(u.permissionGrantBytes),recordsWrite:u.recordsWrite,dataBytes:u.permissionGrantBytes,message:u.recordsWrite.message,dataEncodedMessage:u.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s=vt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=rs.fromBytes(i));let u={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${t.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:i,dataCid:a,dataSize:o,signer:n,attestationSigners:s,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await xt.create(u),l=d.message;return{author:r,message:l,dataCid:a,dataSize:o,dataBytes:i,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:s,protocolDefinition:a,protocolPath:o,protocolParentContextId:i,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:u}=e,d=t.randomBytes(12),l=t.randomBytes(32),{ciphertext:f,tag:h}=await ga.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:v}=await t.generateRecordsWrite({author:n,recipient:s,protocol:a.protocol,protocolPath:o,parentContextId:i,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:l,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let $ of p)_=_[$];let I=_.$encryption?.publicKeyJwk,N={publicKeyId:_.$encryption?.rootKeyId,publicKey:I,derivationScheme:"protocolPath"};E.keyEncryptionInputs.push(N)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(i===void 0){let I={rootKeyId:n.keyId,derivationScheme:"protocolContext",derivedPrivateKey:n.encryptionKeyPair.privateJwk},R=await xt.getEntryId(n.did,y.descriptor),N=_e.constructKeyDerivationPathUsingProtocolContextScheme(R),$=await Ja.derivePublicKey(I,N);_={publicKeyId:n.keyId,publicKey:$,derivationScheme:"protocolContext"}}else{if(c===void 0||u===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:u,derivationScheme:"protocolContext"}}E.keyEncryptionInputs.push(_)}return await v.encryptSymmetricEncryptionKey(E),await v.sign({signer:vt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:v,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=yt.getCurrentTimestamp(),s=!(e.published??r.descriptor.published),a=e.datePublished??(s?n:void 0),o=e.data??t.randomBytes(32),i=rs.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:vt.createSigner(e.author)},u=await xt.createFrom(c);return{message:u.message,recordsWrite:u,dataBytes:o,dataStream:i}}static async generateRecordsQuery(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Ft(a);let i=(await Zl.create(a)).message;return{author:r,message:i}}static async generateRecordsSubscribe(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Ft(a);let i=(await yf.create(a)).message;return{author:r,message:i}}static async generateRecordsCount(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};Ft(a);let i=(await Jl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await hd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:vt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Ft(s);let a=await Ql.create(s),o=a.message;return{author:r,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),s={signer:vt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Yl.create(s);return{author:r,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:t.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await pm.generateKeyPair(),r=await pm.sign(t.randomBytes(32),e.privateJwk);return Te.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let s=0;s<e;s++)n+=r.charAt(Math.floor(Math.random()*r.length));return n}static randomBytes(e){let r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=Math.floor(Math.random()*256);return r}static async randomCborSha256Cid(){let e=t.randomBytes(32),r=await Sn.digest(e);return(await qt.createV1(Vd,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:s,hour:a,minute:o,second:i,millisecond:c,microsecond:u}=e||{};return yt.createTimestamp({year:r||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:s||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:i||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:u||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 Mw.create(),r=await Mw.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await vn.generateKey(),c={publicJwk:await vn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ld({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};w();Hs();var VA=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let s=Date.now();for(;;)try{return await e()}catch{if(Date.now()-s>=n)throw new Error("Operation timed out");await yt.sleep(r)}}};export{dg as AllowAllTenantGate,Nf as BlockstoreLevel,Dr as Cid,LE as ContentEncryptionAlgorithm,cg as CoreProtocolRegistry,BA as DataStoreLevel,rs as DataStream,Mp as DateSort,xA as Dwn,jo as DwnConstant,ne as DwnError,pt as DwnErrorCode,Qt as DwnInterfaceName,cr as DwnMethodName,Te as Encoder,ga as Encryption,qA as EventEmitterEventLog,Ja as HdKey,nm as IndexLevel,vt as Jws,g3 as KeyAgreementAlgorithm,Kp as KeyDerivationScheme,Da as LevelWrapper,we as Message,KA as MessageStoreLevel,Yl as MessagesRead,Ql as MessagesSubscribe,fg as MessagesSync,KE as PERMISSIONS_REVOCATION_PATH,v3 as PermissionConditionPublication,Xr as PermissionGrant,ug as PermissionRequest,Ir as PermissionsProtocol,VA as Poller,Ld as PrivateKeySigner,dm as ProtocolRecordLimitStrategy,sI as Protocols,pd as ProtocolsConfigure,mf as ProtocolsQuery,_e as Records,Jl as RecordsCount,hd as RecordsDelete,Zl as RecordsQuery,Vg as RecordsRead,yf as RecordsSubscribe,xt as RecordsWrite,zA as ResumableTaskStoreLevel,Gw as SMTStoreLevel,GA as SMTStoreMemory,Pi as SMT_DEPTH,Oa as Secp256k1,Ud as Secp256r1,Za as SortDirection,Ww as SparseMerkleTree,FA as StateIndexLevel,WA as TestDataGenerator,yt as Time,s_ as ZERO_HASH,dn as authenticate,zi as createLevelDatabase,Nn as executeUnlessAborted,uo as getBit,gO as getDefaultHashes,fd as getRuleSetAtPath,vu as hashChildren,rn as hashEquals,ef as hashKey,lg as hashLeaf,Jn as hashToHex,tf as hexToHash,hh as initDefaultHashes,hf as isCrossProtocolRef,Ni as parseCrossProtocolRef};
11
11
  /*! Bundled license information:
12
12
 
13
13
  ieee754/index.js: