@enbox/dwn-sdk-js 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.mjs +1 -1
- package/dist/browser.mjs.map +3 -3
- package/dist/esm/src/handlers/records-write.js +33 -9
- package/dist/esm/src/handlers/records-write.js.map +1 -1
- package/dist/esm/tests/handlers/records-write.spec.js +15 -0
- package/dist/esm/tests/handlers/records-write.spec.js.map +1 -1
- package/dist/types/src/handlers/records-write.d.ts +1 -0
- package/dist/types/src/handlers/records-write.d.ts.map +1 -1
- package/dist/types/tests/handlers/records-write.spec.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/handlers/records-write.ts +59 -9
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,xt._)`[${s}]`)}}}function TY({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,xt._)`${e} !== undefined`,()=>t.assign((0,xt._)`${e}[${r}]`,n))}function A_(t,e,r,n=wh.Correct){let s=n===wh.Correct?xt.operators.EQ:xt.operators.NEQ,a;switch(t){case"null":return(0,xt._)`${e} ${s} null`;case"array":a=(0,xt._)`Array.isArray(${e})`;break;case"object":a=(0,xt._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=o((0,xt._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=o();break;default:return(0,xt._)`typeof ${e} ${s} ${t}`}return n===wh.Correct?a:(0,xt.not)(a);function o(i=xt.nil){return(0,xt.and)((0,xt._)`typeof ${e} == "number"`,i,r?(0,xt._)`isFinite(${e})`:xt.nil)}}Js.checkDataType=A_;function R_(t,e,r,n){if(t.length===1)return A_(t[0],e,r,n);let s,a=(0,UM.toHash)(t);if(a.array&&a.object){let o=(0,xt._)`typeof ${e} != "object"`;s=a.null?o:(0,xt._)`!${e} || ${o}`,delete a.null,delete a.array,delete a.object}else s=xt.nil;a.number&&delete a.integer;for(let o in a)s=(0,xt.and)(s,A_(o,e,r,n));return s}Js.checkDataTypes=R_;var IY={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,xt._)`{type: ${t}}`:(0,xt._)`{type: ${e}}`};function D_(t){let e=AY(t);(0,xY.reportError)(e,IY)}Js.reportTypeError=D_;function AY(t){let{gen:e,data:r,schema:n}=t,s=(0,UM.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var qM=xe(Cb=>{"use strict";v();Object.defineProperty(Cb,"__esModule",{value:!0});Cb.assignDefaults=void 0;var vh=vt(),RY=$t();function DY(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)zM(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,a)=>zM(t,a,s.default))}Cb.assignDefaults=DY;function zM(t,e,r){let{gen:n,compositeRule:s,data:a,opts:o}=t;if(r===void 0)return;let i=(0,vh._)`${a}${(0,vh.getProperty)(e)}`;if(s){(0,RY.checkStrictMode)(t,`default is ignored for: ${i}`);return}let c=(0,vh._)`${i} === undefined`;o.useDefaults==="empty"&&(c=(0,vh._)`${c} || ${i} === null || ${i} === ""`),n.if(c,(0,vh._)`${i} = ${(0,vh.stringify)(r)}`)}});var Oo=xe(_r=>{"use strict";v();Object.defineProperty(_r,"__esModule",{value:!0});_r.validateUnion=_r.validateArray=_r.usePattern=_r.callValidateCode=_r.schemaProperties=_r.allSchemaProperties=_r.noPropertyInData=_r.propertyInData=_r.isOwnProperty=_r.hasPropFunc=_r.reportMissingProp=_r.checkMissingProp=_r.checkReportMissingProp=void 0;var Wr=vt(),C_=$t(),xu=$o(),CY=$t();function jY(t,e){let{gen:r,data:n,it:s}=t;r.if($_(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Wr._)`${e}`},!0),t.error()})}_r.checkReportMissingProp=jY;function $Y({gen:t,data:e,it:{opts:r}},n,s){return(0,Wr.or)(...n.map(a=>(0,Wr.and)($_(t,e,a,r.ownProperties),(0,Wr._)`${s} = ${a}`)))}_r.checkMissingProp=$Y;function OY(t,e){t.setParams({missingProperty:e},!0),t.error()}_r.reportMissingProp=OY;function FM(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Wr._)`Object.prototype.hasOwnProperty`})}_r.hasPropFunc=FM;function j_(t,e,r){return(0,Wr._)`${FM(t)}.call(${e}, ${r})`}_r.isOwnProperty=j_;function MY(t,e,r,n){let s=(0,Wr._)`${e}${(0,Wr.getProperty)(r)} !== undefined`;return n?(0,Wr._)`${s} && ${j_(t,e,r)}`:s}_r.propertyInData=MY;function $_(t,e,r,n){let s=(0,Wr._)`${e}${(0,Wr.getProperty)(r)} === undefined`;return n?(0,Wr.or)(s,(0,Wr.not)(j_(t,e,r))):s}_r.noPropertyInData=$_;function GM(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}_r.allSchemaProperties=GM;function BY(t,e){return GM(e).filter(r=>!(0,C_.alwaysValidSchema)(t,e[r]))}_r.schemaProperties=BY;function NY({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:a},it:o},i,c,u){let d=u?(0,Wr._)`${t}, ${e}, ${n}${s}`:e,l=[[xu.default.instancePath,(0,Wr.strConcat)(xu.default.instancePath,a)],[xu.default.parentData,o.parentData],[xu.default.parentDataProperty,o.parentDataProperty],[xu.default.rootData,xu.default.rootData]];o.opts.dynamicRef&&l.push([xu.default.dynamicAnchors,xu.default.dynamicAnchors]);let f=(0,Wr._)`${d}, ${r.object(...l)}`;return c!==Wr.nil?(0,Wr._)`${i}.call(${c}, ${f})`:(0,Wr._)`${i}(${f})`}_r.callValidateCode=NY;var UY=(0,Wr._)`new RegExp`;function LY({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,Wr._)`${s.code==="new RegExp"?UY:(0,CY.useFunc)(t,s)}(${r}, ${n})`})}_r.usePattern=LY;function KY(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,Wr._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:C_.Type.Num},a),e.if((0,Wr.not)(a),i)})}}_r.validateArray=KY;function zY(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,C_.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,Wr._)`${o} || ${i}`),t.mergeValidEvaluated(d,i)||e.if((0,Wr.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}_r.validateUnion=zY});var HM=xe(uc=>{"use strict";v();Object.defineProperty(uc,"__esModule",{value:!0});uc.validateKeywordUsage=uc.validSchemaType=uc.funcKeywordCode=uc.macroKeywordCode=void 0;var Pi=vt(),af=$o(),qY=Oo(),FY=bg();function GY(t,e){let{gen:r,keyword:n,schema:s,parentSchema:a,it:o}=t,i=e.macro.call(o.self,s,a,o),c=VM(r,n,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);let u=r.name("valid");t.subschema({schema:i,schemaPath:Pi.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}uc.macroKeywordCode=GY;function WY(t,e){var r;let{gen:n,keyword:s,schema:a,parentSchema:o,$data:i,it:c}=t;HY(c,e);let u=!i&&e.compile?e.compile.call(c.self,a,o,c):e.validate,d=VM(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&&WM(t),y(()=>t.error());else{let S=e.async?h():p();e.modifying&&WM(t),y(()=>VY(t,S))}}function h(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Pi._)`await `),w=>n.assign(l,!1).if((0,Pi._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Pi._)`${w}.errors`),()=>n.throw(w))),S}function p(){let S=(0,Pi._)`${d}.errors`;return n.assign(S,null),m(Pi.nil),S}function m(S=e.async?(0,Pi._)`await `:Pi.nil){let w=c.opts.passContext?af.default.this:af.default.self,E=!("compile"in e&&!i||e.schema===!1);n.assign(l,(0,Pi._)`${S}${(0,qY.callValidateCode)(t,d,w,E)}`,e.modifying)}function y(S){var w;n.if((0,Pi.not)((w=e.valid)!==null&&w!==void 0?w:l),S)}}uc.funcKeywordCode=WY;function WM(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Pi._)`${n.parentData}[${n.parentDataProperty}]`))}function VY(t,e){let{gen:r}=t;r.if((0,Pi._)`Array.isArray(${e})`,()=>{r.assign(af.default.vErrors,(0,Pi._)`${af.default.vErrors} === null ? ${e} : ${af.default.vErrors}.concat(${e})`).assign(af.default.errors,(0,Pi._)`${af.default.vErrors}.length`),(0,FY.extendErrors)(t)},()=>t.error())}function HY({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function VM(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,Pi.stringify)(r)})}function JY(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")}uc.validSchemaType=JY;function ZY({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)}}uc.validateKeywordUsage=ZY});var ZM=xe(Su=>{"use strict";v();Object.defineProperty(Su,"__esModule",{value:!0});Su.extendSubschemaMode=Su.extendSubschemaData=Su.getSubschema=void 0;var lc=vt(),JM=$t();function YY(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,lc._)`${t.schemaPath}${(0,lc.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,lc._)`${t.schemaPath}${(0,lc.getProperty)(e)}${(0,lc.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,JM.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')}Su.getSubschema=YY;function QY(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,lc._)`${e.data}${(0,lc.getProperty)(r)}`,!0);c(f),t.errorPath=(0,lc.str)`${u}${(0,JM.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,lc._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof lc.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]}}Su.extendSubschemaData=QY;function XY(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}Su.extendSubschemaMode=XY});var O_=xe((GRe,YM)=>{"use strict";v();YM.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 XM=xe((VRe,QM)=>{"use strict";v();var Eu=QM.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)};Eu.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Eu.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Eu.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Eu.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 Eu.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 Eu.propsKeywords){if(l&&typeof l=="object")for(var h in l)jb(t,e,r,l[h],s+"/"+d+"/"+eQ(h),a,s,d,n,h)}else(d in Eu.keywords||t.allKeys&&!(d in Eu.skipKeywords))&&jb(t,e,r,l,s+"/"+d,a,s,d,n)}r(n,s,a,o,i,c,u)}}function eQ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var xg=xe(Oi=>{"use strict";v();Object.defineProperty(Oi,"__esModule",{value:!0});Oi.getSchemaRefs=Oi.resolveUrl=Oi.normalizeId=Oi._getFullPath=Oi.getFullPath=Oi.inlineRef=void 0;var tQ=$t(),rQ=O_(),nQ=XM(),sQ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function iQ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!M_(t):e?e4(t)<=e:!1}Oi.inlineRef=iQ;var oQ=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function M_(t){for(let e in t){if(oQ.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 e4(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!sQ.has(r)&&(typeof t[r]=="object"&&(0,tQ.eachItem)(t[r],n=>e+=e4(n)),e===1/0))return 1/0}return e}function t4(t,e="",r){r!==!1&&(e=bh(e));let n=t.parse(e);return r4(t,n)}Oi.getFullPath=t4;function r4(t,e){return t.serialize(e).split("#")[0]+"#"}Oi._getFullPath=r4;var aQ=/#\/?$/;function bh(t){return t?t.replace(aQ,""):""}Oi.normalizeId=bh;function cQ(t,e,r){return r=bh(r),t.resolve(e,r)}Oi.resolveUrl=cQ;var dQ=/^[a-z_][-a-z0-9._]*$/i;function uQ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=bh(t[r]||e),a={"":s},o=t4(n,s,!1),i={},c=new Set;return nQ(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])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),a[f]=y;function S(E){let _=this.opts.uriResolver.resolve;if(E=bh(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!==bh(m)&&(E[0]==="#"?(u(l,i[E],E),i[E]=l):this.refs[E]=m),E}function w(E){if(typeof E=="string"){if(!dQ.test(E))throw new Error(`invalid anchor "${E}"`);S.call(this,`#${E}`)}}}),i;function u(l,f,h){if(f!==void 0&&!rQ(l,f))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Oi.getSchemaRefs=uQ});var kg=xe(ku=>{"use strict";v();Object.defineProperty(ku,"__esModule",{value:!0});ku.getData=ku.KeywordCxt=ku.validateFunctionCode=void 0;var a4=MM(),n4=Pg(),N_=I_(),$b=Pg(),lQ=qM(),Eg=HM(),B_=ZM(),Fe=vt(),ft=$o(),fQ=xg(),dd=$t(),Sg=bg();function pQ(t){if(u4(t)&&(l4(t),d4(t))){yQ(t);return}c4(t,()=>(0,a4.topBoolOrEmptySchema)(t))}ku.validateFunctionCode=pQ;function c4({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},a){s.code.es5?t.func(e,(0,Fe._)`${ft.default.data}, ${ft.default.valCxt}`,n.$async,()=>{t.code((0,Fe._)`"use strict"; ${s4(r,s)}`),mQ(t,s),t.code(a)}):t.func(e,(0,Fe._)`${ft.default.data}, ${hQ(s)}`,n.$async,()=>t.code(s4(r,s)).code(a))}function hQ(t){return(0,Fe._)`{${ft.default.instancePath}="", ${ft.default.parentData}, ${ft.default.parentDataProperty}, ${ft.default.rootData}=${ft.default.data}${t.dynamicRef?(0,Fe._)`, ${ft.default.dynamicAnchors}={}`:Fe.nil}}={}`}function mQ(t,e){t.if(ft.default.valCxt,()=>{t.var(ft.default.instancePath,(0,Fe._)`${ft.default.valCxt}.${ft.default.instancePath}`),t.var(ft.default.parentData,(0,Fe._)`${ft.default.valCxt}.${ft.default.parentData}`),t.var(ft.default.parentDataProperty,(0,Fe._)`${ft.default.valCxt}.${ft.default.parentDataProperty}`),t.var(ft.default.rootData,(0,Fe._)`${ft.default.valCxt}.${ft.default.rootData}`),e.dynamicRef&&t.var(ft.default.dynamicAnchors,(0,Fe._)`${ft.default.valCxt}.${ft.default.dynamicAnchors}`)},()=>{t.var(ft.default.instancePath,(0,Fe._)`""`),t.var(ft.default.parentData,(0,Fe._)`undefined`),t.var(ft.default.parentDataProperty,(0,Fe._)`undefined`),t.var(ft.default.rootData,ft.default.data),e.dynamicRef&&t.var(ft.default.dynamicAnchors,(0,Fe._)`{}`)})}function yQ(t){let{schema:e,opts:r,gen:n}=t;c4(t,()=>{r.$comment&&e.$comment&&p4(t),PQ(t),n.let(ft.default.vErrors,null),n.let(ft.default.errors,0),r.unevaluated&&gQ(t),f4(t),EQ(t)})}function gQ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Fe._)`${r}.evaluated`),e.if((0,Fe._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Fe._)`${t.evaluated}.props`,(0,Fe._)`undefined`)),e.if((0,Fe._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Fe._)`${t.evaluated}.items`,(0,Fe._)`undefined`))}function s4(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Fe._)`/*# sourceURL=${r} */`:Fe.nil}function wQ(t,e){if(u4(t)&&(l4(t),d4(t))){vQ(t,e);return}(0,a4.boolOrEmptySchema)(t,e)}function d4({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 u4(t){return typeof t.schema!="boolean"}function vQ(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&p4(t),xQ(t),SQ(t);let a=n.const("_errs",ft.default.errors);f4(t,a),n.var(e,(0,Fe._)`${a} === ${ft.default.errors}`)}function l4(t){(0,dd.checkUnknownRules)(t),bQ(t)}function f4(t,e){if(t.opts.jtd)return i4(t,[],!1,e);let r=(0,n4.getSchemaTypes)(t.schema),n=(0,n4.coerceAndCheckDataType)(t,r);i4(t,r,!n,e)}function bQ(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,dd.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function PQ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,dd.checkStrictMode)(t,"default is ignored in the schema root")}function xQ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,fQ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function SQ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function p4({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let a=r.$comment;if(s.$comment===!0)t.code((0,Fe._)`${ft.default.self}.logger.log(${a})`);else if(typeof s.$comment=="function"){let o=(0,Fe.str)`${n}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,Fe._)`${ft.default.self}.opts.$comment(${a}, ${o}, ${i}.schema)`)}}function EQ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:a}=t;r.$async?e.if((0,Fe._)`${ft.default.errors} === 0`,()=>e.return(ft.default.data),()=>e.throw((0,Fe._)`new ${s}(${ft.default.vErrors})`)):(e.assign((0,Fe._)`${n}.errors`,ft.default.vErrors),a.unevaluated&&kQ(t),e.return((0,Fe._)`${ft.default.errors} === 0`))}function kQ({gen:t,evaluated:e,props:r,items:n}){r instanceof Fe.Name&&t.assign((0,Fe._)`${e}.props`,r),n instanceof Fe.Name&&t.assign((0,Fe._)`${e}.items`,n)}function i4(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,dd.schemaHasRulesButRef)(a,d))){s.block(()=>m4(t,"$ref",d.all.$ref.definition));return}c.jtd||_Q(t,e),s.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,N_.shouldUseGroup)(a,f)&&(f.type?(s.if((0,$b.checkDataType)(f.type,o,c.strictNumbers)),o4(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,$b.reportTypeError)(t)),s.endIf()):o4(t,f),i||s.if((0,Fe._)`${ft.default.errors} === ${n||0}`))}}function o4(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,lQ.assignDefaults)(t,e.type),r.block(()=>{for(let a of e.rules)(0,N_.shouldUseRule)(n,a)&&m4(t,a.keyword,a.definition,e.type)})}function _Q(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(TQ(t,e),t.opts.allowUnionTypes||IQ(t,e),AQ(t,t.dataTypes))}function TQ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{h4(t.dataTypes,r)||U_(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),DQ(t,e)}}function IQ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&U_(t,"use allowUnionTypes to allow union type keyword")}function AQ(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,N_.shouldUseRule)(t.schema,s)){let{type:a}=s.definition;a.length&&!a.some(o=>RQ(e,o))&&U_(t,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function RQ(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function h4(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function DQ(t,e){let r=[];for(let n of t.dataTypes)h4(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function U_(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,dd.checkStrictMode)(t,e,t.opts.strictTypes)}var Ob=class{constructor(e,r,n){if((0,Eg.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,dd.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",y4(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Eg.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",ft.default.errors))}result(e,r,n){this.failResult((0,Fe.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,Fe.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,Fe._)`${r} !== undefined && (${(0,Fe.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?Sg.reportExtraError:Sg.reportError)(this,this.def.error,r)}$dataError(){(0,Sg.reportError)(this,this.def.$dataError||Sg.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Sg.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=Fe.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Fe.nil,r=Fe.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:a,def:o}=this;n.if((0,Fe.or)((0,Fe._)`${s} === undefined`,r)),e!==Fe.nil&&n.assign(e,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Fe.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:a}=this;return(0,Fe.or)(o(),i());function o(){if(n.length){if(!(r instanceof Fe.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Fe._)`${(0,$b.checkDataTypes)(c,r,a.opts.strictNumbers,$b.DataType.Wrong)}`}return Fe.nil}function i(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Fe._)`!${c}(${r})`}return Fe.nil}}subschema(e,r){let n=(0,B_.getSubschema)(this.it,e);(0,B_.extendSubschemaData)(n,this.it,e),(0,B_.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return wQ(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=dd.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=dd.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,Fe.Name)),!0}};ku.KeywordCxt=Ob;function m4(t,e,r,n){let s=new Ob(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Eg.funcKeywordCode)(s,r):"macro"in r?(0,Eg.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Eg.funcKeywordCode)(s,r)}var CQ=/^\/(?:[^~]|~0|~1)*$/,jQ=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function y4(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,a;if(t==="")return ft.default.rootData;if(t[0]==="/"){if(!CQ.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,a=ft.default.rootData}else{let u=jQ.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,Fe._)`${a}${(0,Fe.getProperty)((0,dd.unescapeJsonPointer)(u))}`,o=(0,Fe._)`${o} && ${a}`);return o;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}ku.getData=y4});var Mb=xe(K_=>{"use strict";v();Object.defineProperty(K_,"__esModule",{value:!0});var L_=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};K_.default=L_});var _g=xe(F_=>{"use strict";v();Object.defineProperty(F_,"__esModule",{value:!0});var z_=xg(),q_=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,z_.resolveUrl)(e,r,n),this.missingSchema=(0,z_.normalizeId)((0,z_.getFullPath)(e,this.missingRef))}};F_.default=q_});var Tg=xe(Mo=>{"use strict";v();Object.defineProperty(Mo,"__esModule",{value:!0});Mo.resolveSchema=Mo.getCompilingSchema=Mo.resolveRef=Mo.compileSchema=Mo.SchemaEnv=void 0;var Sa=vt(),$Q=Mb(),cf=$o(),Ea=xg(),g4=$t(),OQ=kg(),Ph=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,Ea.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Mo.SchemaEnv=Ph;function W_(t){let e=w4.call(this,t);if(e)return e;let r=(0,Ea.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:a}=this.opts,o=new Sa.CodeGen(this.scope,{es5:n,lines:s,ownProperties:a}),i;t.$async&&(i=o.scopeValue("Error",{ref:$Q.default,code:(0,Sa._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");t.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:cf.default.data,parentData:cf.default.parentData,parentDataProperty:cf.default.parentDataProperty,dataNames:[cf.default.data],dataPathArr:[Sa.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Sa.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Sa.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Sa._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,OQ.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let l=o.toString();d=`${o.scopeRefs(cf.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${cf.default.self}`,`${cf.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 Sa.Name?void 0:p,items:m instanceof Sa.Name?void 0:m,dynamicProps:p instanceof Sa.Name,dynamicItems:m instanceof Sa.Name},h.source&&(h.source.evaluated=(0,Sa.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)}}Mo.compileSchema=W_;function MQ(t,e,r){var n;r=(0,Ea.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let a=UQ.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 Ph({schema:o,schemaId:i,root:t,baseId:e}))}if(a!==void 0)return t.refs[r]=BQ.call(this,a)}Mo.resolveRef=MQ;function BQ(t){return(0,Ea.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:W_.call(this,t)}function w4(t){for(let e of this._compilations)if(NQ(e,t))return e}Mo.getCompilingSchema=w4;function NQ(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function UQ(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,Ea._getFullPath)(this.opts.uriResolver,r),s=(0,Ea.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return G_.call(this,r,t);let a=(0,Ea.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:G_.call(this,r,i)}if(typeof o?.schema=="object"){if(o.validate||W_.call(this,o),a===(0,Ea.normalizeId)(e)){let{schema:i}=o,{schemaId:c}=this.opts,u=i[c];return u&&(s=(0,Ea.resolveUrl)(this.opts.uriResolver,s,u)),new Ph({schema:i,schemaId:c,root:t,baseId:s})}return G_.call(this,r,o)}}Mo.resolveSchema=Bb;var LQ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function G_(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,g4.unescapeFragment)(i)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!LQ.has(i)&&u&&(e=(0,Ea.resolveUrl)(this.opts.uriResolver,e,u))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,g4.schemaHasRulesButRef)(r,this.RULES)){let i=(0,Ea.resolveUrl)(this.opts.uriResolver,e,r.$ref);a=Bb.call(this,n,i)}let{schemaId:o}=this.opts;if(a=a||new Ph({schema:r,schemaId:o,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var v4=xe((iDe,KQ)=>{KQ.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 H_=xe((oDe,S4)=>{"use strict";v();var zQ=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),P4=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 V_(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 qQ=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function b4(t){return t.length=0,!0}function FQ(t,e,r){if(t.length){let n=V_(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function GQ(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],a=!1,o=!1,i=FQ;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=b4}else{s.push(u);continue}}return s.length&&(i===b4?r.zone=s.join(""):o?n.push(s.join("")):n.push(V_(s))),r.address=n.join(""),r}function x4(t){if(WQ(t,":")<2)return{host:t,isIPV6:!1};let e=GQ(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 WQ(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function VQ(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 HQ(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 JQ(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!P4(r)){let n=x4(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}S4.exports={nonSimpleDomain:qQ,recomposeAuthority:JQ,normalizeComponentEncoding:HQ,removeDotSegments:VQ,isIPv4:P4,isUUID:zQ,normalizeIPv6:x4,stringArrayToHexStripped:V_}});var I4=xe((cDe,T4)=>{"use strict";v();var{isUUID:ZQ}=H_(),YQ=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,QQ=["http","https","ws","wss","urn","urn:uuid"];function XQ(t){return QQ.indexOf(t)!==-1}function J_(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 E4(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function k4(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 eX(t){return t.secure=J_(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function tX(t){if((t.port===(J_(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 rX(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(YQ);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=Z_(s);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function nX(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=Z_(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 sX(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!ZQ(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function iX(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var _4={scheme:"http",domainHost:!0,parse:E4,serialize:k4},oX={scheme:"https",domainHost:_4.domainHost,parse:E4,serialize:k4},Nb={scheme:"ws",domainHost:!0,parse:eX,serialize:tX},aX={scheme:"wss",domainHost:Nb.domainHost,parse:Nb.parse,serialize:Nb.serialize},cX={scheme:"urn",parse:rX,serialize:nX,skipNormalize:!0},dX={scheme:"urn:uuid",parse:sX,serialize:iX,skipNormalize:!0},Ub={http:_4,https:oX,ws:Nb,wss:aX,urn:cX,"urn:uuid":dX};Object.setPrototypeOf(Ub,null);function Z_(t){return t&&(Ub[t]||Ub[t.toLowerCase()])||void 0}T4.exports={wsIsSecure:J_,SCHEMES:Ub,isValidSchemeName:XQ,getSchemeHandler:Z_}});var D4=xe((uDe,Kb)=>{"use strict";v();var{normalizeIPv6:uX,removeDotSegments:Ig,recomposeAuthority:lX,normalizeComponentEncoding:Lb,isIPv4:fX,nonSimpleDomain:pX}=H_(),{SCHEMES:hX,getSchemeHandler:A4}=I4();function mX(t,e){return typeof t=="string"?t=fc(ud(t,e),e):typeof t=="object"&&(t=ud(fc(t,e),e)),t}function yX(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=R4(ud(t,n),ud(e,n),n,!0);return n.skipEscape=!0,fc(s,n)}function R4(t,e,r,n){let s={};return n||(t=ud(fc(t,r),r),e=ud(fc(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=Ig(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=Ig(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ig(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=Ig(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 gX(t,e,r){return typeof t=="string"?(t=unescape(t),t=fc(Lb(ud(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=fc(Lb(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=fc(Lb(ud(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=fc(Lb(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function fc(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=A4(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=lX(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=Ig(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 wX=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ud(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(wX);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(fX(n.host)===!1){let c=uX(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=A4(r.scheme||n.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(r.domainHost||o&&o.domainHost)&&s===!1&&pX(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 Y_={SCHEMES:hX,normalize:mX,resolve:yX,resolveComponent:R4,equal:gX,serialize:fc,parse:ud};Kb.exports=Y_;Kb.exports.default=Y_;Kb.exports.fastUri=Y_});var j4=xe(Q_=>{"use strict";v();Object.defineProperty(Q_,"__esModule",{value:!0});var C4=D4();C4.code='require("ajv/dist/runtime/uri").default';Q_.default=C4});var K4=xe(Ts=>{"use strict";v();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.CodeGen=Ts.Name=Ts.nil=Ts.stringify=Ts.str=Ts._=Ts.KeywordCxt=void 0;var vX=kg();Object.defineProperty(Ts,"KeywordCxt",{enumerable:!0,get:function(){return vX.KeywordCxt}});var xh=vt();Object.defineProperty(Ts,"_",{enumerable:!0,get:function(){return xh._}});Object.defineProperty(Ts,"str",{enumerable:!0,get:function(){return xh.str}});Object.defineProperty(Ts,"stringify",{enumerable:!0,get:function(){return xh.stringify}});Object.defineProperty(Ts,"nil",{enumerable:!0,get:function(){return xh.nil}});Object.defineProperty(Ts,"Name",{enumerable:!0,get:function(){return xh.Name}});Object.defineProperty(Ts,"CodeGen",{enumerable:!0,get:function(){return xh.CodeGen}});var bX=Mb(),N4=_g(),PX=T_(),Ag=Tg(),xX=vt(),Rg=xg(),zb=Pg(),eT=$t(),$4=v4(),SX=j4(),U4=(t,e)=>new RegExp(t,e);U4.code="new RegExp";var EX=["removeAdditional","useDefaults","coerceTypes"],kX=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_X={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."},TX={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},O4=200;function IX(t){var e,r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S,w,E,_,I,D,N,$,F;let z=t.strict,B=(e=t.code)===null||e===void 0?void 0:e.optimize,H=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:U4,R=(s=t.uriResolver)!==null&&s!==void 0?s:SX.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:H,regExp:X}:{optimize:H,regExp:X},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:O4,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:O4,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!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:(D=t.validateSchema)!==null&&D!==void 0?D:!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:R}}var Dg=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...IX(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new xX.ValueScope({scope:{},prefixes:kX,es5:r,lines:n}),this.logger=$X(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,PX.getRules)(),M4.call(this,_X,e,"NOT SUPPORTED"),M4.call(this,TX,e,"DEPRECATED","warn"),this._metaOpts=CX.call(this),e.formats&&RX.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&DX.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),AX.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=$4;n==="id"&&(s={...$4},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 N4.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,Rg.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=B4.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Ag.SchemaEnv({schema:{},schemaId:n});if(r=Ag.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=B4.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,Rg.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(MX.call(this,n,r),!r)return(0,eT.eachItem)(n,a=>X_.call(this,a)),this;NX.call(this,r);let s={...r,type:(0,zb.getJSONTypes)(r.type),schemaType:(0,zb.getJSONTypes)(r.schemaType)};return(0,eT.eachItem)(n,s.type.length===0?a=>X_.call(this,a,s):a=>s.type.forEach(o=>X_.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]=L4(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,Rg.normalizeId)(o||n);let u=Rg.getSchemaRefs.call(this,e,n);return c=new Ag.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):Ag.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{Ag.compileSchema.call(this,e)}finally{this.opts=r}}};Dg.ValidationError=bX.default;Dg.MissingRefError=N4.default;Ts.default=Dg;function M4(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 B4(t){return t=(0,Rg.normalizeId)(t),this.schemas[t]||this.refs[t]}function AX(){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 RX(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function DX(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 CX(){let t={...this.opts};for(let e of EX)delete t[e];return t}var jX={log(){},warn(){},error(){}};function $X(t){if(t===!1)return jX;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 OX=/^[a-z_$][a-z0-9_$:-]*$/i;function MX(t,e){let{RULES:r}=this;if((0,eT.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!OX.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 X_(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?BX.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 BX(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 NX(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=L4(e)),t.validateSchema=this.compile(e,!0))}var UX={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function L4(t){return{anyOf:[t,UX]}}});var z4=xe(tT=>{"use strict";v();Object.defineProperty(tT,"__esModule",{value:!0});var LX={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};tT.default=LX});var Gb=xe(df=>{"use strict";v();Object.defineProperty(df,"__esModule",{value:!0});df.callRef=df.getValidate=void 0;var KX=_g(),q4=Oo(),Mi=vt(),Sh=$o(),F4=Tg(),qb=$t(),zX={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=F4.resolveRef.call(c,u,s,r);if(d===void 0)throw new KX.default(n.opts.uriResolver,s,r);if(d instanceof F4.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,Mi._)`${p}.validate`,u,u.$async)}function f(p){let m=G4(t,p);Fb(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",i.code.source===!0?{ref:p,code:(0,Mi.stringify)(p)}:{ref:p}),y=e.name("valid"),S=t.subschema({schema:p,dataTypes:[],schemaPath:Mi.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function G4(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Mi._)`${r.scopeValue("wrapper",{ref:e})}.validate`}df.getValidate=G4;function Fb(t,e,r,n){let{gen:s,it:a}=t,{allErrors:o,schemaEnv:i,opts:c}=a,u=c.passContext?Sh.default.this:Mi.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,Mi._)`await ${(0,q4.callValidateCode)(t,e,u)}`),h(e),o||s.assign(p,!0)},m=>{s.if((0,Mi._)`!(${m} instanceof ${a.ValidationError})`,()=>s.throw(m)),f(m),o||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,q4.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,Mi._)`${p}.errors`;s.assign(Sh.default.vErrors,(0,Mi._)`${Sh.default.vErrors} === null ? ${m} : ${Sh.default.vErrors}.concat(${m})`),s.assign(Sh.default.errors,(0,Mi._)`${Sh.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,Mi._)`${p}.evaluated.props`);a.props=qb.mergeEvaluated.props(s,S,a.props,Mi.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,Mi._)`${p}.evaluated.items`);a.items=qb.mergeEvaluated.items(s,S,a.items,Mi.Name)}}}df.callRef=Fb;df.default=zX});var W4=xe(rT=>{"use strict";v();Object.defineProperty(rT,"__esModule",{value:!0});var qX=z4(),FX=Gb(),GX=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qX.default,FX.default];rT.default=GX});var V4=xe(nT=>{"use strict";v();Object.defineProperty(nT,"__esModule",{value:!0});var Wb=vt(),_u=Wb.operators,Vb={maximum:{okStr:"<=",ok:_u.LTE,fail:_u.GT},minimum:{okStr:">=",ok:_u.GTE,fail:_u.LT},exclusiveMaximum:{okStr:"<",ok:_u.LT,fail:_u.GTE},exclusiveMinimum:{okStr:">",ok:_u.GT,fail:_u.LTE}},WX={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}}`},VX={keyword:Object.keys(Vb),type:"number",schemaType:"number",$data:!0,error:WX,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Wb._)`${r} ${Vb[e].fail} ${n} || isNaN(${r})`)}};nT.default=VX});var H4=xe(sT=>{"use strict";v();Object.defineProperty(sT,"__esModule",{value:!0});var Cg=vt(),HX={message:({schemaCode:t})=>(0,Cg.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Cg._)`{multipleOf: ${t}}`},JX={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:HX,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,a=s.opts.multipleOfPrecision,o=e.let("res"),i=a?(0,Cg._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,Cg._)`${o} !== parseInt(${o})`;t.fail$data((0,Cg._)`(${n} === 0 || (${o} = ${r}/${n}, ${i}))`)}};sT.default=JX});var J4=xe(iT=>{"use strict";v();Object.defineProperty(iT,"__esModule",{value:!0});var uf=vt(),ZX=$t(),YX=a2(),QX={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,uf.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,uf._)`{limit: ${t}}`},XX={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QX,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,a=e==="maxLength"?uf.operators.GT:uf.operators.LT,o=s.opts.unicode===!1?(0,uf._)`${r}.length`:(0,uf._)`${(0,ZX.useFunc)(t.gen,YX.default)}(${r})`;t.fail$data((0,uf._)`${o} ${a} ${n}`)}};iT.default=XX});var Z4=xe(oT=>{"use strict";v();Object.defineProperty(oT,"__esModule",{value:!0});var eee=Oo(),tee=$t(),Eh=vt(),ree={message:({schemaCode:t})=>(0,Eh.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Eh._)`{pattern: ${t}}`},nee={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ree,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,Eh._)`new RegExp`:(0,tee.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Eh._)`${u}(${a}, ${i}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Eh._)`!${d}`)}else{let c=(0,eee.usePattern)(t,s);t.fail$data((0,Eh._)`!${c}.test(${r})`)}}};oT.default=nee});var Y4=xe(aT=>{"use strict";v();Object.defineProperty(aT,"__esModule",{value:!0});var jg=vt(),see={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,jg.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,jg._)`{limit: ${t}}`},iee={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:see,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?jg.operators.GT:jg.operators.LT;t.fail$data((0,jg._)`Object.keys(${r}).length ${s} ${n}`)}};aT.default=iee});var Q4=xe(cT=>{"use strict";v();Object.defineProperty(cT,"__esModule",{value:!0});var $g=Oo(),Og=vt(),oee=$t(),aee={message:({params:{missingProperty:t}})=>(0,Og.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Og._)`{missingProperty: ${t}}`},cee={keyword:"required",type:"object",schemaType:"array",$data:!0,error:aee,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,oee.checkStrictMode)(o,S,o.opts.strictRequired)}}function u(){if(c||a)t.block$data(Og.nil,l);else for(let h of r)(0,$g.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,$g.checkMissingProp)(t,r,h)),(0,$g.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,$g.noPropertyInData)(e,s,h,i.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,$g.propertyInData)(e,s,h,i.ownProperties)),e.if((0,Og.not)(p),()=>{t.error(),e.break()})},Og.nil)}}};cT.default=cee});var X4=xe(dT=>{"use strict";v();Object.defineProperty(dT,"__esModule",{value:!0});var Mg=vt(),dee={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Mg.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Mg._)`{limit: ${t}}`},uee={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dee,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Mg.operators.GT:Mg.operators.LT;t.fail$data((0,Mg._)`${r}.length ${s} ${n}`)}};dT.default=uee});var Hb=xe(uT=>{"use strict";v();Object.defineProperty(uT,"__esModule",{value:!0});var eB=O_();eB.code='require("ajv/dist/runtime/equal").default';uT.default=eB});var tB=xe(fT=>{"use strict";v();Object.defineProperty(fT,"__esModule",{value:!0});var lT=Pg(),Is=vt(),lee=$t(),fee=Hb(),pee={message:({params:{i:t,j:e}})=>(0,Is.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Is._)`{i: ${t}, j: ${e}}`},hee={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:pee,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,lT.getSchemaTypes)(a.items):[];t.block$data(c,d,(0,Is._)`${o} === false`),t.ok(c);function d(){let p=e.let("i",(0,Is._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,Is._)`${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,lT.checkDataTypes)(u,y,i.opts.strictNumbers,lT.DataType.Wrong),w=e.const("indices",(0,Is._)`{}`);e.for((0,Is._)`;${p}--;`,()=>{e.let(y,(0,Is._)`${r}[${p}]`),e.if(S,(0,Is._)`continue`),u.length>1&&e.if((0,Is._)`typeof ${y} == "string"`,(0,Is._)`${y} += "_"`),e.if((0,Is._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Is._)`${w}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Is._)`${w}[${y}] = ${p}`)})}function h(p,m){let y=(0,lee.useFunc)(e,fee.default),S=e.name("outer");e.label(S).for((0,Is._)`;${p}--;`,()=>e.for((0,Is._)`${m} = ${p}; ${m}--;`,()=>e.if((0,Is._)`${y}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};fT.default=hee});var rB=xe(hT=>{"use strict";v();Object.defineProperty(hT,"__esModule",{value:!0});var pT=vt(),mee=$t(),yee=Hb(),gee={message:"must be equal to constant",params:({schemaCode:t})=>(0,pT._)`{allowedValue: ${t}}`},wee={keyword:"const",$data:!0,error:gee,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:a}=t;n||a&&typeof a=="object"?t.fail$data((0,pT._)`!${(0,mee.useFunc)(e,yee.default)}(${r}, ${s})`):t.fail((0,pT._)`${a} !== ${r}`)}};hT.default=wee});var nB=xe(mT=>{"use strict";v();Object.defineProperty(mT,"__esModule",{value:!0});var Bg=vt(),vee=$t(),bee=Hb(),Pee={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Bg._)`{allowedValues: ${t}}`},xee={keyword:"enum",schemaType:"array",$data:!0,error:Pee,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,vee.useFunc)(e,bee.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,Bg.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,Bg._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function f(h,p){let m=s[p];return typeof m=="object"&&m!==null?(0,Bg._)`${u()}(${r}, ${h}[${p}])`:(0,Bg._)`${r} === ${m}`}}};mT.default=xee});var sB=xe(yT=>{"use strict";v();Object.defineProperty(yT,"__esModule",{value:!0});var See=V4(),Eee=H4(),kee=J4(),_ee=Z4(),Tee=Y4(),Iee=Q4(),Aee=X4(),Ree=tB(),Dee=rB(),Cee=nB(),jee=[See.default,Eee.default,kee.default,_ee.default,Tee.default,Iee.default,Aee.default,Ree.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Dee.default,Cee.default];yT.default=jee});var wT=xe(Ng=>{"use strict";v();Object.defineProperty(Ng,"__esModule",{value:!0});Ng.validateAdditionalItems=void 0;var lf=vt(),gT=$t(),$ee={message:({params:{len:t}})=>(0,lf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,lf._)`{limit: ${t}}`},Oee={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:$ee,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,gT.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}iB(t,n)}};function iB(t,e){let{gen:r,schema:n,data:s,keyword:a,it:o}=t;o.items=!0;let i=r.const("len",(0,lf._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,lf._)`${i} <= ${e.length}`);else if(typeof n=="object"&&!(0,gT.alwaysValidSchema)(o,n)){let u=r.var("valid",(0,lf._)`${i} <= ${e.length}`);r.if((0,lf.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,i,d=>{t.subschema({keyword:a,dataProp:d,dataPropType:gT.Type.Num},u),o.allErrors||r.if((0,lf.not)(u),()=>r.break())})}}Ng.validateAdditionalItems=iB;Ng.default=Oee});var vT=xe(Ug=>{"use strict";v();Object.defineProperty(Ug,"__esModule",{value:!0});Ug.validateTuple=void 0;var oB=vt(),Jb=$t(),Mee=Oo(),Bee={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return aB(t,"additionalItems",e);r.items=!0,!(0,Jb.alwaysValidSchema)(r,e)&&t.ok((0,Mee.validateArray)(t))}};function aB(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,oB._)`${a}.length`);r.forEach((l,f)=>{(0,Jb.alwaysValidSchema)(i,l)||(n.if((0,oB._)`${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)}}}Ug.validateTuple=aB;Ug.default=Bee});var cB=xe(bT=>{"use strict";v();Object.defineProperty(bT,"__esModule",{value:!0});var Nee=vT(),Uee={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Nee.validateTuple)(t,"items")};bT.default=Uee});var uB=xe(PT=>{"use strict";v();Object.defineProperty(PT,"__esModule",{value:!0});var dB=vt(),Lee=$t(),Kee=Oo(),zee=wT(),qee={message:({params:{len:t}})=>(0,dB.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,dB._)`{limit: ${t}}`},Fee={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qee,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Lee.alwaysValidSchema)(n,e)&&(s?(0,zee.validateAdditionalItems)(t,s):t.ok((0,Kee.validateArray)(t)))}};PT.default=Fee});var lB=xe(xT=>{"use strict";v();Object.defineProperty(xT,"__esModule",{value:!0});var Bo=vt(),Zb=$t(),Gee={message:({params:{min:t,max:e}})=>e===void 0?(0,Bo.str)`must contain at least ${t} valid item(s)`:(0,Bo.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Bo._)`{minContains: ${t}}`:(0,Bo._)`{minContains: ${t}, maxContains: ${e}}`},Wee={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Gee,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,Bo._)`${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,Bo._)`${d} >= ${o}`;i!==void 0&&(m=(0,Bo._)`${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,Bo._)`${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,Bo._)`${m}++`),i===void 0?e.if((0,Bo._)`${m} >= ${o}`,()=>e.assign(l,!0).break()):(e.if((0,Bo._)`${m} > ${i}`,()=>e.assign(l,!1).break()),o===1?e.assign(l,!0):e.if((0,Bo._)`${m} >= ${o}`,()=>e.assign(l,!0)))}}};xT.default=Wee});var Yb=xe(pc=>{"use strict";v();Object.defineProperty(pc,"__esModule",{value:!0});pc.validateSchemaDeps=pc.validatePropertyDeps=pc.error=void 0;var ST=vt(),Vee=$t(),Lg=Oo();pc.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ST.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ST._)`{property: ${t},
|
|
8
8
|
missingProperty: ${n},
|
|
9
9
|
depsCount: ${e},
|
|
10
|
-
deps: ${r}}`};var Hee={keyword:"dependencies",type:"object",schemaType:"object",error:pc.error,code(t){let[e,r]=Jee(t);fB(t,e),pB(t,r)}};function Jee({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 fB(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,Lg.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,Lg.checkReportMissingProp)(t,u)}):(r.if((0,ST._)`${c} && (${(0,Lg.checkMissingProp)(t,i,a)})`),(0,Lg.reportMissingProp)(t,a),r.else())}}pc.validatePropertyDeps=fB;function pB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Vee.alwaysValidSchema)(a,e[i])||(r.if((0,Lg.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))}pc.validateSchemaDeps=pB;pc.default=Hee});var mB=xe(ET=>{"use strict";v();Object.defineProperty(ET,"__esModule",{value:!0});var hB=vt(),Zee=$t(),Yee={message:"property name must be valid",params:({params:t})=>(0,hB._)`{propertyName: ${t.propertyName}}`},Qee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Yee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Zee.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,hB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};ET.default=Qee});var _T=xe(kT=>{"use strict";v();Object.defineProperty(kT,"__esModule",{value:!0});var Qb=Oo(),ka=vt(),Xee=$o(),Xb=$t(),ete={message:"must NOT have additional properties",params:({params:t})=>(0,ka._)`{additionalProperty: ${t.additionalProperty}}`},tte={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ete,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,ka._)`${a} === ${Xee.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 w=(0,Xb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Qb.isOwnProperty)(e,w,y)}else u.length?S=(0,ka.or)(...u.map(w=>(0,ka._)`${y} === ${w}`)):S=ka.nil;return d.length&&(S=(0,ka.or)(S,...d.map(w=>(0,ka._)`${(0,Qb.usePattern)(t,w)}.test(${y})`))),(0,ka.not)(S)}function h(y){e.code((0,ka._)`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,ka.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,ka.not)(S),()=>e.break()))}}function m(y,S,w){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Xb.Type.Str};w===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};kT.default=tte});var wB=xe(IT=>{"use strict";v();Object.defineProperty(IT,"__esModule",{value:!0});var rte=kg(),yB=Oo(),TT=$t(),gB=_T(),nte={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&&gB.default.code(new rte.KeywordCxt(a,gB.default,"additionalProperties"));let o=(0,yB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=TT.mergeEvaluated.props(e,(0,TT.toHash)(o),a.props));let i=o.filter(l=>!(0,TT.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,yB.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)}}};IT.default=nte});var xB=xe(AT=>{"use strict";v();Object.defineProperty(AT,"__esModule",{value:!0});var vB=Oo(),e1=vt(),bB=$t(),PB=$t(),ste={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,vB.allSchemaProperties)(r),c=i.filter(m=>(0,bB.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,PB.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,bB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,e1._)`${(0,vB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:PB.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())})})}}};AT.default=ste});var SB=xe(RT=>{"use strict";v();Object.defineProperty(RT,"__esModule",{value:!0});var ite=$t(),ote={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,ite.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"}};RT.default=ote});var EB=xe(DT=>{"use strict";v();Object.defineProperty(DT,"__esModule",{value:!0});var ate=Oo(),cte={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ate.validateUnion,error:{message:"must match a schema in anyOf"}};DT.default=cte});var kB=xe(CT=>{"use strict";v();Object.defineProperty(CT,"__esModule",{value:!0});var t1=vt(),dte=$t(),ute={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},lte={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ute,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,dte.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)})})}}};CT.default=lte});var _B=xe(jT=>{"use strict";v();Object.defineProperty(jT,"__esModule",{value:!0});var fte=$t(),pte={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,fte.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};jT.default=pte});var AB=xe($T=>{"use strict";v();Object.defineProperty($T,"__esModule",{value:!0});var r1=vt(),IB=$t(),hte={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},mte={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:hte,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,IB.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=TB(n,"then"),a=TB(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 TB(t,e){let r=t.schema[e];return r!==void 0&&!(0,IB.alwaysValidSchema)(t,r)}$T.default=mte});var RB=xe(OT=>{"use strict";v();Object.defineProperty(OT,"__esModule",{value:!0});var yte=$t(),gte={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,yte.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};OT.default=gte});var DB=xe(MT=>{"use strict";v();Object.defineProperty(MT,"__esModule",{value:!0});var wte=wT(),vte=cB(),bte=vT(),Pte=uB(),xte=lB(),Ste=Yb(),Ete=mB(),kte=_T(),_te=wB(),Tte=xB(),Ite=SB(),Ate=EB(),Rte=kB(),Dte=_B(),Cte=AB(),jte=RB();function $te(t=!1){let e=[Ite.default,Ate.default,Rte.default,Dte.default,Cte.default,jte.default,Ete.default,kte.default,Ste.default,_te.default,Tte.default];return t?e.push(vte.default,Pte.default):e.push(wte.default,bte.default),e.push(xte.default),e}MT.default=$te});var NT=xe(Kg=>{"use strict";v();Object.defineProperty(Kg,"__esModule",{value:!0});Kg.dynamicAnchor=void 0;var BT=vt(),Ote=$o(),CB=Tg(),Mte=Gb(),Bte={keyword:"$dynamicAnchor",schemaType:"string",code:t=>jB(t,t.schema)};function jB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,BT._)`${Ote.default.dynamicAnchors}${(0,BT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Nte(t);r.if((0,BT._)`!${s}`,()=>r.assign(s,a))}Kg.dynamicAnchor=jB;function Nte(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 CB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return CB.compileSchema.call(n,u),(0,Mte.getValidate)(t,u)}Kg.default=Bte});var UT=xe(zg=>{"use strict";v();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicRef=void 0;var $B=vt(),Ute=$o(),OB=Gb(),Lte={keyword:"$dynamicRef",schemaType:"string",code:t=>MB(t,t.schema)};function MB(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,$B._)`${Ute.default.dynamicAnchors}${(0,$B.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,OB.callRef)(t,c),r.let(u,!0)}):()=>(0,OB.callRef)(t,c)}}zg.dynamicRef=MB;zg.default=Lte});var BB=xe(LT=>{"use strict";v();Object.defineProperty(LT,"__esModule",{value:!0});var Kte=NT(),zte=$t(),qte={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,Kte.dynamicAnchor)(t,""):(0,zte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};LT.default=qte});var NB=xe(KT=>{"use strict";v();Object.defineProperty(KT,"__esModule",{value:!0});var Fte=UT(),Gte={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Fte.dynamicRef)(t,t.schema)};KT.default=Gte});var UB=xe(zT=>{"use strict";v();Object.defineProperty(zT,"__esModule",{value:!0});var Wte=NT(),Vte=UT(),Hte=BB(),Jte=NB(),Zte=[Wte.default,Vte.default,Hte.default,Jte.default];zT.default=Zte});var KB=xe(qT=>{"use strict";v();Object.defineProperty(qT,"__esModule",{value:!0});var LB=Yb(),Yte={keyword:"dependentRequired",type:"object",schemaType:"object",error:LB.error,code:t=>(0,LB.validatePropertyDeps)(t)};qT.default=Yte});var zB=xe(FT=>{"use strict";v();Object.defineProperty(FT,"__esModule",{value:!0});var Qte=Yb(),Xte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Qte.validateSchemaDeps)(t)};FT.default=Xte});var qB=xe(GT=>{"use strict";v();Object.defineProperty(GT,"__esModule",{value:!0});var ere=$t(),tre={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,ere.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};GT.default=tre});var FB=xe(WT=>{"use strict";v();Object.defineProperty(WT,"__esModule",{value:!0});var rre=KB(),nre=zB(),sre=qB(),ire=[rre.default,nre.default,sre.default];WT.default=ire});var WB=xe(VT=>{"use strict";v();Object.defineProperty(VT,"__esModule",{value:!0});var Tu=vt(),GB=$t(),ore=$o(),are={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Tu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},cre={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:are,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 Tu.Name?e.if((0,Tu._)`${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,Tu._)`${s} === ${ore.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,GB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:GB.Type.Str},f),o||e.if((0,Tu.not)(f),()=>e.break())}}function u(l,f){return(0,Tu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Tu._)`${f} !== ${p}`);return(0,Tu.and)(...h)}}};VT.default=cre});var HB=xe(HT=>{"use strict";v();Object.defineProperty(HT,"__esModule",{value:!0});var ff=vt(),VB=$t(),dre={message:({params:{len:t}})=>(0,ff.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ff._)`{limit: ${t}}`},ure={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:dre,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,ff._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,ff._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,VB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,ff._)`${o} <= ${a}`);e.if((0,ff.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:VB.Type.Num},c),s.allErrors||e.if((0,ff.not)(c),()=>e.break())})}}};HT.default=ure});var JB=xe(JT=>{"use strict";v();Object.defineProperty(JT,"__esModule",{value:!0});var lre=WB(),fre=HB(),pre=[lre.default,fre.default];JT.default=pre});var ZB=xe(ZT=>{"use strict";v();Object.defineProperty(ZT,"__esModule",{value:!0});var An=vt(),hre={message:({schemaCode:t})=>(0,An.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,An._)`{format: ${t}}`},mre={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hre,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)(w(),E()));function w(){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){w();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(_());function w(){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 D=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:D});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})`}}}};ZT.default=mre});var YB=xe(YT=>{"use strict";v();Object.defineProperty(YT,"__esModule",{value:!0});var yre=ZB(),gre=[yre.default];YT.default=gre});var QB=xe(kh=>{"use strict";v();Object.defineProperty(kh,"__esModule",{value:!0});kh.contentVocabulary=kh.metadataVocabulary=void 0;kh.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kh.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var eN=xe(QT=>{"use strict";v();Object.defineProperty(QT,"__esModule",{value:!0});var wre=W4(),vre=sB(),bre=DB(),Pre=UB(),xre=FB(),Sre=JB(),Ere=YB(),XB=QB(),kre=[Pre.default,wre.default,vre.default,(0,bre.default)(!0),Ere.default,XB.metadataVocabulary,XB.contentVocabulary,xre.default,Sre.default];QT.default=kre});var rN=xe(n1=>{"use strict";v();Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var tN;(function(t){t.Tag="tag",t.Mapping="mapping"})(tN||(n1.DiscrError=tN={}))});var sN=xe(eI=>{"use strict";v();Object.defineProperty(eI,"__esModule",{value:!0});var _h=vt(),XT=rN(),nN=Tg(),_re=_g(),Tre=$t(),Ire={message:({params:{discrError:t,tagName:e}})=>t===XT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,_h._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Are={keyword:"discriminator",type:"object",schemaType:"object",error:Ire,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,_h._)`${r}${(0,_h.getProperty)(i)}`);e.if((0,_h._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:XT.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,_h._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:XT.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,_h.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,Tre.schemaHasRulesButRef)(I,a.self.RULES)){let N=I.$ref;if(I=nN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),I instanceof nN.SchemaEnv&&(I=I.schema),I===void 0)throw new _re.default(a.opts.uriResolver,a.baseId,N)}let D=(h=I?.properties)===null||h===void 0?void 0:h[i];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(I)),w(D,_)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:_}){return Array.isArray(_)&&_.includes(i)}function w(_,I){if(_.const)E(_.const,I);else if(_.enum)for(let D of _.enum)E(D,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}}}};eI.default=Are});var iN=xe((c5e,Rre)=>{Rre.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 oN=xe((d5e,Dre)=>{Dre.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 aN=xe((u5e,Cre)=>{Cre.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 cN=xe((l5e,jre)=>{jre.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 dN=xe((f5e,$re)=>{$re.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 uN=xe((p5e,Ore)=>{Ore.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 lN=xe((h5e,Mre)=>{Mre.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 fN=xe((m5e,Bre)=>{Bre.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 pN=xe(tI=>{"use strict";v();Object.defineProperty(tI,"__esModule",{value:!0});var Nre=iN(),Ure=oN(),Lre=aN(),Kre=cN(),zre=dN(),qre=uN(),Fre=lN(),Gre=fN(),Wre=["/properties"];function Vre(t){return[Nre,Ure,Lre,Kre,zre,e(this,qre),Fre,e(this,Gre)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Wre):n}}tI.default=Vre});var sI=xe((Vr,nI)=>{"use strict";v();Object.defineProperty(Vr,"__esModule",{value:!0});Vr.MissingRefError=Vr.ValidationError=Vr.CodeGen=Vr.Name=Vr.nil=Vr.stringify=Vr.str=Vr._=Vr.KeywordCxt=Vr.Ajv2020=void 0;var Hre=K4(),Jre=eN(),Zre=sN(),Yre=pN(),rI="https://json-schema.org/draft/2020-12/schema",Th=class extends Hre.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Jre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Zre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(Yre.default.call(this,e),this.refs["http://json-schema.org/schema"]=rI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rI)?rI:void 0)}};Vr.Ajv2020=Th;nI.exports=Vr=Th;nI.exports.Ajv2020=Th;Object.defineProperty(Vr,"__esModule",{value:!0});Vr.default=Th;var Qre=kg();Object.defineProperty(Vr,"KeywordCxt",{enumerable:!0,get:function(){return Qre.KeywordCxt}});var Ih=vt();Object.defineProperty(Vr,"_",{enumerable:!0,get:function(){return Ih._}});Object.defineProperty(Vr,"str",{enumerable:!0,get:function(){return Ih.str}});Object.defineProperty(Vr,"stringify",{enumerable:!0,get:function(){return Ih.stringify}});Object.defineProperty(Vr,"nil",{enumerable:!0,get:function(){return Ih.nil}});Object.defineProperty(Vr,"Name",{enumerable:!0,get:function(){return Ih.Name}});Object.defineProperty(Vr,"CodeGen",{enumerable:!0,get:function(){return Ih.CodeGen}});var Xre=Mb();Object.defineProperty(Vr,"ValidationError",{enumerable:!0,get:function(){return Xre.default}});var ene=_g();Object.defineProperty(Vr,"MissingRefError",{enumerable:!0,get:function(){return ene.default}})});var I9=xe((x4e,_A)=>{"use strict";v();var gue=Object.prototype.hasOwnProperty,Ei="~";function Mw(){}Object.create&&(Mw.prototype=Object.create(null),new Mw().__proto__||(Ei=!1));function wue(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function T9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new wue(r,n||t,s),o=Ei?Ei+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 vP(t,e){--t._eventsCount===0?t._events=new Mw:delete t._events[e]}function ei(){this._events=new Mw,this._eventsCount=0}ei.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)gue.call(r,n)&&e.push(Ei?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ei.prototype.listeners=function(e){var r=Ei?Ei+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};ei.prototype.listenerCount=function(e){var r=Ei?Ei+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ei.prototype.emit=function(e,r,n,s,a,o){var i=Ei?Ei+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};ei.prototype.on=function(e,r,n){return T9(this,e,r,n,!1)};ei.prototype.once=function(e,r,n){return T9(this,e,r,n,!0)};ei.prototype.removeListener=function(e,r,n,s){var a=Ei?Ei+e:e;if(!this._events[a])return this;if(!r)return vP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&vP(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:vP(this,a)}return this};ei.prototype.removeAllListeners=function(e){var r;return e?(r=Ei?Ei+e:e,this._events[r]&&vP(this,r)):(this._events=new Mw,this._eventsCount=0),this};ei.prototype.off=ei.prototype.removeListener;ei.prototype.addListener=ei.prototype.on;ei.prefixed=Ei;ei.EventEmitter=ei;typeof _A<"u"&&(_A.exports=ei)});v();v();var cm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(cm||{});v();v();pn();Ba();v();v();var Cm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,L6=new Set,s2=typeof process=="object"&&process?process:{},K6=(t,e,r,n)=>{typeof s2.emitWarning=="function"?s2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},T0=globalThis.AbortController,U6=globalThis.AbortSignal;if(typeof T0>"u"){U6=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},T0=class{constructor(){e()}signal=new U6;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=s2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,K6("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 BF=t=>!L6.has(t),hme=Symbol("type"),Ld=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),z6=t=>Ld(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?hp:null:null,hp=class extends Array{constructor(e){super(e),this.fill(0)}},i2=class t{heap;length;static#c=!1;static create(e){let r=z6(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]}},I0=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:w,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:_,ignoreFetchAbort:I}=e;if(r!==0&&!Ld(r))throw new TypeError("max option must be a nonnegative integer");let D=r?z6(r):Array;if(!D)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 D(r),this.#f=new D(r),this.#a=0,this.#i=0,this.#y=i2.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&&!Ld(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Ld(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Ld(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Ld(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";BF(N)&&(L6.add(N),K6("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 hp(this.#c),r=new hp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=Cm.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?Cm.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=Cm.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 hp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#O=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Ld(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Ld(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)=>{};#O=(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.#M(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.#M(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#M(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=Cm.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=Cm.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.#O(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 T0,{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,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!w&&!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,w=S||n.allowStaleOnFetchRejection,E=w||n.noDeleteOnFetchRejection,_=h;if(this.#e[r]===h&&(!E||_.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=_.__staleWhileFetching)),w)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(w=>m(w),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=w=>u(w,!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 T0}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:w}=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:w},_=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 D=this.#p(_);if(!y&&!D)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=D?"stale":"refresh",F&&D&&(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 A0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new I0({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)}};C0();ut();var zd=class t{static _singleton;cache;constructor(e){this.cache=e||new A0(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=_e.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new re("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new re("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 pt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=pt.extractDid(i);if(a)n.push(l);else throw new re("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=pt.extractDid(e),{didDocument:s,didResolutionMetadata:a}=await r.resolve(n),{verificationMethod:o=[]}=s||{},i;for(let u of o)if(e.endsWith(u.id)){i=u;break}if(!i)throw new re("GeneralJwsVerifierGetPublicKeyNotFound",t.buildPublicKeyNotFoundMessage(e,n,s,a,o));Lc("JwkVerificationMethod",i);let{publicKeyJwk:c}=i;return c}static buildPublicKeyNotFoundMessage(e,r,n,s,a){let o=s?.error;if(o!==void 0){let c=s?.errorMessage,u=c?`${o} \u2014 ${c}`:o;return`unable to resolve DID '${r}' to verify signature with kid '${e}': ${u}`}if(n==null)return`DID Document not found for '${r}' when verifying signature with kid '${e}'`;if(a.length===0)return`DID Document for '${r}' has no verification methods to verify signature with kid '${e}'`;let i=a.map(c=>c.id).join(", ");return`public key for kid '${e}' not found in DID Document for '${r}' (available verification methods: [${i}])`}};wi();ut();async function cn(t,e,r){if(t===void 0)throw new re("AuthenticateJwsMissing","Missing JWS.");if(await zd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await zd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await gt.parse(t.authorDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await gt.parse(t.ownerDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await zd.verifySignatures(r,e)}v();var ag=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}}};qE();v();var cg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Vc();v();v();Ba();sr();var Pn=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 ge.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=ge.getSigner(e),e.authorization.authorDelegatedGrant===void 0?this._author=this._signer:this._author=ge.getSigner(e.authorization.authorDelegatedGrant),this._signaturePayload=pt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var Hl=class t extends Pn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter)};Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};v();Al();sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var Jl=class t extends Pn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new re("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new re("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Vd();Kp();v();sr();v();function ot(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}v();Vd();pn();v();Jt();Ov();v();v();var Co=class{static maxDataSizeAllowedToBeEncoded=3e4};pn();ga();sr();fa();v();pn();sr();ut();var dg=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 re("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(ge.getSigner(e)===void 0)throw new re("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(_e.base64UrlToObject(e.encodedData).scope===void 0)throw new re("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=ge.getSigner(e);let r=e.encodedData,n=_e.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};Mn();wi();gi();C0();ut();Jt();Ao();var kr=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 re("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>Co.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>ge.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,...ke.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Ut.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return _e.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new re("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=_e.objectToBytes(n),o=await gt.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:_e.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 re("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=_e.objectToBytes(n),o=await gt.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:_e.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:li(e.grant.scope.protocol)});let a=_e.objectToBytes(r),o=await gt.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:_e.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=_e.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Lc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Lc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Lc("PermissionRevocationData",s);else throw new re("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 re("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Qr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new re("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?Qr.parse(n).scope:dg.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=li(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?.protocol===void 0)throw new re("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new re("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(Gn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new re("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};Mn();wi();ut();var gu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await ro.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 ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),kr.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new re("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 re("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=ke.isRecordsWrite(a)?a:await gt.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===kr.uri){let i=await kr.getScopeFromPermissionRecord(e,s,o);if(kr.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new re("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};v();Vc();sr();gi();ut();Jt();var Zl=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await ge.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 ge.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return ge.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Rr.parseCid(e)}catch{throw new re("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};Mn();ut();var bb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ot(o,400)}try{await cn(r.authorization,this.deps.didResolver)}catch(o){return ot(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 ot(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(ke.isRecordsWrite(s)){let o=a.message;if(o.encodedData===void 0){let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}else{let i=_e.base64UrlToBytes(o.encodedData);a.data=ns.fromBytes(i),delete o.encodedData}}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 kr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await gu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new re("MessagesReadAuthorizationFailed","protocol message failed authorization")}};v();sr();v();ga();Ao();Vt();var Pb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol===void 0?void 0:li(n.protocol),a={...n,protocol:s};Ot(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=Ut.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?Ut.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}};v();sr();Vt();gi();Ao();Jt();var Yl=class t extends Pn{static async parse(e){ge.validateJsonSchema(e),await ge.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&Gn(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};Ot(n);let{permissionGrantId:s,signer:a}=e,o=await ge.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return ge.validateJsonSchema(i),new t(i)}};ut();var xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ot(new re("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Yl.parse(r)}catch(u){return ot(u,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ot(u,401)}let{filters:a,cursor:o}=r.descriptor,i=Pb.convertFilters(a,this.deps.coreProtocols),c=await ge.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 re&&u.code==="EventLogProgressGap"){let d=u.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:d===void 0?void 0:{code:"ProgressGap",...d}}}return ot(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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("MessagesSubscribeAuthorizationFailed","message failed authorization")}};v();pn();vu();v();sr();Vt();gi();Ao();Jt();var lg=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),await ge.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&Gn(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};Ot(r);let{permissionGrantId:n,signer:s}=e,a=await ge.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return ge.validateJsonSchema(o),new t(o)}};ut();var AZ=Co.maxDataSizeAllowedToBeEncoded,Sb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await lg.parse(r)}catch(i){return ot(i,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ot(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.getRoot(e):await this.deps.stateIndex.getProtocolRoot(e,a);return{status:{code:200,detail:"OK"},root:Zn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a===void 0?await this.deps.stateIndex.getSubtreeHash(e,i):await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i);return{status:{code:200,detail:"OK"},hash:Zn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a===void 0?await this.deps.stateIndex.getLeaves(e,i):await this.deps.stateIndex.getProtocolLeaves(e,a,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 ot(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 w=t.parseBitPrefix(h),E=n===void 0?await o.getLeaves(e,w):await o.getProtocolLeaves(e,n,w);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n===void 0?await o.getLeaves(e,y):await o.getProtocolLeaves(e,n,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.getSubtreeHash(e,d):await s.getProtocolSubtreeHash(e,r,d),f=Zn(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(()=>(vu(),bM)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Zn(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<=AZ&&(c.encodedData=_e.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 re("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new re("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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("MessagesSyncAuthorizationFailed","message failed authorization")}};v();sr();v();var hN=Kn(sI(),1);sr();fa();v();Ov();ut();var Iu=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await ro.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 ro.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 re("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 re("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};gi();ut();Jt();v();Up();Kp();function Bi(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 pf(t){return t.includes(":")}function s1(t){return t.split("/").slice(-1)[0]}function ld(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 iI=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 Ha.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await wn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Ha.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ao();var fd=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await ge.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 ge.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),s={descriptor:r,authorization:n};return ge.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await Iu.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;Gn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Ya(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 re("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{Gn(e[s])}catch{throw new re("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new re("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 re("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 re("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 re("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 re("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(cm);if(!l.includes(d))throw new re("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new hN.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 re("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(pf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new re("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new re("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 re("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 re("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(pf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new re("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new re("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 re("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 re("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.role===f.role)throw new re("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.who===f.who&&d.of===f.of)throw new re("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} 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 re("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=Bi(s);if(a===void 0)throw new re("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n?.[a.alias]===void 0)throw new re("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 re("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=Bi(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new re(o,`cross-protocol '${s}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r?.[a.alias]===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new re(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=Dl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=li(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:li(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ut();Jt();var i1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fd.parse(r)}catch(d){return ot(d,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return ot(d,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(d){return ot(d,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await ge.getCid(r);for(let d of a)if(await ge.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let i=await ge.getNewestMessage(a),c=!1;(i===void 0||await ge.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 ge.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 ge.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 fd.parse(d),f=t.constructIndexes(l,!1),h=await ge.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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Iu.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("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 re("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=Bi(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new re("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 re("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 re("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=Bi(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new re("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);if(!ld(u.protocolPath,d.structure)?.$role)throw new re("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Bi(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new re("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(ld(u.protocolPath,d.structure)===void 0)throw new re("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)}}};v();ut();v();sr();Vt();gi();ut();Jt();Ao();var hf=class t extends Pn{static async parse(e){return e.authorization!==void 0&&await ge.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&Gn(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};Ot(r);let n;e.signer!==void 0&&(n=await ge.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return ge.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:li(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await kr.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Iu.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new re("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};Vt();Jt();var o1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hf.parse(r)}catch(o){return ot(o,400)}try{await cn(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 ot(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};Ot(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}};v();sr();v();Za();ut();Jt();v();ga();wi();ut();Jt();async function qg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(pf(c)){let p=Bi(c);if(p===void 0)throw new re("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses?.[p.alias]===void 0)throw new re("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);if(!ld(d,m.structure)?.$role)throw new re("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else if(!ld(c,s.structure)?.$role)throw new re("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 re("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Ut.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new re("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function nne(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await gt.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 gt.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Fg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await nne(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new re("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 sne(c,l,n,a))return}throw new re("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function sne(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(pf(s)&&n?.uses!==void 0){let o=Bi(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 gt.parse(a)).author;return t===o}}v();wi();ut();Jt();async function Ah(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 gt.getInitialWrite(s)}async function Gg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Ah(t,s,r);if(a===void 0)throw new re("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 oI(t,e,r){let n=await Ah(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}v();var mN=Kn(sI(),1);ga();Mn();ut();Jt();async function yN(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 re("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await ine(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 re("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new re("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new re("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new re("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function ine(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=Bi(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 gN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=s1(o),c=await one(t,o,r,n,s,a);ane(e,c,i)}async function one(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=Bi(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 ane(t,e,r){let n=r??s1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new re("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 re("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 re("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new re("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function wN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new re("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new re("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function vN(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 mN.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 re("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function bN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new re("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=ke.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Ut.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 re("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function PN(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=ke.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Ut.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new re("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 re("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function xN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new re("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 re("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function SN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new re("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Zs=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await oI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await gN(e,r.message,o,n,i,a),await yN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await bN(e,r,c,n),wN(r,c),vN(r,c),await SN(r,c),await xN(r,c),await PN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Ah(e,r.message.recordId,n),o;a===void 0?o=await Gg(e,r.message.descriptor.parentId,n):o=await Gg(e,r.message.recordId,n);let i=await oI(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 qg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Fg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Gg(e,n.message.recordId,s),i=await Ah(e,n.message.recordId,s),c=i===void 0?n.message.descriptor.messageTimestamp:i.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 qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(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 qg(e,r,a,i,c,n,d),await Fg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Gg(e,r.message.descriptor.recordId,s),i=await Ah(e,r.message.descriptor.recordId,s),c=i===void 0?n.message.descriptor.messageTimestamp:i.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 qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(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.isLatestBaseState=!0:o.messageTimestamp={lte:s};let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new re("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=ld(e,r.structure);if(n===void 0)throw new re("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};Mn();Jt();var a1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Hl.parse(r)}catch(a){return ot(a,400)}let s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ot(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={...ke.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 ke.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.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{...ke.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Jt();sr();Mn();v();sr();fa();Mn();Qa();Vt();gi();Jt();var pd=class t extends Pn{static async parse(e){let r;return e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.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 ge.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return ge.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 Ot(d),d}async authorizeDelegate(e,r){let n=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Qa();wi();v();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 pd.parse(r)}catch(u){return ot(u,400)}try{await cn(r.authorization,this.deps.didResolver)}catch(u){return ot(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await ge.getNewestMessage(a);if(!ke.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await ge.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await gt.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ot(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(ge.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 kr.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 Zs.authorizeDelete(e,r,n,s,a)}};v();Al();sr();Mn();wi();Za();Jt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(o){return ot(o,400)}let s,a;if(ke.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 cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ot(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 gt.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={...ke.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=[];ke.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(a)&&(ke.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Vd();pn();sr();Mn();Qa();v();Al();sr();fa();Mn();Qa();Vt();gi();ut();Jt();var Wg=class t extends Pn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new re("RecordsReadParseFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.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 re("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:ke.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};Ot(c);let u;n!==void 0&&(u=await ge.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return ge.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};wi();ut();Jt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Wg.parse(r)}catch(l){return ot(l,400)}try{n.author!==void 0&&await cn(r.authorization,this.deps.didResolver)}catch(l){return ot(l,401)}let s={interface:"Records",isLatestBaseState:!0,...ke.convertFilter(r.descriptor.filter)},a=ke.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 gt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ot(new re("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await gt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await gt.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ot(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await gt.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ot(l,401)}let u;if(c.encodedData===void 0){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}else{let l=_e.base64UrlToBytes(c.encodedData);u=ns.fromBytes(l),delete c.encodedData}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await gt.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){ge.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 kr.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 Zs.authorizeRead(e,r,n,s,a)}}};v();Al();sr();Mn();v();sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var mf=class t extends Pn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};wi();Za();ut();Jt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ot(new re("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await mf.parse(r)}catch(f){return ot(f,400)}let a=[],o=[];if(ke.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ot(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await ge.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 re&&f.code==="EventLogProgressGap"){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h===void 0?void 0:{code:"ProgressGap",...h}}}return ot(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 gt.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await u.close(),ot(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[{...ke.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...ke.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return ke.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({...ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Vc();Vd();pn();ga();sr();Mn();Qa();wi();Za();v();ga();sr();Mn();wi();Jt();var Rh=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 ge.getNewestMessage(s);if(!ke.canPerformDeleteAgainstRecord(r,a))return;let o=await pd.parse(r),i=await gt.getInitialWrite(s),c=o.constructIndexes(i),u=await ge.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=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Ut.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;ke.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f===void 0?u.set(l,[d]):f.push(d)}for(let[d,l]of u){if(d===r.recordId)continue;let f=await ge.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<=Co.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;ke.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 ge.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>ge.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 ge.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ge.getCid(c);if(await s.delete(e,d),await gt.isInitialWrite(c)){let p=await(await gt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await ge.getCid(c);i.push(f)}}await o.delete(e,i)}}};ut();Jt();var p1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await gt.parse(r),await Zs.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return ot(p,400)}try{await cn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(p){return ot(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 gt.getInitialWrite(o),gt.verifyEqualityOfImmutableProperties(c,r)}catch(p){return ot(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return ot(p,409)}let u=await ge.getNewestMessage(o),d=!1,l;if(u===void 0||await ge.isNewer(r,u)?(d=!0,l=r):l=u,!d){let p=!1;if(u!==void 0&&n!==void 0&&await gt.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?void 0:this.deps.coreProtocols?.get(r.descriptor.protocol);try{if(u?.descriptor.method==="Delete")throw new re("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){if(!i){let w=u;m=await this.processMessageWithoutDataStream(e,r,w),p=!0}}else m=await this.processMessageWithDataStream(e,r,n),p=!0;let y=await s.constructIndexes(p);await this.deps.messageStore.put(e,m,y);let S=await ge.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 re&&(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 ot(p,400);throw p}let h={status:i&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Rh.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=_e.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=Co.maxDataSizeAllowedToBeEncoded){let a=await ns.toBytes(n),o=await Rr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(r.descriptor.protocol);i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=ns.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Rr.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<=Co.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new re("RecordsWriteMissingEncodedDataInPrevious","No dataStream was provided and unable to get data from previous message");s.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new re("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 re("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new re("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 Zs.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?.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Ut.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 re("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 re("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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await kn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Zs.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};v();var dne=Object.create,BI=Object.defineProperty,une=Object.getOwnPropertyDescriptor,lne=Object.getOwnPropertyNames,fne=Object.getPrototypeOf,pne=Object.prototype.hasOwnProperty,Bt=(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})},hne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lne(e))!pne.call(t,s)&&s!==r&&BI(t,s,{get:()=>e[s],enumerable:!(n=une(e,s))||n.enumerable});return t},Rf=(t,e,r)=>(r=t!=null?dne(fne(t)):{},hne(e||!t||!t.__esModule?BI(r,"default",{value:t,enumerable:!0}):r,t)),mne=Bt((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 KU{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!==KU.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}),yne=Bt(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)})}}),kc=Bt((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)}}}),gne=Bt(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],w=y[1],E=new n(u(p,S,w)),_=0,I=w>0?S-4:S,D;for(D=0;D<I;D+=4)m=r[p.charCodeAt(D)]<<18|r[p.charCodeAt(D+1)]<<12|r[p.charCodeAt(D+2)]<<6|r[p.charCodeAt(D+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return w===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,E[_++]=m&255),w===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+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,w=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),w.push(l(S));return w.join("")}function h(p){for(var m,y=p.length,S=y%3,w=[],E=16383,_=0,I=y-S;_<I;_+=E)w.push(f(p,_,_+E>I?I:_+E));return S===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),wne=Bt(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=Bt(t=>{"use strict";var e=gne(),r=wne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=w,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(ze(T,ArrayBuffer)||T&&ze(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ze(T,SharedArrayBuffer)||T&&ze(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(ze(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"||Ft(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 w(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(ze(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),ze(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(ze(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)||ze(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 Ee(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return Tr(T).length;default:if(ae)return te?-1:Ee(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 R(this,M,L);case"ascii":return P(this,M,L);case"latin1":case"binary":return b(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?R(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(ze(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,be=L-M,Rt=Math.min(he,be),Ln=this.slice(te,ae),Or=T.slice(M,L);for(let lr=0;lr<Rt;++lr)if(Ln[lr]!==Or[lr]){he=Ln[lr],be=Or[lr];break}return he<be?-1:be<he?1:0};function D(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,Ft(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,be=T.length,Rt=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,be/=2,Rt/=2,L/=2}function Ln(lr,rr){return he===1?lr[rr]:lr.readUInt16BE(rr*he)}let Or;if(ae){let lr=-1;for(Or=L;Or<be;Or++)if(Ln(T,Or)===Ln(M,lr===-1?0:Or-lr)){if(lr===-1&&(lr=Or),Or-lr+1===Rt)return lr*he}else lr!==-1&&(Or-=Or-lr),lr=-1}else for(L+Rt>be&&(L=be-Rt),Or=L;Or>=0;Or--){let lr=!0;for(let rr=0;rr<Rt;rr++)if(Ln(T,Or+rr)!==Ln(M,rr)){lr=!1;break}if(lr)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 D(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return D(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 be;for(be=0;be<te;++be){let Rt=parseInt(M.substr(be*2,2),16);if(Ft(Rt))return be;T[L+be]=Rt}return be}function F(T,M,L,te){return ki(Ee(M,T.length-L),T,L,te)}function z(T,M,L,te){return ki(bt(M),T,L,te)}function B(T,M,L,te){return ki(Tr(M),T,L,te)}function H(T,M,L,te){return ki(Un(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 H(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 R(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],be=null,Rt=he>239?4:he>223?3:he>191?2:1;if(ae+Rt<=L){let Ln,Or,lr,rr;switch(Rt){case 1:he<128&&(be=he);break;case 2:Ln=T[ae+1],(Ln&192)===128&&(rr=(he&31)<<6|Ln&63,rr>127&&(be=rr));break;case 3:Ln=T[ae+1],Or=T[ae+2],(Ln&192)===128&&(Or&192)===128&&(rr=(he&15)<<12|(Ln&63)<<6|Or&63,rr>2047&&(rr<55296||rr>57343)&&(be=rr));break;case 4:Ln=T[ae+1],Or=T[ae+2],lr=T[ae+3],(Ln&192)===128&&(Or&192)===128&&(lr&192)===128&&(rr=(he&15)<<18|(Ln&63)<<12|(Or&63)<<6|lr&63,rr>65535&&rr<1114112&&(be=rr))}}be===null?(be=65533,Rt=1):be>65535&&(be-=65536,te.push(be>>>10&1023|55296),be=56320|be&1023),te.push(be),ae+=Rt}return x(te)}var j=4096;function x(T){let M=T.length;if(M<=j)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=j));return L}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]&127);return te}function b(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+=Ir[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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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 K(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 be=Math.pow(2,8*L)-1;K(this,T,M,L,be,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 be=Math.pow(2,8*L)-1;K(this,T,M,L,be,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||K(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||K(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||K(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||K(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||K(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){ce(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 be=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=be,be=be>>8,T[L++]=be,be=be>>8,T[L++]=be,be=be>>8,T[L++]=be,L}function V(T,M,L,te,ae){ce(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 be=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=be,be=be>>8,T[L+2]=be,be=be>>8,T[L+1]=be,be=be>>8,T[L]=be,L+8}i.prototype.writeBigUInt64LE=tr(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=tr(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 Rt=Math.pow(2,8*L-1);K(this,T,M,L,Rt-1,-Rt)}let ae=0,he=1,be=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&be===0&&this[M+ae-1]!==0&&(be=1),this[M+ae]=(T/he>>0)-be&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Rt=Math.pow(2,8*L-1);K(this,T,M,L,Rt-1,-Rt)}let ae=L-1,he=1,be=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&be===0&&this[M+ae+1]!==0&&(be=1),this[M+ae]=(T/he>>0)-be&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||K(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||K(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||K(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||K(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||K(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=tr(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=tr(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function W(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 J(T,M,L,te,ae){return M=+M,L=L>>>0,ae||W(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return J(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return J(this,T,M,!1,L)};function q(T,M,L,te,ae){return M=+M,L=L>>>0,ae||W(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return q(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return q(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),be=he.length;if(be===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%be]}return this};var Y={};function ne(T,M,L){Y[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}`}}}ne("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ne("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),ne("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=se(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=se(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function se(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){fe(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&ue(M,T.length-(L+1))}function ce(T,M,L,te,ae,he){if(T>L||T<M){let be=typeof M=="bigint"?"n":"",Rt;throw he>3?M===0||M===BigInt(0)?Rt=`>= 0${be} and < 2${be} ** ${(he+1)*8}${be}`:Rt=`>= -(2${be} ** ${(he+1)*8-1}${be}) and < 2 ** ${(he+1)*8-1}${be}`:Rt=`>= ${M}${be} and <= ${L}${be}`,new Y.ERR_OUT_OF_RANGE("value",Rt,T)}Z(te,ae,he)}function fe(T,M){if(typeof T!="number")throw new Y.ERR_INVALID_ARG_TYPE(M,"number",T)}function ue(T,M,L){throw Math.floor(T)!==T?(fe(T,L),new Y.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Y.ERR_BUFFER_OUT_OF_BOUNDS:new Y.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var Pe=/[^+/0-9A-Za-z-_]/g;function pe(T){if(T=T.split("=")[0],T=T.trim().replace(Pe,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Ee(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let be=0;be<te;++be){if(L=T.charCodeAt(be),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(be+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 bt(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Un(T,M){let L,te,ae,he=[];for(let be=0;be<T.length&&!((M-=2)<0);++be)L=T.charCodeAt(be),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function Tr(T){return e.toByteArray(pe(T))}function ki(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 ze(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function Ft(T){return T!==T}var Ir=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 tr(T){return typeof BigInt>"u"?At:T}function At(){throw new Error("BigInt not supported")}}),zU=Bt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),qU=Bt(t=>{"use strict";var e=kc(),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}),FU=Bt(t=>{"use strict";var{Buffer:e}=UI()||{},{Encoding:r}=qU(),n=zU(),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}),vne=Bt(t=>{"use strict";var{Buffer:e}=UI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=zU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=FU(),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"})}),bne=Bt(t=>{"use strict";var e=kc(),r=vne(),{Encoding:n}=qU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=FU(),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(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}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:w,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 '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,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,w=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new o({...y,name:w});case"buffer":return new s({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var h={binary:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),Pne=Bt((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,w,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,w=new Array(S-1);E<S;E++)w[E-1]=arguments[E];y.fn.apply(y.context,w)}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(!w)for(I=1,w=new Array(S-1);I<S;I++)w[I-1]=arguments[I];y[E].fn.apply(y[E].context,w)}}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)}),xne=Bt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),tP=Bt(t=>{"use strict";var e=xne();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=Bt(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:{}}}),Sf=Bt(t=>{"use strict";var{fromCallback:e}=tP(),r=kc(),{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"),w=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),I=Symbol("keys"),D=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),F=Object.freeze({}),z=()=>{},B=!1,H=class{constructor(P,b,k){if(typeof P!="object"||P===null){let A=P===null?"null":typeof P;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof b!="object"||b===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]=b[S],this[w]=b[w],this[_]=k,this[N]=Number.isInteger(b.limit)&&b.limit>=0?b.limit:1/0,this[$]=0,this[E]=!!b.abortOnClose,this.db=P,this.db.attachResource(this),this.nextTick=P.nextTick}get count(){return this[$]}get limit(){return this[N]}next(P){let b;if(P===void 0)b=new Promise((k,A)=>{P=(O,K,G)=>{O?A(O):this[_]?K===void 0&&G===void 0?k():k([K,G]):k(K)}});else if(typeof P!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(P,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),b}_next(P){this.nextTick(P)}nextv(P,b,k){return k=s(b,k),k=e(k,a),b=n(b,F),Number.isInteger(P)?(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"})):(P<1&&(P=1),this[N]<1/0&&(P=Math.min(P,this[N]-this[$])),this[i]=!0,this[o]=k,P<=0?this.nextTick(this[u],null,[]):this._nextv(P,b,this[u])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(P,b,k){let A=[],O=(K,G,V)=>{if(K)return k(K);if(this[_]?G===void 0&&V===void 0:G===void 0)return k(null,A);A.push(this[_]?[G,V]:G),A.length===P?k(null,A):this._next(O)};this._next(O)}all(P,b){return b=s(P,b),b=e(b,a),P=n(P,F),this[h]?this.nextTick(b,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(b,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=b,this[d]=!0,this[$]>=this[N]?this.nextTick(this[u],null,[]):this._all(P,this[u])),b[a]}_all(P,b){let k=this[$],A=[],O=()=>{let G=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;G<=0?this.nextTick(b,null,A):this._nextv(G,F,K)},K=(G,V)=>{G?b(G):V.length===0?b(null,A):(A.push.apply(A,V),k+=V.length,O())};O()}[l](){let P=this[o];return this[E]&&P===null?z:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),P)}[f](P,b,k){this[d]?this.close(P.bind(null,b,k)):P(b,k)}seek(P,b){if(b=n(b,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(b.keyEncoding||this[S]),A=k.format;b.keyEncoding!==A&&(b={...b,keyEncoding:A});let O=this.db.prefixKey(k.encode(P),A);this._seek(O,b)}}}_seek(P,b){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(P){return P=e(P,a),this[m]?this.nextTick(P):this[h]?this[y].push(P):(this[h]=!0,this[y].push(P),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),P[a]}_close(P){this.nextTick(P)}[p](){this[m]=!0,this.db.detachResource(this);let P=this[y];this[y]=[];for(let b of P)b()}async*[Symbol.asyncIterator](){try{let P;for(;(P=await this.next())!==void 0;)yield P}finally{this[m]||await this.close()}}},X=class extends H{constructor(P,b){super(P,b,!0),this[I]=b.keys!==!1,this[D]=b.values!==!1}[c](P,b,k){let A=this[l]();if(P)return A(P);try{b=this[I]&&b!==void 0?this[S].decode(b):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(O){return A(new x("entry",O))}b===void 0&&k===void 0||this[$]++,A(null,b,k)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A of b){let O=A[0],K=A[1];A[0]=this[I]&&O!==void 0?this[S].decode(O):void 0,A[1]=this[D]&&K!==void 0?this[w].decode(K):void 0}}catch(A){return this[f](k,new x("entries",A))}this[$]+=b.length,this[f](k,null,b)}end(P){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(P)}},R=class extends H{constructor(P,b){super(P,b,!1)}[c](P,b){let k=this[l]();if(P)return k(P);try{b=b!==void 0?this[S].decode(b):void 0}catch(A){return k(new x("key",A))}b!==void 0&&this[$]++,k(null,b)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A=0;A<b.length;A++){let O=b[A];b[A]=O!==void 0?this[S].decode(O):void 0}}catch(A){return this[f](k,new x("keys",A))}this[$]+=b.length,this[f](k,null,b)}},j=class extends H{constructor(P,b){super(P,b,!1)}[c](P,b){let k=this[l]();if(P)return k(P);try{b=b!==void 0?this[w].decode(b):void 0}catch(A){return k(new x("value",A))}b!==void 0&&this[$]++,k(null,b)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A=0;A<b.length;A++){let O=b[A];b[A]=O!==void 0?this[w].decode(O):void 0}}catch(A){return this[f](k,new x("values",A))}this[$]+=b.length,this[f](k,null,b)}},x=class extends r{constructor(P,b){super(`Iterator could not decode ${P}`,{code:"LEVEL_DECODE_ERROR",cause:b})}};for(let P of["_ended property","_nexting property","_end method"])Object.defineProperty(X.prototype,P.split(" ")[0],{get(){throw new r(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})}});X.keyEncoding=S,X.valueEncoding=w,t.AbstractIterator=X,t.AbstractKeyIterator=R,t.AbstractValueIterator=j}),Sne=Bt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Sf(),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}),Ene=Bt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=kc(),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}),GU=Bt(t=>{"use strict";var{fromCallback:e}=tP(),r=kc(),{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),w=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let _=m.prefixKey(S.encode(l),E),I=w.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}),kne=Bt(t=>{"use strict";var{AbstractChainedBatch:e}=GU(),r=kc(),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}),_ne=Bt((t,e)=>{"use strict";var r=kc(),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}}),WU=Bt((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))}),Tne=Bt((t,e)=>{"use strict";var r=WU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),Ine=Bt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),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}),Ane=Bt((t,e)=>{"use strict";var r=kc(),{Buffer:n}=UI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Ine(),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(D){if(typeof D=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?h:D.separator?D:{...D,separator:"!"}}constructor(D,N,$){let{separator:F,manifest:z,...B}=_.defaults($);N=w(N,F);let H=F.charCodeAt(0)+1,X=D[d]||D;if(!f.encode(N).every(x=>x>H&&x<127))throw new r(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(X,z),B);let R=(D.prefix||"")+F+N+F,j=R.slice(0,-1)+String.fromCharCode(H);this[d]=X,this[i]=new y(R),this[c]=new y(j),this[l]=new S,this.nextTick=X.nextTick}prefixKey(D,N){if(N==="utf8")return this[i].utf8+D;if(D.byteLength===0)return this[i][N];if(N==="view"){let $=this[i].view,F=new Uint8Array($.byteLength+D.byteLength);return F.set($,0),F.set(D,$.byteLength),F}else{let $=this[i].buffer;return n.concat([$,D],$.byteLength+D.byteLength)}}[u](D,N){D.gte!==void 0?D.gte=this.prefixKey(D.gte,N):D.gt!==void 0?D.gt=this.prefixKey(D.gt,N):D.gte=this[i][N],D.lte!==void 0?D.lte=this.prefixKey(D.lte,N):D.lt!==void 0?D.lt=this.prefixKey(D.lt,N):D.lte=this[c][N]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(D,N){this[d].open({passive:!0},N)}_put(D,N,$,F){this[d].put(D,N,$,F)}_get(D,N,$){this[d].get(D,N,$)}_getMany(D,N,$){this[d].getMany(D,N,$)}_del(D,N,$){this[d].del(D,N,$)}_batch(D,N,$){this[d].batch(D,N,$)}_clear(D,N){this[u](D,D.keyEncoding),this[d].clear(D,N)}_iterator(D){this[u](D,D.keyEncoding);let N=this[d].iterator(D),$=this[l].get(this[i].utf8.length,D.keyEncoding);return new s(this,D,N,$)}_keys(D){this[u](D,D.keyEncoding);let N=this[d].keys(D),$=this[l].get(this[i].utf8.length,D.keyEncoding);return new a(this,D,N,$)}_values(D){this[u](D,D.keyEncoding);let N=this[d].values(D);return new o(this,D,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(D,N){return N.subarray(D)}).bind(null,E):I=(function(D,N){return N.slice(D)}).bind(null,E),this.cache.set(_,I)),I}},w=function(E,_){let I=0,D=E.length;for(;I<D&&E[I]===_;)I++;for(;D>I&&E[D-1]===_;)D--;return E.slice(I,D)}}),EN=Bt(t=>{"use strict";var{supports:e}=yne(),{Transcoder:r}=bne(),{EventEmitter:n}=Pne(),{fromCallback:s}=tP(),a=kc(),{AbstractIterator:o}=Sf(),{DefaultKeyIterator:i,DefaultValueIterator:c}=Sne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=Ene(),{DefaultChainedBatch:f}=kne(),{getCallback:h,getOptions:p}=LI(),m=_ne(),y=Symbol("promise"),S=Symbol("landed"),w=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),I=Symbol("undefer"),D=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),F=Symbol("defaultOptions"),z=Symbol("transcoder"),B=Symbol("keyEncoding"),H=Symbol("valueEncoding"),X=()=>{},R=class extends n{constructor(b,k){if(super(),typeof b!="object"||b===null)throw new TypeError("The first argument 'manifest' must be an object");k=p(k);let{keyEncoding:A,valueEncoding:O,passive:K,...G}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[N]=G,this[$]="opening",this.supports=e(b,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:b.snapshots!==!1,permanence:b.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:b.encodings||{},events:Object.assign({},b.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(P(this)),this[B]=this[z].encoding(A||"utf8"),this[H]=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[H].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},X)})}get status(){return this[$]}keyEncoding(b){return this[z].encoding(b??this[B])}valueEncoding(b){return this[z].encoding(b??this[H])}open(b,k){k=h(b,k),k=s(k,y),b={...this[N],...p(b)},b.createIfMissing=b.createIfMissing!==!1,b.errorIfExists=!!b.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 b.passive?this[$]==="opening"?this.once(S,A):this.nextTick(A):this[$]==="closed"||this[D]?(this[D]=!1,this[$]="opening",this.emit("opening"),this._open(b,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(b,k)),k[y]}_open(b,k){this.nextTick(k)}close(b){b=s(b,y);let k=A=>{this[$]==="opening"||this[$]==="closing"?this.once(S,A?k(A):k):this[$]!=="closed"?b(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):b()};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(b));return b[y]}[E](b){if(this[w].size===0)return this.nextTick(b);let k=this[w].size,A=!0,O=()=>{--k===0&&(A?this.nextTick(b):b())};for(let K of this[w])K.close(O);A=!1,this[w].clear()}_close(b){this.nextTick(b)}get(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.get(b,k,A)),A[y];if(x(this,A))return A[y];let O=this._checkKey(b);if(O)return this.nextTick(A,O),A[y];let K=this.keyEncoding(k.keyEncoding),G=this.valueEncoding(k.valueEncoding),V=K.format,W=G.format;return(k.keyEncoding!==V||k.valueEncoding!==W)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:W})),this._get(this.prefixKey(K.encode(b),V),k,(J,q)=>{if(J)return(J.code==="LEVEL_NOT_FOUND"||J.notFound||/NotFound/i.test(J))&&(J.code||(J.code="LEVEL_NOT_FOUND"),J.notFound||(J.notFound=!0),J.status||(J.status=404)),A(J);try{q=G.decode(q)}catch(Y){return A(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Y}))}A(null,q)}),A[y]}_get(b,k,A){this.nextTick(A,new Error("NotFound"))}getMany(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.getMany(b,k,A)),A[y];if(x(this,A))return A[y];if(!Array.isArray(b))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(b.length===0)return this.nextTick(A,null,[]),A[y];let O=this.keyEncoding(k.keyEncoding),K=this.valueEncoding(k.valueEncoding),G=O.format,V=K.format;(k.keyEncoding!==G||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:G,valueEncoding:V}));let W=new Array(b.length);for(let J=0;J<b.length;J++){let q=b[J],Y=this._checkKey(q);if(Y)return this.nextTick(A,Y),A[y];W[J]=this.prefixKey(O.encode(q),G)}return this._getMany(W,k,(J,q)=>{if(J)return A(J);try{for(let Y=0;Y<q.length;Y++)q[Y]!==void 0&&(q[Y]=K.decode(q[Y]))}catch(Y){return A(new a(`Could not decode one or more of ${q.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Y}))}A(null,q)}),A[y]}_getMany(b,k,A){this.nextTick(A,null,new Array(b.length).fill(void 0))}put(b,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(b,k,A,O)),O[y];if(x(this,O))return O[y];let K=this._checkKey(b)||this._checkValue(k);if(K)return this.nextTick(O,K),O[y];let G=this.keyEncoding(A.keyEncoding),V=this.valueEncoding(A.valueEncoding),W=G.format,J=V.format;(A.keyEncoding!==W||A.valueEncoding!==J)&&(A=Object.assign({},A,{keyEncoding:W,valueEncoding:J}));let q=this.prefixKey(G.encode(b),W),Y=V.encode(k);return this._put(q,Y,A,ne=>{if(ne)return O(ne);this.emit("put",b,k),O()}),O[y]}_put(b,k,A,O){this.nextTick(O)}del(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].key),this[$]==="opening")return this.defer(()=>this.del(b,k,A)),A[y];if(x(this,A))return A[y];let O=this._checkKey(b);if(O)return this.nextTick(A,O),A[y];let K=this.keyEncoding(k.keyEncoding),G=K.format;return k.keyEncoding!==G&&(k=Object.assign({},k,{keyEncoding:G})),this._del(this.prefixKey(K.encode(b),G),k,V=>{if(V)return A(V);this.emit("del",b),A()}),A[y]}_del(b,k,A){this.nextTick(A)}batch(b,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 b=="function"?A=b:A=h(k,A),A=s(A,y),k=p(k,this[F].empty),this[$]==="opening")return this.defer(()=>this.batch(b,k,A)),A[y];if(x(this,A))return A[y];if(!Array.isArray(b))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(b.length===0)return this.nextTick(A),A[y];let O=new Array(b.length),{keyEncoding:K,valueEncoding:G,...V}=k;for(let W=0;W<b.length;W++){if(typeof b[W]!="object"||b[W]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let J=Object.assign({},b[W]);if(J.type!=="put"&&J.type!=="del")return this.nextTick(A,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),A[y];let q=this._checkKey(J.key);if(q)return this.nextTick(A,q),A[y];let Y=J.sublevel!=null?J.sublevel:this,ne=Y.keyEncoding(J.keyEncoding||K),se=ne.format;if(J.key=Y.prefixKey(ne.encode(J.key),se),J.keyEncoding=se,J.type==="put"){let Z=this._checkValue(J.value);if(Z)return this.nextTick(A,Z),A[y];let ce=Y.valueEncoding(J.valueEncoding||G);J.value=ce.encode(J.value),J.valueEncoding=ce.format}Y!==this&&(J.sublevel=null),O[W]=J}return this._batch(O,V,W=>{if(W)return A(W);this.emit("batch",b),A()}),A[y]}_batch(b,k,A){this.nextTick(A)}sublevel(b,k){return this._sublevel(b,j.defaults(k))}_sublevel(b,k){return new j(this,b,k)}prefixKey(b,k){return b}clear(b,k){if(k=h(b,k),k=s(k,y),b=p(b,this[F].empty),this[$]==="opening")return this.defer(()=>this.clear(b,k)),k[y];if(x(this,k))return k[y];let A=b,O=this.keyEncoding(b.keyEncoding);return b=m(b,O),b.keyEncoding=O.format,b.limit===0?this.nextTick(k):this._clear(b,K=>{if(K)return k(K);this.emit("clear",A),k()}),k[y]}_clear(b,k){this.nextTick(k)}iterator(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b.keys=b.keys!==!1,b.values=b.values!==!1,b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new u(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(b)}_iterator(b){return new o(this,b)}keys(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new d(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(b)}_keys(b){return new i(this,b)}values(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new l(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(b)}_values(b){return new c(this,b)}defer(b){if(typeof b!="function")throw new TypeError("The first argument must be a function");this[_].push(b)}[I](){if(this[_].length===0)return;let b=this[_];this[_]=[];for(let k of b)k()}attachResource(b){if(typeof b!="object"||b===null||typeof b.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(b)}detachResource(b){this[w].delete(b)}_chainedBatch(){return new f(this)}_checkKey(b){if(b==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(b){if(b==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=Tne();var{AbstractSublevel:j}=Ane()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=j;var x=function(b,k){return b[$]!=="open"?(b.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},P=function(b){return Object.keys(b.supports.encodings).filter(k=>!!b.supports.encodings[k])}}),VU=Bt(t=>{"use strict";t.AbstractLevel=EN().AbstractLevel,t.AbstractSublevel=EN().AbstractSublevel,t.AbstractIterator=Sf().AbstractIterator,t.AbstractKeyIterator=Sf().AbstractKeyIterator,t.AbstractValueIterator=Sf().AbstractValueIterator,t.AbstractChainedBatch=GU().AbstractChainedBatch}),Rne=Bt((t,e)=>{e.exports=n;var r=WU();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,w){if(i[y]=w,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(w,E){m(y,w,E)}),S===a-1}):s.some(function(y,S){return y(function(w,E){m(S,w,E)}),S===a-1}):p(null),f=!1}}),HU=Bt((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}}),JU=Bt((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)}}),Dne=Bt(t=>{"use strict";var{AbstractIterator:e}=VU(),r=HU(),n=JU(),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 w=this.db.db.transaction([this[u]],"readonly"),E=w.objectStore(this[u]),_=[];if(this[o].reverse){let I=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[I](S,"prev").onsuccess=D=>{let N=D.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(w)}else this[a]=!0}}else{let I,D,N=()=>{if(I===void 0||D===void 0)return;let $=Math.max(I.length,D.length);$===0||p===1/0?this[a]=!0:this[c]=I[$-1],_.length=$;for(let F=0;F<$;F++){let z=I[F],B=D[F];_[F]=[this[o].keys&&z!==void 0?n(z):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(w)};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=$=>{D=$.target.result,N()}:(D=[],this.nextTick(N))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(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,(w,E)=>{if(w)return m(w);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()}}),Cne=Bt((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()})}}}),jne=Bt(t=>{"use strict";var{AbstractLevel:e}=VU(),r=kc(),n=Rne(),{fromCallback:s}=tP(),{Iterator:a}=Dne(),o=JU(),i=Cne(),c=HU(),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(w,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:D,...N}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[l]=I??u,this[h]=parseInt(D||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(w,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 D=I.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,E){let _=w.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,w.result)}}_get(w,E,_){let I=this[p]("readonly"),D;try{D=I.get(w)}catch(N){return this.nextTick(_,N)}this[m](D,function(N,$){if(N)return _(N);if($===void 0)return _(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(w,E,_){let I=this[p]("readonly"),D=w.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(D,16,_)}_del(w,E,_){let I=this[p]("readwrite"),D;try{D=I.delete(w)}catch(N){return this.nextTick(_,N)}this[m](D,_)}_put(w,E,_,I){let D=this[p]("readwrite"),N;try{N=D.put(E,w)}catch($){return this.nextTick(I,$)}this[m](N,I)}_iterator(w){return new a(this,this[f],w)}_batch(w,E,_){let I=this[p]("readwrite"),D=I.transaction,N=0,$;D.onabort=function(){_($||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function F(){let z=w[N++],B=z.key,H;try{H=z.type==="del"?I.delete(B):I.put(z.value,B)}catch(X){$=X,D.abort();return}N<w.length?H.onsuccess=F:typeof D.commit=="function"&&D.commit()}F()}_clear(w,E){let _,I;try{_=c(w)}catch{return this.nextTick(E)}if(w.limit>=0)return i(this,this[f],_,w,E);try{let D=this[p]("readwrite");I=_?D.delete(_):D.clear()}catch(D){return this.nextTick(E,D)}this[m](I,E)}_close(w){this[d].close(),this.nextTick(w)}};S.destroy=function(w,E,_){typeof E=="function"&&(_=E,E=u),_=s(_,y);let I=indexedDB.deleteDatabase(E+w);return I.onsuccess=function(){_()},I.onerror=function(D){_(D)},_[y]},t.BrowserLevel=S}),ZU=Bt(t=>{t.Level=jne().BrowserLevel}),$ne=Bt((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 Q=arguments.length,ie=Array(Q),oe=0;oe<Q;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,we=1;we<ye;++we)ie[we]=ie[we].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(Q){return"(?:"+Q+")"}function a(Q){return Q===void 0?"undefined":Q===null?"null":Object.prototype.toString.call(Q).split(" ").pop().split("]").shift().toLowerCase()}function o(Q){return Q.toUpperCase()}function i(Q){return Q!=null?Q instanceof Array?Q:typeof Q.length!="number"||Q.split||Q.setInterval||Q.call?[Q]:Array.prototype.slice.call(Q):[]}function c(Q,ie){var oe=Q;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(Q){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",we="[\\x22]",Ue=n(ye,"[A-Fa-f]"),St="[\\x0A]",ar="[\\x20]",Kr=s(s("%[EFef]"+Ue+"%"+Ue+Ue+"%"+Ue+Ue)+"|"+s("%[89A-Fa-f]"+Ue+"%"+Ue+Ue)+"|"+s("%"+Ue+Ue)),zr="[\\:\\/\\?\\#\\[\\]\\@]",Yt="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",fn=n(zr,Yt),$n=Q?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",nn=Q?"[\\uE000-\\uF8FF]":"[]",mr=n(ie,ye,"[\\-\\.\\_\\~]",$n),fr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Ns=s(s(Kr+"|"+n(mr,Yt,"[\\:]"))+"*"),nm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),_i=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Zo=s(_i+"\\."+_i+"\\."+_i+"\\."+_i),yr=s(Ue+"{1,4}"),qi=s(s(yr+"\\:"+yr)+"|"+Zo),vo=s(s(yr+"\\:")+"{6}"+qi),_c=s("\\:\\:"+s(yr+"\\:")+"{5}"+qi),Zu=s(s(yr)+"?\\:\\:"+s(yr+"\\:")+"{4}"+qi),Ca=s(s(s(yr+"\\:")+"{0,1}"+yr)+"?\\:\\:"+s(yr+"\\:")+"{3}"+qi),Ww=s(s(s(yr+"\\:")+"{0,2}"+yr)+"?\\:\\:"+s(yr+"\\:")+"{2}"+qi),Vw=s(s(s(yr+"\\:")+"{0,3}"+yr)+"?\\:\\:"+yr+"\\:"+qi),qf=s(s(s(yr+"\\:")+"{0,4}"+yr)+"?\\:\\:"+qi),Ff=s(s(s(yr+"\\:")+"{0,5}"+yr)+"?\\:\\:"+yr),Gf=s(s(s(yr+"\\:")+"{0,6}"+yr)+"?\\:\\:"),Yu=s([vo,_c,Zu,Ca,Ww,Vw,qf,Ff,Gf].join("|")),Wf=s(s(mr+"|"+Kr)+"+"),Vf=s(Yu+"\\%25"+Wf),yz=s(Yu+s("\\%25|\\%(?!"+Ue+"{2})")+Wf),gz=s("[vV]"+Ue+"+\\."+n(mr,Yt,"[\\:]")+"+"),wz=s("\\["+s(yz+"|"+Yu+"|"+gz)+"\\]"),QA=s(s(Kr+"|"+n(mr,Yt))+"*"),sm=s(wz+"|"+Zo+"(?!"+QA+")|"+QA),im=s(ye+"*"),XA=s(s(Ns+"@")+"?"+sm+s("\\:"+im)+"?"),om=s(Kr+"|"+n(mr,Yt,"[\\:\\@]")),vz=s(om+"*"),eR=s(om+"+"),bz=s(s(Kr+"|"+n(mr,Yt,"[\\@]"))+"+"),Tc=s(s("\\/"+vz)+"*"),Hf=s("\\/"+s(eR+Tc)+"?"),$P=s(bz+Tc),Hw=s(eR+Tc),Jf="(?!"+om+")",$ue=s(Tc+"|"+Hf+"|"+$P+"|"+Hw+"|"+Jf),Zf=s(s(om+"|"+n("[\\/\\?]",nn))+"*"),am=s(s(om+"|[\\/\\?]")+"*"),tR=s(s("\\/\\/"+XA+Tc)+"|"+Hf+"|"+Hw+"|"+Jf),Pz=s(fr+"\\:"+tR+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),xz=s(s("\\/\\/"+XA+Tc)+"|"+Hf+"|"+$P+"|"+Jf),Sz=s(xz+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),Oue=s(Pz+"|"+Sz),Mue=s(fr+"\\:"+tR+s("\\?"+Zf)+"?"),Bue="^("+fr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",Nue="^(){0}"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+$P+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",Uue="^("+fr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?$",Lue="^"+s("\\#("+am+")")+"?$",Kue="^"+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",mr,Yt),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",mr,Yt),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",mr,Yt),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",mr,Yt),"g"),NOT_QUERY:new RegExp(n("[^\\%]",mr,Yt,"[\\:\\@\\/\\?]",nn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",mr,Yt,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",mr,Yt),"g"),UNRESERVED:new RegExp(mr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",mr,fn),"g"),PCT_ENCODED:new RegExp(Kr,"g"),IPV4ADDRESS:new RegExp("^("+Zo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Yu+")"+s(s("\\%25|\\%(?!"+Ue+"{2})")+"("+Wf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function Q(ie,oe){var ye=[],we=!0,Ue=!1,St=void 0;try{for(var ar=ie[Symbol.iterator](),Kr;!(we=(Kr=ar.next()).done)&&(ye.push(Kr.value),!(oe&&ye.length===oe));we=!0);}catch(zr){Ue=!0,St=zr}finally{try{!we&&ar.return&&ar.return()}finally{if(Ue)throw St}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return Q(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(Q){if(Array.isArray(Q)){for(var ie=0,oe=Array(Q.length);ie<Q.length;ie++)oe[ie]=Q[ie];return oe}else return Array.from(Q)},p=2147483647,m=36,y=1,S=26,w=38,E=700,_=72,I=128,D="-",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,H=Math.floor,X=String.fromCharCode;function R(Q){throw new RangeError(z[Q])}function j(Q,ie){for(var oe=[],ye=Q.length;ye--;)oe[ye]=ie(Q[ye]);return oe}function x(Q,ie){var oe=Q.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",Q=oe[1]),Q=Q.replace(F,".");var we=Q.split("."),Ue=j(we,ie).join(".");return ye+Ue}function P(Q){for(var ie=[],oe=0,ye=Q.length;oe<ye;){var we=Q.charCodeAt(oe++);if(we>=55296&&we<=56319&&oe<ye){var Ue=Q.charCodeAt(oe++);(Ue&64512)==56320?ie.push(((we&1023)<<10)+(Ue&1023)+65536):(ie.push(we),oe--)}else ie.push(we)}return ie}var b=function(Q){return String.fromCodePoint.apply(String,h(Q))},k=function(Q){return Q-48<10?Q-22:Q-65<26?Q-65:Q-97<26?Q-97:m},A=function(Q,ie){return Q+22+75*(Q<26)-((ie!=0)<<5)},O=function(Q,ie,oe){var ye=0;for(Q=oe?H(Q/E):Q>>1,Q+=H(Q/ie);Q>B*S>>1;ye+=m)Q=H(Q/B);return H(ye+(B+1)*Q/(Q+w))},K=function(Q){var ie=[],oe=Q.length,ye=0,we=I,Ue=_,St=Q.lastIndexOf(D);St<0&&(St=0);for(var ar=0;ar<St;++ar)Q.charCodeAt(ar)>=128&&R("not-basic"),ie.push(Q.charCodeAt(ar));for(var Kr=St>0?St+1:0;Kr<oe;){for(var zr=ye,Yt=1,fn=m;;fn+=m){Kr>=oe&&R("invalid-input");var $n=k(Q.charCodeAt(Kr++));($n>=m||$n>H((p-ye)/Yt))&&R("overflow"),ye+=$n*Yt;var nn=fn<=Ue?y:fn>=Ue+S?S:fn-Ue;if($n<nn)break;var mr=m-nn;Yt>H(p/mr)&&R("overflow"),Yt*=mr}var fr=ie.length+1;Ue=O(ye-zr,fr,zr==0),H(ye/fr)>p-we&&R("overflow"),we+=H(ye/fr),ye%=fr,ie.splice(ye++,0,we)}return String.fromCodePoint.apply(String,ie)},G=function(Q){var ie=[];Q=P(Q);var oe=Q.length,ye=I,we=0,Ue=_,St=!0,ar=!1,Kr=void 0;try{for(var zr=Q[Symbol.iterator](),Yt;!(St=(Yt=zr.next()).done);St=!0){var fn=Yt.value;fn<128&&ie.push(X(fn))}}catch(Vf){ar=!0,Kr=Vf}finally{try{!St&&zr.return&&zr.return()}finally{if(ar)throw Kr}}var $n=ie.length,nn=$n;for($n&&ie.push(D);nn<oe;){var mr=p,fr=!0,Ns=!1,nm=void 0;try{for(var _i=Q[Symbol.iterator](),Zo;!(fr=(Zo=_i.next()).done);fr=!0){var yr=Zo.value;yr>=ye&&yr<mr&&(mr=yr)}}catch(Vf){Ns=!0,nm=Vf}finally{try{!fr&&_i.return&&_i.return()}finally{if(Ns)throw nm}}var qi=nn+1;mr-ye>H((p-we)/qi)&&R("overflow"),we+=(mr-ye)*qi,ye=mr;var vo=!0,_c=!1,Zu=void 0;try{for(var Ca=Q[Symbol.iterator](),Ww;!(vo=(Ww=Ca.next()).done);vo=!0){var Vw=Ww.value;if(Vw<ye&&++we>p&&R("overflow"),Vw==ye){for(var qf=we,Ff=m;;Ff+=m){var Gf=Ff<=Ue?y:Ff>=Ue+S?S:Ff-Ue;if(qf<Gf)break;var Yu=qf-Gf,Wf=m-Gf;ie.push(X(A(Gf+Yu%Wf,0))),qf=H(Yu/Wf)}ie.push(X(A(qf,0))),Ue=O(we,qi,nn==$n),we=0,++nn}}}catch(Vf){_c=!0,Zu=Vf}finally{try{!vo&&Ca.return&&Ca.return()}finally{if(_c)throw Zu}}++we,++ye}return ie.join("")},V=function(Q){return x(Q,function(ie){return N.test(ie)?K(ie.slice(4).toLowerCase()):ie})},W=function(Q){return x(Q,function(ie){return $.test(ie)?"xn--"+G(ie):ie})},J={version:"2.1.0",ucs2:{decode:P,encode:b},decode:K,encode:G,toASCII:W,toUnicode:V},q={};function Y(Q){var ie=Q.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 ne(Q){for(var ie="",oe=0,ye=Q.length;oe<ye;){var we=parseInt(Q.substr(oe+1,2),16);if(we<128)ie+=String.fromCharCode(we),oe+=3;else if(we>=194&&we<224){if(ye-oe>=6){var Ue=parseInt(Q.substr(oe+4,2),16);ie+=String.fromCharCode((we&31)<<6|Ue&63)}else ie+=Q.substr(oe,6);oe+=6}else if(we>=224){if(ye-oe>=9){var St=parseInt(Q.substr(oe+4,2),16),ar=parseInt(Q.substr(oe+7,2),16);ie+=String.fromCharCode((we&15)<<12|(St&63)<<6|ar&63)}else ie+=Q.substr(oe,9);oe+=9}else ie+=Q.substr(oe,3),oe+=3}return ie}function se(Q,ie){function oe(ye){var we=ne(ye);return we.match(ie.UNRESERVED)?we:ye}return Q.scheme&&(Q.scheme=String(Q.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),Q.userinfo!==void 0&&(Q.userinfo=String(Q.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Y).replace(ie.PCT_ENCODED,o)),Q.host!==void 0&&(Q.host=String(Q.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Y).replace(ie.PCT_ENCODED,o)),Q.path!==void 0&&(Q.path=String(Q.path).replace(ie.PCT_ENCODED,oe).replace(Q.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Y).replace(ie.PCT_ENCODED,o)),Q.query!==void 0&&(Q.query=String(Q.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Y).replace(ie.PCT_ENCODED,o)),Q.fragment!==void 0&&(Q.fragment=String(Q.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Y).replace(ie.PCT_ENCODED,o)),Q}function Z(Q){return Q.replace(/^0*(.*)/,"$1")||"0"}function ce(Q,ie){var oe=Q.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),we=ye[1];return we?we.split(".").map(Z).join("."):Q}function fe(Q,ie){var oe=Q.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),we=ye[1],Ue=ye[2];if(we){for(var St=we.toLowerCase().split("::").reverse(),ar=f(St,2),Kr=ar[0],zr=ar[1],Yt=zr?zr.split(":").map(Z):[],fn=Kr.split(":").map(Z),$n=ie.IPV4ADDRESS.test(fn[fn.length-1]),nn=$n?7:8,mr=fn.length-nn,fr=Array(nn),Ns=0;Ns<nn;++Ns)fr[Ns]=Yt[Ns]||fn[mr+Ns]||"";$n&&(fr[nn-1]=ce(fr[nn-1],ie));var nm=fr.reduce(function(vo,_c,Zu){if(!_c||_c==="0"){var Ca=vo[vo.length-1];Ca&&Ca.index+Ca.length===Zu?Ca.length++:vo.push({index:Zu,length:1})}return vo},[]),_i=nm.sort(function(vo,_c){return _c.length-vo.length})[0],Zo=void 0;if(_i&&_i.length>1){var yr=fr.slice(0,_i.index),qi=fr.slice(_i.index+_i.length);Zo=yr.join(":")+"::"+qi.join(":")}else Zo=fr.join(":");return Ue&&(Zo+="%"+Ue),Zo}else return Q}var ue=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Pe="".match(/(){0}/)[1]===void 0;function pe(Q){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(Q=(ie.scheme?ie.scheme+":":"")+"//"+Q);var we=Q.match(ue);if(we){Pe?(oe.scheme=we[1],oe.userinfo=we[3],oe.host=we[4],oe.port=parseInt(we[5],10),oe.path=we[6]||"",oe.query=we[7],oe.fragment=we[8],isNaN(oe.port)&&(oe.port=we[5])):(oe.scheme=we[1]||void 0,oe.userinfo=Q.indexOf("@")!==-1?we[3]:void 0,oe.host=Q.indexOf("//")!==-1?we[4]:void 0,oe.port=parseInt(we[5],10),oe.path=we[6]||"",oe.query=Q.indexOf("?")!==-1?we[7]:void 0,oe.fragment=Q.indexOf("#")!==-1?we[8]:void 0,isNaN(oe.port)&&(oe.port=Q.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?we[4]:void 0)),oe.host&&(oe.host=fe(ce(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 Ue=q[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!Ue||!Ue.unicodeSupport)){if(oe.host&&(ie.domainHost||Ue&&Ue.domainHost))try{oe.host=J.toASCII(oe.host.replace(ye.PCT_ENCODED,ne).toLowerCase())}catch(St){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+St}se(oe,d)}else se(oe,ye);Ue&&Ue.parse&&Ue.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function Ee(Q,ie){var oe=ie.iri!==!1?l:d,ye=[];return Q.userinfo!==void 0&&(ye.push(Q.userinfo),ye.push("@")),Q.host!==void 0&&ye.push(fe(ce(String(Q.host),oe),oe).replace(oe.IPV6ADDRESS,function(we,Ue,St){return"["+Ue+(St?"%25"+St:"")+"]"})),(typeof Q.port=="number"||typeof Q.port=="string")&&(ye.push(":"),ye.push(String(Q.port))),ye.length?ye.join(""):void 0}var bt=/^\.\.?\//,Un=/^\/\.(\/|$)/,Tr=/^\/\.\.(\/|$)/,ki=/^\/?(?:.|\n)*?(?=\/|$)/;function ze(Q){for(var ie=[];Q.length;)if(Q.match(bt))Q=Q.replace(bt,"");else if(Q.match(Un))Q=Q.replace(Un,"/");else if(Q.match(Tr))Q=Q.replace(Tr,"/"),ie.pop();else if(Q==="."||Q==="..")Q="";else{var oe=Q.match(ki);if(oe){var ye=oe[0];Q=Q.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function Ft(Q){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],we=q[(ie.scheme||Q.scheme||"").toLowerCase()];if(we&&we.serialize&&we.serialize(Q,ie),Q.host&&!oe.IPV6ADDRESS.test(Q.host)&&(ie.domainHost||we&&we.domainHost))try{Q.host=ie.iri?J.toUnicode(Q.host):J.toASCII(Q.host.replace(oe.PCT_ENCODED,ne).toLowerCase())}catch(ar){Q.error=Q.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+ar}se(Q,oe),ie.reference!=="suffix"&&Q.scheme&&(ye.push(Q.scheme),ye.push(":"));var Ue=Ee(Q,ie);if(Ue!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(Ue),Q.path&&Q.path.charAt(0)!=="/"&&ye.push("/")),Q.path!==void 0){var St=Q.path;!ie.absolutePath&&(!we||!we.absolutePath)&&(St=ze(St)),Ue===void 0&&(St=St.replace(/^\/\//,"/%2F")),ye.push(St)}return Q.query!==void 0&&(ye.push("?"),ye.push(Q.query)),Q.fragment!==void 0&&(ye.push("#"),ye.push(Q.fragment)),ye.join("")}function Ir(Q,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],we={};return ye||(Q=pe(Ft(Q,oe),oe),ie=pe(Ft(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(we.scheme=ie.scheme,we.userinfo=ie.userinfo,we.host=ie.host,we.port=ie.port,we.path=ze(ie.path||""),we.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(we.userinfo=ie.userinfo,we.host=ie.host,we.port=ie.port,we.path=ze(ie.path||""),we.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?we.path=ze(ie.path):((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path?we.path="/"+ie.path:Q.path?we.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+ie.path:we.path=ie.path,we.path=ze(we.path)),we.query=ie.query):(we.path=Q.path,ie.query!==void 0?we.query=ie.query:we.query=Q.query),we.userinfo=Q.userinfo,we.host=Q.host,we.port=Q.port),we.scheme=Q.scheme),we.fragment=ie.fragment,we}function tr(Q,ie,oe){var ye=c({scheme:"null"},oe);return Ft(Ir(pe(Q,ye),pe(ie,ye),ye,!0),ye)}function At(Q,ie){return typeof Q=="string"?Q=Ft(pe(Q,ie),ie):a(Q)==="object"&&(Q=pe(Ft(Q,ie),ie)),Q}function T(Q,ie,oe){return typeof Q=="string"?Q=Ft(pe(Q,oe),oe):a(Q)==="object"&&(Q=Ft(Q,oe)),typeof ie=="string"?ie=Ft(pe(ie,oe),oe):a(ie)==="object"&&(ie=Ft(ie,oe)),Q===ie}function M(Q,ie){return Q&&Q.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Y)}function L(Q,ie){return Q&&Q.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,ne)}var te={scheme:"http",domainHost:!0,parse:function(Q,ie){return Q.host||(Q.error=Q.error||"HTTP URIs must have a host."),Q},serialize:function(Q,ie){var oe=String(Q.scheme).toLowerCase()==="https";return(Q.port===(oe?443:80)||Q.port==="")&&(Q.port=void 0),Q.path||(Q.path="/"),Q}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(Q){return typeof Q.secure=="boolean"?Q.secure:String(Q.scheme).toLowerCase()==="wss"}var be={scheme:"ws",domainHost:!0,parse:function(Q,ie){var oe=Q;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(Q,ie){if((Q.port===(he(Q)?443:80)||Q.port==="")&&(Q.port=void 0),typeof Q.secure=="boolean"&&(Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0),Q.resourceName){var oe=Q.resourceName.split("?"),ye=f(oe,2),we=ye[0],Ue=ye[1];Q.path=we&&we!=="/"?we:void 0,Q.query=Ue,Q.resourceName=void 0}return Q.fragment=void 0,Q}},Rt={scheme:"wss",domainHost:be.domainHost,parse:be.parse,serialize:be.serialize},Ln={},Or=!0,lr="[A-Za-z0-9\\-\\.\\_\\~"+(Or?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",rr="[0-9A-Fa-f]",oz=s(s("%[EFef]"+rr+"%"+rr+rr+"%"+rr+rr)+"|"+s("%[89A-Fa-f]"+rr+"%"+rr+rr)+"|"+s("%"+rr+rr)),az="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",cz="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",dz=n(cz,'[\\"\\\\]'),uz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",lz=new RegExp(lr,"g"),zf=new RegExp(oz,"g"),fz=new RegExp(n("[^]",az,"[\\.]",'[\\"]',dz),"g"),HA=new RegExp(n("[^]",lr,uz),"g"),pz=HA;function jP(Q){var ie=ne(Q);return ie.match(lz)?ie:Q}var JA={scheme:"mailto",parse:function(Q,ie){var oe=Q,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var we=!1,Ue={},St=oe.query.split("&"),ar=0,Kr=St.length;ar<Kr;++ar){var zr=St[ar].split("=");switch(zr[0]){case"to":for(var Yt=zr[1].split(","),fn=0,$n=Yt.length;fn<$n;++fn)ye.push(Yt[fn]);break;case"subject":oe.subject=L(zr[1],ie);break;case"body":oe.body=L(zr[1],ie);break;default:we=!0,Ue[L(zr[0],ie)]=L(zr[1],ie);break}}we&&(oe.headers=Ue)}oe.query=void 0;for(var nn=0,mr=ye.length;nn<mr;++nn){var fr=ye[nn].split("@");if(fr[0]=L(fr[0]),ie.unicodeSupport)fr[1]=L(fr[1],ie).toLowerCase();else try{fr[1]=J.toASCII(L(fr[1],ie).toLowerCase())}catch(Ns){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ns}ye[nn]=fr.join("@")}return oe},serialize:function(Q,ie){var oe=Q,ye=i(Q.to);if(ye){for(var we=0,Ue=ye.length;we<Ue;++we){var St=String(ye[we]),ar=St.lastIndexOf("@"),Kr=St.slice(0,ar).replace(zf,jP).replace(zf,o).replace(fz,Y),zr=St.slice(ar+1);try{zr=ie.iri?J.toUnicode(zr):J.toASCII(L(zr,ie).toLowerCase())}catch(nn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+nn}ye[we]=Kr+"@"+zr}oe.path=ye.join(",")}var Yt=Q.headers=Q.headers||{};Q.subject&&(Yt.subject=Q.subject),Q.body&&(Yt.body=Q.body);var fn=[];for(var $n in Yt)Yt[$n]!==Ln[$n]&&fn.push($n.replace(zf,jP).replace(zf,o).replace(HA,Y)+"="+Yt[$n].replace(zf,jP).replace(zf,o).replace(pz,Y));return fn.length&&(oe.query=fn.join("&")),oe}},hz=/^([^\:]+)\:(.*)/,ZA={scheme:"urn",parse:function(Q,ie){var oe=Q.path&&Q.path.match(hz),ye=Q;if(oe){var we=ie.scheme||ye.scheme||"urn",Ue=oe[1].toLowerCase(),St=oe[2],ar=we+":"+(ie.nid||Ue),Kr=q[ar];ye.nid=Ue,ye.nss=St,ye.path=void 0,Kr&&(ye=Kr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(Q,ie){var oe=ie.scheme||Q.scheme||"urn",ye=Q.nid,we=oe+":"+(ie.nid||ye),Ue=q[we];Ue&&(Q=Ue.serialize(Q,ie));var St=Q,ar=Q.nss;return St.path=(ye||ie.nid)+":"+ar,St}},mz=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,YA={scheme:"urn:uuid",parse:function(Q,ie){var oe=Q;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(mz))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(Q,ie){var oe=Q;return oe.nss=(Q.uuid||"").toLowerCase(),oe}};q[te.scheme]=te,q[ae.scheme]=ae,q[be.scheme]=be,q[Rt.scheme]=Rt,q[JA.scheme]=JA,q[ZA.scheme]=ZA,q[YA.scheme]=YA,r.SCHEMES=q,r.pctEncChar=Y,r.pctDecChars=ne,r.parse=pe,r.removeDotSegments=ze,r.serialize=Ft,r.resolveComponents=Ir,r.resolve=tr,r.normalize=At,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),One=Bt((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])}`},"")}}`}}),YU=Bt((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":"")}}),rP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(rP||{}),Bs={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Ds=class QU{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=QU.DID_URI_PATTERN.exec(e);if(!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}};Ds.METHOD_PATTERN="([a-z0-9]+)",Ds.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Ds.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Ds.PCT_ENCODED_PATTERN})`,Ds.METHOD_ID_PATTERN=`((?:${Ds.ID_CHAR_PATTERN}*:)*(${Ds.ID_CHAR_PATTERN}+))`,Ds.PATH_PATTERN="(/[^#?]*)?",Ds.QUERY_PATTERN="([?][^#]*)?",Ds.FRAGMENT_PATTERN="(#.*)?",Ds.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Ds.METHOD_PATTERN+"):(?<id>"+Ds.METHOD_ID_PATTERN+")(?<path>"+Ds.PATH_PATTERN+")(?<query>"+Ds.QUERY_PATTERN+")(?<fragment>"+Ds.FRAGMENT_PATTERN+")$");var ls=Ds,We=class XU 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,XU)}},Mne=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidGatewayUri="invalidGatewayUri",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))(Mne||{}),Wo=class eL extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,eL)}},Li;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Li||(Li={}));var Bne=Rf(mne(),1);function Nne(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,w=p.length;S!==w&&p[S]===0;)S++,m++;for(var E=(w-S)*d+1>>>0,_=new Uint8Array(E);S!==w;){for(var I=p[S],D=0,N=E-1;(I!==0||D<y)&&N!==-1;N--,D++)I+=256*_[N]>>>0,_[N]=I%i>>>0,I=I/i>>>0;if(I!==0)throw new Error("Non-zero carry");y=D,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 w=(p.length-m)*u+1>>>0,E=new Uint8Array(w);p[m];){var _=r[p.charCodeAt(m)];if(_===255)return;for(var I=0,D=w-1;(_!==0||I<S)&&D!==-1;D--,I++)_+=i*E[D]>>>0,E[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");S=I,m++}if(p[m]!==" "){for(var N=w-S;N!==w&&E[N]===0;)N++;for(var $=new Uint8Array(y+(w-N)),F=y;N!==w;)$[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 Une=Nne,Lne=Une,Kne=Lne,u$e=new Uint8Array(0),zne=(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")},qne=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")}},Fne=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 tL(this,t)}},Gne=class{constructor(t){this.decoders=t}or(t){return tL(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`)}},tL=(t,e)=>new Gne({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Wne=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new qne(t,e,r),this.decoder=new Fne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},rL=({name:t,prefix:e,encode:r,decode:n})=>new Wne(t,e,r,n),nL=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=Kne(r,e);return rL({prefix:t,name:e,encode:n,decode:a=>KI(s(a))})},Vne=(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},Hne=(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},yo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>rL({prefix:e,name:t,encode(s){return Hne(s,n,r)},decode(s){return Vne(s,n,r,t)}}),x1=yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),l$e=yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),f$e=yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),p$e=yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),h$e=yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),m$e=yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),y$e=yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),g$e=yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kN=yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Fo=nL({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),w$e=nL({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),v$e=yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),b$e=yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hd=yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),P$e=yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Jne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Zne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function gI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Vg=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())})},_N=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,yf=new TextDecoder,Je=class Ni{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ni(e,"ArrayBuffer")}static asyncIterable(e){if(!Zne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ni(e,"AsyncIterable")}static base32Z(e){return new Ni(e,"Base32Z")}static base58Btc(e){return new Ni(e,"Base58Btc")}static base64Url(e){return new Ni(e,"Base64Url")}static bufferSource(e){return new Ni(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 Ni(e,"Hex")}static multibase(e){return new Ni(e,"Multibase")}static object(e){return new Ni(e,"Object")}static string(e){return new Ni(e,"String")}static uint8Array(e){return new Ni(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Fo.baseDecode(this.data).buffer;case"Base64Url":return hd.baseDecode(this.data).buffer;case"BufferSource":{if(gI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Jne(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 Vg(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 kN.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 Fo.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Fo.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 hd.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return hd.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=h1.encode(e);return hd.baseEncode(r)}case"String":{let e=h1.encode(this.data);return hd.baseEncode(e)}case"Uint8Array":return hd.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=_N(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 Ni.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ni.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=hd.baseDecode(this.data),r=yf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=yf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Vg(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 yf.decode(this.data);case"Base64Url":{let e=hd.baseDecode(this.data);return yf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return yf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=_N(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+=yf.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+=yf.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 kN.baseDecode(this.data);case"Base58Btc":return Fo.baseDecode(this.data);case"Base64Url":return hd.baseDecode(this.data);case"BufferSource":{let e=gI(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 Vg(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.`)}})}},mw;(function(t){t.Debug="debug",t.Silent="silent"})(mw||(mw={}));var Yne=class{constructor(){this.logLevel=mw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==mw.Silent&&console.info(t)}error(t){this.logLevel!==mw.Silent&&console.error(t)}},Qne=new Yne;typeof window<"u"&&(window.enboxLogger=Qne);var ew={};NI(ew,{decode:()=>F1,encodeTo:()=>gw,encodingLength:()=>ww});var Xne=sL,TN=128,ese=127,tse=~ese,rse=Math.pow(2,31);function sL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=rse;)e[r++]=t&255|TN,t/=128;for(;t&tse;)e[r++]=t&255|TN,t>>>=7;return e[r]=t|0,sL.bytes=r-n+1,e}var nse=wI,sse=128,IN=127;function wI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw wI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&IN)<<s:(o&IN)*Math.pow(2,s),s+=7}while(o>=sse);return wI.bytes=a-n,r}var ise=Math.pow(2,7),ose=Math.pow(2,14),ase=Math.pow(2,21),cse=Math.pow(2,28),dse=Math.pow(2,35),use=Math.pow(2,42),lse=Math.pow(2,49),fse=Math.pow(2,56),pse=Math.pow(2,63),hse=function(t){return t<ise?1:t<ose?2:t<ase?3:t<cse?4:t<dse?5:t<use?6:t<lse?7:t<fse?8:t<pse?9:10},mse={encode:Xne,decode:nse,encodingLength:hse},yse=mse,q1=yse,F1=(t,e=0)=>[q1.decode(t,e),q1.decode.bytes],gw=(t,e,r=0)=>(q1.encode(t,e,r),e),ww=t=>q1.encodingLength(t),gse=(t,e)=>{let r=e.byteLength,n=ww(t),s=n+ww(r),a=new Uint8Array(s+r);return gw(t,a,0),gw(r,a,n),a.set(e,s),new zI(t,r,e,a)},wse=t=>{let e=KI(t),[r,n]=F1(e),[s,a]=F1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new zI(r,s,o,e)},vse=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&zne(t.bytes,r.bytes)}},zI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},AN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Pse(r,vI(t),e||Fo.encoder);default:return xse(r,vI(t),e||x1.encoder)}},RN=new WeakMap,vI=t=>{let e=RN.get(t);if(e==null){let r=new Map;return RN.set(t,r),r}return e},x$e=class Ys{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!==Hg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Sse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ys.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=gse(e,r);return Ys.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 Ys.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&vse(e.multihash,n.multihash)}toString(e){return AN(this,e)}toJSON(){return{"/":AN(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 Ys)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Ys(n,s,a,o||DN(n,s,a.bytes))}else if(r[Ese]===!0){let{version:n,multihash:s,code:a}=r,o=wse(s);return Ys.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!==Hg)throw new Error(`Version 0 CID must use dag-pb (code: ${Hg}) block encoding`);return new Ys(e,r,n,n.bytes)}case 1:{let s=DN(e,r,n.bytes);return new Ys(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Ys.create(0,Hg,e)}static createV1(e,r){return Ys.create(1,e,r)}static decode(e){let[r,n]=Ys.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Ys.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?Ys.createV0(o):Ys.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=F1(e.subarray(r));return r+=f,l},s=n(),a=Hg;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]=bse(e,r),a=Ys.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vI(a).set(n,e),a}},bse=(t,e)=>{switch(t[0]){case"Q":{let r=e||Fo;return[Fo.prefix,r.decode(`${Fo.prefix}${t}`)]}case Fo.prefix:{let r=e||Fo;return[Fo.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)]}}},Pse=(t,e,r)=>{let{prefix:n}=r;if(n!==Fo.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},xse=(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},Hg=112,Sse=18,DN=(t,e,r)=>{let n=ww(t),s=n+ww(e),a=new Uint8Array(s+r.byteLength);return gw(t,a,0),gw(e,a,n),a.set(r,s),a},Ese=Symbol.for("@ipld/js-cid/CID"),Ho=class Uu{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=Uu.codeToName.has(n)?n:Uu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=ew.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),ew.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=ew.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Uu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Uu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Uu.codeToName.set(e.code,e.name),Uu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=ew.decode(r),a=Uu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Ho.codeToName=new Map;Ho.nameToCode=new Map;Ho.registerCodec({code:237,name:"ed25519-pub"});Ho.registerCodec({code:4864,name:"ed25519-priv"});Ho.registerCodec({code:236,name:"x25519-pub"});Ho.registerCodec({code:4866,name:"x25519-priv"});Ho.registerCodec({code:231,name:"secp256k1-pub"});Ho.registerCodec({code:4865,name:"secp256k1-priv"});function iL(t){Object.keys(t).forEach(e=>{let r=t[e];r===void 0?delete t[e]:r!==null&&typeof r=="object"&&iL(r)})}var S$e=Rf(ZU(),1),Au=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())})},kse=class{constructor(){this.store=new Map}clear(){return Au(this,void 0,void 0,function*(){this.store.clear()})}open(){return Au(this,void 0,void 0,function*(){})}close(){return Au(this,void 0,void 0,function*(){})}delete(t){return Au(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Au(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Au(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Au(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Au(this,void 0,void 0,function*(){this.store.set(t,e)})}},_se=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())})};function Tse(t){let e=t.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let r=e.indexOf("%");if(r!==-1&&(e=e.slice(0,r)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=aL(e);return n!==void 0?cL(n):e.includes(":")?Dse(e):!1}var Ise=["http:","https:"],S1=class extends Error{constructor(t){super(t),this.name="PublicUrlValidationError"}};function CN(t,e="URL",r){var n;let s=typeof t=="string"?new URL(t):new URL(t.toString()),a=(n=r?.allowedProtocols)!==null&&n!==void 0?n:Ise;if(!a.includes(s.protocol))throw new S1(`${e} must use one of the allowed schemes (${a.join(", ")}): ${s.protocol}`);if(s.hostname==="")throw new S1(`${e} must specify a hostname.`);if(Tse(s.hostname))throw new S1(`${e} must not target a private, loopback, or link-local host: ${s.hostname}`);return s}var Ase=5,Rse=new Set([301,302,303,307,308]);function oL(t,e,r){return _se(this,void 0,void 0,function*(){var n,s;let a=(n=r?.description)!==null&&n!==void 0?n:"URL",o=(s=r?.maxRedirects)!==null&&s!==void 0?s:Ase,i=CN(t,a,{allowedProtocols:r?.allowedProtocols}).href;for(let c=0;c<=o;c++){let u=yield fetch(i,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!Rse.has(u.status))return u;let d=u.headers.get("location");if(d===null)return u;i=CN(new URL(d,i),a,{allowedProtocols:r?.allowedProtocols}).href}throw new Error(`${a} exceeded the maximum number of redirects (${o}).`)})}function aL(t){let e=t.split(".");if(e.length!==4)return;let r=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(r.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return r}function cL([t,e]){return t===0||t===10||t===100&&e>=64&&e<=127||t===127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224}function Dse(t){let e=Cse(t);if(e===void 0)return!1;let[r,n,s,a,o,i,c,u]=e,d=r===0&&n===0&&s===0&&a===0&&o===0&&i===0;return e.every(l=>l===0)||d&&c===0&&u===1||(r&65024)===64512||(r&65472)===65152||(r&65280)===65280?!0:r===100&&n===65435&&s===0&&a===0&&o===0&&i===0||r===0&&n===0&&s===0&&a===0&&o===0&&i===65535?cL($se(c,u)):!!d}function Cse(t){let[e,r,n]=t.split("::");if(n!==void 0)return;let s=e===""?[]:e.split(":"),a=r===void 0||r===""?[]:r.split(":"),o=jse([...s,...a]);if(o===void 0||o.length>8||r===void 0&&o.length!==8||r!==void 0&&o.length>=8)return;let i=o.map(u=>/^[0-9a-f]{1,4}$/.test(u)?Number.parseInt(u,16):Number.NaN);if(!i.every(u=>Number.isInteger(u)&&u>=0&&u<=65535))return;if(r===void 0)return i;let c=new Array(8-i.length).fill(0);return[...i.slice(0,s.length),...c,...i.slice(s.length)]}function jse(t){let e=t.at(-1);if(!e?.includes("."))return t;let r=aL(e);if(r===void 0)return;let[n,s,a,o]=r;return[...t.slice(0,-1),((n<<8|s)&65535).toString(16),((a<<8|o)&65535).toString(16)]}function $se(t,e){return[t>>8&255,t&255,e>>8&255,e&255]}var nP=class{},dL={};NI(dL,{bitGet:()=>Kse,bitLen:()=>Lse,bitMask:()=>FI,bitSet:()=>zse,bytesToHex:()=>Tf,bytesToNumberBE:()=>Ef,bytesToNumberLE:()=>Fu,concatBytes:()=>If,createHmacDrbg:()=>fL,ensureBytes:()=>Cn,equalBytes:()=>Nse,hexToBytes:()=>qh,hexToNumber:()=>qI,isBytes:()=>xc,numberToBytesBE:()=>Sc,numberToBytesLE:()=>Fh,numberToHexUnpadded:()=>lL,numberToVarBytesBE:()=>Bse,utf8ToBytes:()=>Use,validateObject:()=>Df});var uL=BigInt(0),sP=BigInt(1),Ose=BigInt(2);function xc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Mse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Tf(t){if(!xc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Mse[t[r]];return e}function lL(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 md={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function jN(t){if(t>=md._0&&t<=md._9)return t-md._0;if(t>=md._A&&t<=md._F)return t-(md._A-10);if(t>=md._a&&t<=md._f)return t-(md._a-10)}function qh(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=jN(t.charCodeAt(a)),i=jN(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 Ef(t){return qI(Tf(t))}function Fu(t){if(!xc(t))throw new Error("Uint8Array expected");return qI(Tf(Uint8Array.from(t).reverse()))}function Sc(t,e){return qh(t.toString(16).padStart(e*2,"0"))}function Fh(t,e){return Sc(t,e).reverse()}function Bse(t){return qh(lL(t))}function Cn(t,e,r){let n;if(typeof e=="string")try{n=qh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(xc(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 If(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!xc(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 Nse(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 Use(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Lse(t){let e;for(e=0;t>uL;t>>=sP,e+=1);return e}function Kse(t,e){return t>>BigInt(e)&sP}var zse=(t,e,r)=>t|(r?sP:uL)<<BigInt(e),FI=t=>(Ose<<BigInt(t-1))-sP,aI=t=>new Uint8Array(t),$N=t=>Uint8Array.from(t);function fL(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=aI(t),s=aI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=aI())=>{s=i($N([0]),d),n=i(),d.length!==0&&(s=i($N([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 If(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var qse={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"||xc(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 Df(t,e,r={}){let n=(s,a,o)=>{let i=qse[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 ON(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Fse(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function pL(t,...e){if(!Fse(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 Gse(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ON(t.outputLen),ON(t.blockLen)}function G1(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 Wse(t,e){pL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var cI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function hL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var dI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),hc=(t,e)=>t<<32-e|t>>>e,Vse=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Vse)throw new Error("Non little-endian hardware is not supported");function mL(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=mL(t)),!hL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function yL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!hL(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 gL=class{clone(){return this._cloneInto()}},E$e={}.toString;function wL(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(cI&&typeof cI.getRandomValues=="function")return cI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Hse(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 vL=class extends gL{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=dI(this.buffer)}update(t){G1(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=dI(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){G1(this),Wse(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;Hse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=dI(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,Zse=(t,e,r)=>t&e^t&r^e&r,Yse=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]),Ru=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Du=new Uint32Array(64),Qse=class extends vL{constructor(){super(64,32,8,!1),this.A=Ru[0]|0,this.B=Ru[1]|0,this.C=Ru[2]|0,this.D=Ru[3]|0,this.E=Ru[4]|0,this.F=Ru[5]|0,this.G=Ru[6]|0,this.H=Ru[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)Du[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Du[d-15],f=Du[d-2],h=hc(l,7)^hc(l,18)^l>>>3,p=hc(f,17)^hc(f,19)^f>>>10;Du[d]=p+Du[d-7]+h+Du[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=hc(o,6)^hc(o,11)^hc(o,25),f=u+l+Jse(o,i,c)+Yse[d]+Du[d]|0,h=(hc(r,2)^hc(r,13)^hc(r,22))+Zse(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(){Du.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},bL=wL(()=>new Qse),Qn=BigInt(0),rn=BigInt(1),vf=BigInt(2),Xse=BigInt(3),bI=BigInt(4),MN=BigInt(5),BN=BigInt(8),k$e=BigInt(9),eie=BigInt(16);function Lr(t,e){let r=t%e;return r>=Qn?r:e+r}function PL(t,e,r){if(r<=Qn||e<Qn)throw new Error("Expected power/modulo > 0");if(r===rn)return Qn;let n=rn;for(;e>Qn;)e&rn&&(n=n*t%r),t=t*t%r,e>>=rn;return n}function dn(t,e,r){let n=t;for(;e-- >Qn;)n*=n,n%=r;return n}function PI(t,e){if(t===Qn||e<=Qn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Lr(t,e),n=e,s=Qn,a=rn,o=rn,i=Qn;for(;r!==Qn;){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!==rn)throw new Error("invert: does not exist");return Lr(s,e)}function tie(t){let e=(t-rn)/vf,r,n,s;for(r=t-rn,n=0;r%vf===Qn;r/=vf,n++);for(s=vf;s<t&&PL(s,e,t)!==t-rn;s++);if(n===1){let o=(t+rn)/bI;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+rn)/vf;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,rn<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function rie(t){if(t%bI===Xse){let e=(t+rn)/bI;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%BN===MN){let e=(t-MN)/BN;return function(r,n){let s=r.mul(n,vf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,vf),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%eie,tie(t)}var nie=(t,e)=>(Lr(t,e)&rn)===rn,sie=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iie(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=sie.reduce((n,s)=>(n[s]="function",n),e);return Df(t,r)}function oie(t,e,r){if(r<Qn)throw new Error("Expected power > 0");if(r===Qn)return t.ONE;if(r===rn)return e;let n=t.ONE,s=e;for(;r>Qn;)r&rn&&(n=t.mul(n,s)),s=t.sqr(s),r>>=rn;return n}function aie(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 xL(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<=Qn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=xL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=rie(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:FI(s),ZERO:Qn,ONE:rn,create:c=>Lr(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Qn<=c&&c<t},is0:c=>c===Qn,isOdd:c=>(c&rn)===rn,neg:c=>Lr(-c,t),eql:(c,u)=>c===u,sqr:c=>Lr(c*c,t),add:(c,u)=>Lr(c+u,t),sub:(c,u)=>Lr(c-u,t),mul:(c,u)=>Lr(c*u,t),pow:(c,u)=>oie(i,c,u),div:(c,u)=>Lr(c*PI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>PI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>aie(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Fh(c,a):Sc(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Fu(c):Ef(c)}});return Object.freeze(i)}function cie(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 SL(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 EL(t){let e=SL(t);return e+Math.ceil(e/2)}function die(t,e,r=!1){let n=t.length,s=SL(e),a=EL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?Ef(t):Fu(t),i=Lr(o,e-rn)+rn;return r?Fh(i,s):Sc(i,s)}var uie=BigInt(0),uI=BigInt(1);function kL(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>uie;)a&uI&&(o=o.add(i)),i=i.double(),a>>=uI;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+=uI);let S=m,w=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[w]))}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 iie(t.Fp),Df(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...xL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function lie(t){let e=HI(t);Df(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:fie,hexToBytes:pie}=dL,xf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=xf;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:fie(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=xf,r=typeof t=="string"?pie(t):t;if(!xc(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}=xf._parseInt(r.subarray(2)),{d:o,l:i}=xf._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}`}},Pd=BigInt(0),qo=BigInt(1),_$e=BigInt(2),NN=BigInt(3),T$e=BigInt(4);function hie(t){let e=lie(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return If(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),w=r.mul(S,p);return r.add(r.add(w,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"&&Pd<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:w}=e;if(m&&typeof p!="bigint"){if(xc(p)&&(p=Tf(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:Ef(Cn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Lr(E,w)),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 w=E=>r.eql(E,r.ZERO);return w(y)&&w(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,w)=>S.toAffine(y[w])).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),w=a(m);if(!r.eql(S,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:S,pz:w}=this,{px:E,py:_,pz:I}=m,D=r.eql(r.mul(y,I),r.mul(E,w)),N=r.eql(r.mul(S,I),r.mul(_,w));return D&&N}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,NN),{px:w,py:E,pz:_}=this,I=r.ZERO,D=r.ZERO,N=r.ZERO,$=r.mul(w,w),F=r.mul(E,E),z=r.mul(_,_),B=r.mul(w,E);return B=r.add(B,B),N=r.mul(w,_),N=r.add(N,N),I=r.mul(m,N),D=r.mul(S,z),D=r.add(I,D),I=r.sub(F,D),D=r.add(F,D),D=r.mul(I,D),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),D=r.add(D,$),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,D,N)}add(m){d(m);let{px:y,py:S,pz:w}=this,{px:E,py:_,pz:I}=m,D=r.ZERO,N=r.ZERO,$=r.ZERO,F=e.a,z=r.mul(e.b,NN),B=r.mul(y,E),H=r.mul(S,_),X=r.mul(w,I),R=r.add(y,S),j=r.add(E,_);R=r.mul(R,j),j=r.add(B,H),R=r.sub(R,j),j=r.add(y,w);let x=r.add(E,I);return j=r.mul(j,x),x=r.add(B,X),j=r.sub(j,x),x=r.add(S,w),D=r.add(_,I),x=r.mul(x,D),D=r.add(H,X),x=r.sub(x,D),$=r.mul(F,j),D=r.mul(z,X),$=r.add(D,$),D=r.sub(H,$),$=r.add(H,$),N=r.mul(D,$),H=r.add(B,B),H=r.add(H,B),X=r.mul(F,X),j=r.mul(z,j),H=r.add(H,X),X=r.sub(B,X),X=r.mul(F,X),j=r.add(j,X),B=r.mul(H,j),N=r.add(N,B),B=r.mul(x,j),D=r.mul(R,D),D=r.sub(D,B),B=r.mul(R,H),$=r.mul(x,$),$=r.add($,B),new l(D,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(w=>w.pz));return y.map((w,E)=>w.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Pd)return y;if(i(m),m===qo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:w,k1:E,k2neg:_,k2:I}=S.splitScalar(m),D=y,N=y,$=this;for(;E>Pd||I>Pd;)E&qo&&(D=D.add($)),I&qo&&(N=N.add($)),$=$.double(),E>>=qo,I>>=qo;return w&&(D=D.negate()),_&&(N=N.negate()),N=new l(r.mul(N.px,S.beta),N.py,N.pz),D.add(N)}multiply(m){i(m);let y=m,S,w,{endo:E}=e;if(E){let{k1neg:_,k1:I,k2neg:D,k2:N}=E.splitScalar(y),{p:$,f:F}=this.wNAF(I),{p:z,f:B}=this.wNAF(N);$=h.constTimeNegate(_,$),z=h.constTimeNegate(D,z),z=new l(r.mul(z.px,E.beta),z.py,z.pz),S=$.add(z),w=F.add(B)}else{let{p:_,f:I}=this.wNAF(y);S=_,w=I}return l.normalizeZ([S,w])[0]}multiplyAndAddUnsafe(m,y,S){let w=l.BASE,E=(I,D)=>D===Pd||D===qo||!I.equals(w)?I.multiplyUnsafe(D):I.multiply(D),_=E(this,y).add(E(m,S));return _.is0()?void 0:_}toAffine(m){let{px:y,py:S,pz:w}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(w));let _=r.mul(y,m),I=r.mul(S,m),D=r.mul(w,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===qo)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===qo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Tf(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=kL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function mie(t){let e=HI(t);return Df(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function yie(t){let e=mie(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o(j){return Pd<j&&j<r.ORDER}function i(j){return Lr(j,n)}function c(j){return PI(j,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=hie({...e,toBytes(j,x,P){let b=x.toAffine(),k=r.toBytes(b.x),A=If;return P?A(Uint8Array.from([x.hasEvenY()?2:3]),k):A(Uint8Array.from([4]),k,r.toBytes(b.y))},fromBytes(j){let x=j.length,P=j[0],b=j.subarray(1);if(x===s&&(P===2||P===3)){let k=Ef(b);if(!o(k))throw new Error("Point is not on curve");let A=l(k),O=r.sqrt(A),K=(O&qo)===qo;return(P&1)===1!==K&&(O=r.neg(O)),{x:k,y:O}}else if(x===a&&P===4){let k=r.fromBytes(b.subarray(0,r.BYTES)),A=r.fromBytes(b.subarray(r.BYTES,2*r.BYTES));return{x:k,y:A}}else throw new Error(`Point of length ${x} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=j=>Tf(Sc(j,e.nByteLength));function p(j){let x=n>>qo;return j>x}function m(j){return p(j)?i(-j):j}let y=(j,x,P)=>Ef(j.slice(x,P));class S{constructor(x,P,b){this.r=x,this.s=P,this.recovery=b,this.assertValidity()}static fromCompact(x){let P=e.nByteLength;return x=Cn("compactSignature",x,P*2),new S(y(x,0,P),y(x,P,2*P))}static fromDER(x){let{r:P,s:b}=xf.toSig(Cn("DER",x));return new S(P,b)}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(x){return new S(this.r,this.s,x)}recoverPublicKey(x){let{r:P,s:b,recovery:k}=this,A=N(Cn("msgHash",x));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let O=k===2||k===3?P+e.n:P;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let K=k&1?"03":"02",G=u.fromHex(K+h(O)),V=c(O),W=i(-A*V),J=i(b*V),q=u.BASE.multiplyAndAddUnsafe(G,W,J);if(!q)throw new Error("point at infinify");return q.assertValidity(),q}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qh(this.toDERHex())}toDERHex(){return xf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(j){try{return d(j),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let j=EL(e.n);return die(e.randomBytes(j),e.n)},precompute(j=8,x=u.BASE){return x._setWindowSize(j),x.multiply(BigInt(3)),x}};function E(j,x=!0){return u.fromPrivateKey(j).toRawBytes(x)}function _(j){let x=xc(j),P=typeof j=="string",b=(x||P)&&j.length;return x?b===s||b===a:P?b===2*s||b===2*a:j instanceof u}function I(j,x,P=!0){if(_(j))throw new Error("first arg must be private key");if(!_(x))throw new Error("second arg must be public key");return u.fromHex(x).multiply(d(j)).toRawBytes(P)}let D=e.bits2int||function(j){let x=Ef(j),P=j.length*8-e.nBitLength;return P>0?x>>BigInt(P):x},N=e.bits2int_modN||function(j){return i(D(j))},$=FI(e.nBitLength);function F(j){if(typeof j!="bigint")throw new Error("bigint expected");if(!(Pd<=j&&j<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Sc(j,e.nByteLength)}function z(j,x,P=B){if(["recovered","canonical"].some(ne=>ne in P))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:k}=e,{lowS:A,prehash:O,extraEntropy:K}=P;A==null&&(A=!0),j=Cn("msgHash",j),O&&(j=Cn("prehashed msgHash",b(j)));let G=N(j),V=d(x),W=[F(V),F(G)];if(K!=null){let ne=K===!0?k(r.BYTES):K;W.push(Cn("extraEntropy",ne))}let J=If(...W),q=G;function Y(ne){let se=D(ne);if(!f(se))return;let Z=c(se),ce=u.BASE.multiply(se).toAffine(),fe=i(ce.x);if(fe===Pd)return;let ue=i(Z*i(q+fe*V));if(ue===Pd)return;let Pe=(ce.x===fe?0:2)|Number(ce.y&qo),pe=ue;return A&&p(ue)&&(pe=m(ue),Pe^=1),new S(fe,pe,Pe)}return{seed:J,k2sig:Y}}let B={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function X(j,x,P=B){let{seed:b,k2sig:k}=z(j,x,P),A=e;return fL(A.hash.outputLen,A.nByteLength,A.hmac)(b,k)}u.BASE._setWindowSize(8);function R(j,x,P,b=H){let k=j;if(x=Cn("msgHash",x),P=Cn("publicKey",P),"strict"in b)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:O}=b,K,G;try{if(typeof k=="string"||xc(k))try{K=S.fromDER(k)}catch(Z){if(!(Z instanceof xf.Err))throw Z;K=S.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Z,s:ce}=k;K=new S(Z,ce)}else throw new Error("PARSE");G=u.fromHex(P)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(A&&K.hasHighS())return!1;O&&(x=e.hash(x));let{r:V,s:W}=K,J=N(x),q=c(W),Y=i(J*q),ne=i(V*q),se=u.BASE.multiplyAndAddUnsafe(G,Y,ne)?.toAffine();return se?i(se.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:I,sign:X,verify:R,ProjectivePoint:u,Signature:S,utils:w}}var _L=class extends gL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Gse(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 G1(this),this.iHash.update(t),this}digestInto(t){G1(this),pL(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()}},TL=(t,e,r)=>new _L(t,e).update(r).digest();TL.create=(t,e)=>new _L(t,e);function gie(t){return{hash:t,hmac:(e,...r)=>TL(t,e,yL(...r)),randomBytes:WI}}function IL(t,e){let r=n=>yie({...t,...gie(n)});return Object.freeze({...r(e),create:r})}var AL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),UN=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),wie=BigInt(1),xI=BigInt(2),LN=(t,e)=>(t+e/xI)/e;function vie(t){let e=AL,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=dn(d,r,e)*d%e,f=dn(l,r,e)*d%e,h=dn(f,xI,e)*u%e,p=dn(h,s,e)*h%e,m=dn(p,a,e)*p%e,y=dn(m,i,e)*m%e,S=dn(y,c,e)*y%e,w=dn(S,i,e)*m%e,E=dn(w,r,e)*d%e,_=dn(E,o,e)*p%e,I=dn(_,n,e)*u%e,D=dn(I,xI,e);if(!SI.eql(SI.sqr(D),t))throw new Error("Cannot find square root");return D}var SI=VI(AL,void 0,void 0,{sqrt:vie}),fo=IL({a:BigInt(0),b:BigInt(7),Fp:SI,n:UN,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=UN,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-wie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=LN(a*t,e),c=LN(-n*t,e),u=Lr(t-i*r-c*s,e),d=Lr(-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}}}},bL),I$e=BigInt(0),A$e=fo.ProjectivePoint;function bie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function RL(t,...e){if(!bie(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 KN(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 Pie(t,e){RL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var E1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,lI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,R$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function DL(t){return typeof t=="string"&&(t=xie(t)),RL(t),t}var Sie=class{clone(){return this._cloneInto()}},D$e={}.toString;function Eie(t){let e=n=>t().update(DL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function kie(t=32){if(E1&&typeof E1.getRandomValues=="function")return E1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function _ie(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 Tie=(t,e,r)=>t&e^~t&r,Iie=(t,e,r)=>t&e^t&r^e&r,Aie=class extends Sie{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=lI(this.buffer)}update(t){KN(this);let{view:e,buffer:r,blockLen:n}=this;t=DL(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=lI(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){KN(this),Pie(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;_ie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=lI(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}},Rie=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]),Cu=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ju=new Uint32Array(64),Die=class extends Aie{constructor(){super(64,32,8,!1),this.A=Cu[0]|0,this.B=Cu[1]|0,this.C=Cu[2]|0,this.D=Cu[3]|0,this.E=Cu[4]|0,this.F=Cu[5]|0,this.G=Cu[6]|0,this.H=Cu[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)ju[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=ju[d-15],f=ju[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;ju[d]=p+ju[d-7]+h+ju[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+Tie(o,i,c)+Rie[d]+ju[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+Iie(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(){ju.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},vw=Eie(()=>new Die);function Cie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort((o,i)=>o.localeCompare(i)),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var jie=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())})},CL=class{static digest(t){return jie(this,arguments,void 0,function*({data:e}){return vw(e)})}},$ie=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())})},zN="urn:jwk:";function ur(t){return $ie(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}`);iL(n);let s=Cie(n),a=Je.string(s).toUint8Array(),o=yield CL.digest({data:a});return Je.uint8Array(o).toBase64Url()})}function kf(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 Ed(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 Oie(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 As=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())})},Mie=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},js=class gc{static adjustSignatureToLowS(e){return As(this,arguments,void 0,function*({signature:r}){let n=fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static compressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return As(this,arguments,void 0,function*({key:r}){let n=yield gc.privateKeyToBytes({privateKey:r}),s=yield gc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Je.uint8Array(s.x).toBase64Url(),y:Je.uint8Array(s.y).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertDerToCompactSignature(e){return As(this,arguments,void 0,function*({derSignature:r}){return fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return As(this,void 0,void 0,function*(){let e=fo.utils.randomPrivateKey(),r=yield gc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return As(this,arguments,void 0,function*({key:r}){var n;if(!(kf(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=Mie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return As(this,arguments,void 0,function*({privateKey:r}){if(!kf(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return As(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=Je.base64Url(r.x).toUint8Array(),a=Je.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return As(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 gc.privateKeyToBytes({privateKey:r}),a=yield gc.publicKeyToBytes({publicKey:n});return fo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return As(this,arguments,void 0,function*({data:r,key:n}){let s=yield gc.privateKeyToBytes({privateKey:n}),a=vw(r);return fo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){return fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){try{fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return As(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield gc.publicKeyToBytes({publicKey:r}),o=vw(s);return fo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return As(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=fo.getPublicKey(r));let n=fo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},jL=VI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Bie=jL.create(BigInt("-3")),Nie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Uie=IL({a:Bie,b:Nie,Fp:jL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},bL),No=Uie,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())})},Lie=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},Qs=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=No.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:"P-256",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({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:"P-256",x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return No.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:"P-256",x:Je.uint8Array(s.x).toBase64Url(),y:Je.uint8Array(s.y).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return No.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return No.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=No.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(kf(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=Lie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!kf(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(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=Je.base64Url(r.x).toUint8Array(),a=Je.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("Secp256r1: 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 No.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=vw(r);return No.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return No.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{No.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=vw(s);return No.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=No.getPublicKey(r));let n=No.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},yd=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())})},qN=class extends nP{bytesToPrivateKey(t){return yd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Qs.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return yd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Qs.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Qs.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return yd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield js.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield Qs.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Qs.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return yd(this,arguments,void 0,function*({key:e,data:r}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield js.sign({key:e,data:r});case"P-256":return yield Qs.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return yd(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 js.verify({key:e,signature:r,data:n});case"P-256":return yield Qs.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return yd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield js.privateKeyToBytes({privateKey:e});case"P-256":return yield Qs.privateKeyToBytes({privateKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return yd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield js.publicKeyToBytes({publicKey:e});case"P-256":return yield Qs.publicKeyToBytes({publicKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m1=BigInt(4294967295),EI=BigInt(32);function $L(t,e=!1){return e?{h:Number(t&m1),l:Number(t>>EI&m1)}:{h:Number(t>>EI&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}=$L(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var zie=(t,e)=>BigInt(t>>>0)<<EI|BigInt(e>>>0),qie=(t,e,r)=>t>>>r,Fie=(t,e,r)=>t<<32-r|e>>>r,Gie=(t,e,r)=>t>>>r|e<<32-r,Wie=(t,e,r)=>t<<32-r|e>>>r,Vie=(t,e,r)=>t<<64-r|e>>>r-32,Hie=(t,e,r)=>t>>>r-32|e<<64-r,Jie=(t,e)=>e,Zie=(t,e)=>t,Yie=(t,e,r)=>t<<r|e>>>32-r,Qie=(t,e,r)=>e<<r|t>>>32-r,Xie=(t,e,r)=>e<<r-32|t>>>64-r,eoe=(t,e,r)=>t<<r-32|e>>>64-r;function toe(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var roe=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),noe=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,soe=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),ioe=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,ooe=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),aoe=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,coe={fromBig:$L,split:Kie,toBig:zie,shrSH:qie,shrSL:Fie,rotrSH:Gie,rotrSL:Wie,rotrBH:Vie,rotrBL:Hie,rotr32H:Jie,rotr32L:Zie,rotlSH:Yie,rotlSL:Qie,rotlBH:Xie,rotlBL:eoe,add:toe,add3L:roe,add3H:noe,add4L:soe,add4H:ioe,add5H:aoe,add5L:ooe},Et=coe,[doe,uoe]=Et.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))),$u=new Uint32Array(80),Ou=new Uint32Array(80),loe=class extends vL{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 w=0;w<16;w++,e+=4)$u[w]=t.getUint32(e),Ou[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let E=$u[w-15]|0,_=Ou[w-15]|0,I=Et.rotrSH(E,_,1)^Et.rotrSH(E,_,8)^Et.shrSH(E,_,7),D=Et.rotrSL(E,_,1)^Et.rotrSL(E,_,8)^Et.shrSL(E,_,7),N=$u[w-2]|0,$=Ou[w-2]|0,F=Et.rotrSH(N,$,19)^Et.rotrBH(N,$,61)^Et.shrSH(N,$,6),z=Et.rotrSL(N,$,19)^Et.rotrBL(N,$,61)^Et.shrSL(N,$,6),B=Et.add4L(D,z,Ou[w-7],Ou[w-16]),H=Et.add4H(B,I,F,$u[w-7],$u[w-16]);$u[w]=H|0,Ou[w]=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 w=0;w<80;w++){let E=Et.rotrSH(d,l,14)^Et.rotrSH(d,l,18)^Et.rotrBH(d,l,41),_=Et.rotrSL(d,l,14)^Et.rotrSL(d,l,18)^Et.rotrBL(d,l,41),I=d&f^~d&p,D=l&h^~l&m,N=Et.add5L(S,_,D,uoe[w],Ou[w]),$=Et.add5H(N,y,E,I,doe[w],$u[w]),F=N|0,z=Et.rotrSH(r,n,28)^Et.rotrBH(r,n,34)^Et.rotrBH(r,n,39),B=Et.rotrSL(r,n,28)^Et.rotrBL(r,n,34)^Et.rotrBL(r,n,39),H=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}=Et.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 R=Et.add3L(F,B,X);r=Et.add3H(R,$,z,H),n=R|0}({h:r,l:n}=Et.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Et.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Et.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Et.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Et.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Et.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Et.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Et.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(){$u.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)}},OL=wL(()=>new loe),_a=BigInt(0),uo=BigInt(1),y1=BigInt(2),foe=BigInt(8),poe={zip215:!0};function hoe(t){let e=HI(t);return Df(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=hoe(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=y1<<BigInt(i*8)-uo,d=r.create,l=e.uvRatio||((P,b)=>{try{return{isValid:!0,value:r.sqrt(P*r.inv(b))}}catch{return{isValid:!1,value:_a}}}),f=e.adjustScalarBytes||(P=>P),h=e.domain||((P,b,k)=>{if(b.length||k)throw new Error("Contexts/pre-hash are not supported");return P}),p=P=>typeof P=="bigint"&&_a<P,m=(P,b)=>p(P)&&p(b)&&P<b,y=P=>P===_a||m(P,u);function S(P,b){if(m(P,b))return P;throw new Error(`Expected valid scalar < ${b}, got ${typeof P} ${P}`)}function w(P){return P===_a?P:S(P,n)}let E=new Map;function _(P){if(!(P instanceof I))throw new Error("ExtendedPoint expected")}class I{constructor(b,k,A,O){if(this.ex=b,this.ey=k,this.ez=A,this.et=O,!y(b))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(b){if(b instanceof I)throw new Error("extended point not allowed");let{x:k,y:A}=b||{};if(!y(k)||!y(A))throw new Error("invalid affine point");return new I(k,A,uo,d(k*A))}static normalizeZ(b){let k=r.invertBatch(b.map(A=>A.ez));return b.map((A,O)=>A.toAffine(k[O])).map(I.fromAffine)}_setWindowSize(b){this._WINDOW_SIZE=b,E.delete(this)}assertValidity(){let{a:b,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:O,ez:K,et:G}=this,V=d(A*A),W=d(O*O),J=d(K*K),q=d(J*J),Y=d(V*b),ne=d(J*d(Y+W)),se=d(q+d(k*d(V*W)));if(ne!==se)throw new Error("bad point: equation left != right (1)");let Z=d(A*O),ce=d(K*G);if(Z!==ce)throw new Error("bad point: equation left != right (2)")}equals(b){_(b);let{ex:k,ey:A,ez:O}=this,{ex:K,ey:G,ez:V}=b,W=d(k*V),J=d(K*O),q=d(A*V),Y=d(G*O);return W===J&&q===Y}is0(){return this.equals(I.ZERO)}negate(){return new I(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:b}=e,{ex:k,ey:A,ez:O}=this,K=d(k*k),G=d(A*A),V=d(y1*d(O*O)),W=d(b*K),J=k+A,q=d(d(J*J)-K-G),Y=W+G,ne=Y-V,se=W-G,Z=d(q*ne),ce=d(Y*se),fe=d(q*se),ue=d(ne*Y);return new I(Z,ce,ue,fe)}add(b){_(b);let{a:k,d:A}=e,{ex:O,ey:K,ez:G,et:V}=this,{ex:W,ey:J,ez:q,et:Y}=b;if(k===BigInt(-1)){let ki=d((K-O)*(J+W)),ze=d((K+O)*(J-W)),Ft=d(ze-ki);if(Ft===_a)return this.double();let Ir=d(G*y1*Y),tr=d(V*y1*q),At=tr+Ir,T=ze+ki,M=tr-Ir,L=d(At*Ft),te=d(T*M),ae=d(At*M),he=d(Ft*T);return new I(L,te,he,ae)}let ne=d(O*W),se=d(K*J),Z=d(V*A*Y),ce=d(G*q),fe=d((O+K)*(W+J)-ne-se),ue=ce-Z,Pe=ce+Z,pe=d(se-k*ne),Ee=d(fe*ue),bt=d(Pe*pe),Un=d(fe*pe),Tr=d(ue*Pe);return new I(Ee,bt,Tr,Un)}subtract(b){return this.add(b.negate())}wNAF(b){return $.wNAFCached(this,E,b,I.normalizeZ)}multiply(b){let{p:k,f:A}=this.wNAF(S(b,n));return I.normalizeZ([k,A])[0]}multiplyUnsafe(b){let k=w(b);return k===_a?N:this.equals(N)||k===uo?this:this.equals(D)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(b){let{ex:k,ey:A,ez:O}=this,K=this.is0();b==null&&(b=K?foe:r.inv(O));let G=d(k*b),V=d(A*b),W=d(O*b);if(K)return{x:_a,y:uo};if(W!==uo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:b}=e;return b===uo?this:this.multiplyUnsafe(b)}static fromHex(b,k=!1){let{d:A,a:O}=e,K=r.BYTES;b=Cn("pointHex",b,K);let G=b.slice(),V=b[K-1];G[K-1]=V&-129;let W=Fu(G);W===_a||(k?S(W,u):S(W,r.ORDER));let J=d(W*W),q=d(J-uo),Y=d(A*J-O),{isValid:ne,value:se}=l(q,Y);if(!ne)throw new Error("Point.fromHex: invalid y coordinate");let Z=(se&uo)===uo,ce=(V&128)!==0;if(!k&&se===_a&&ce)throw new Error("Point.fromHex: x=0 and x_0=1");return ce!==Z&&(se=d(-se)),I.fromAffine({x:se,y:W})}static fromPrivateKey(b){return B(b).point}toRawBytes(){let{x:b,y:k}=this.toAffine(),A=Fh(k,r.BYTES);return A[A.length-1]|=b&uo?128:0,A}toHex(){return Tf(this.toRawBytes())}}I.BASE=new I(e.Gx,e.Gy,uo,d(e.Gx*e.Gy)),I.ZERO=new I(_a,uo,uo,_a);let{BASE:D,ZERO:N}=I,$=kL(I,i*8);function F(P){return Lr(P,n)}function z(P){return F(Fu(P))}function B(P){let b=i;P=Cn("private key",P,b);let k=Cn("hashed private key",a(P),2*b),A=f(k.slice(0,b)),O=k.slice(b,2*b),K=z(A),G=D.multiply(K),V=G.toRawBytes();return{head:A,prefix:O,scalar:K,point:G,pointBytes:V}}function H(P){return B(P).pointBytes}function X(P=new Uint8Array,...b){let k=If(...b);return z(a(h(k,Cn("context",P),!!s)))}function R(P,b,k={}){P=Cn("message",P),s&&(P=s(P));let{prefix:A,scalar:O,pointBytes:K}=B(b),G=X(k.context,A,P),V=D.multiply(G).toRawBytes(),W=X(k.context,V,K,P),J=F(G+W*O);w(J);let q=If(V,Fh(J,r.BYTES));return Cn("result",q,i*2)}let j=poe;function x(P,b,k,A=j){let{context:O,zip215:K}=A,G=r.BYTES;P=Cn("signature",P,2*G),b=Cn("message",b),s&&(b=s(b));let V=Fu(P.slice(G,2*G)),W,J,q;try{W=I.fromHex(k,K),J=I.fromHex(P.slice(0,G),K),q=D.multiplyUnsafe(V)}catch{return!1}if(!K&&W.isSmallOrder())return!1;let Y=X(O,J.toRawBytes(),W.toRawBytes(),b);return J.add(W.multiplyUnsafe(Y)).subtract(q).clearCofactor().equals(I.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:x,ExtendedPoint:I,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(r.BYTES),precompute(P=8,b=I.BASE){return b._setWindowSize(P),b.multiply(BigInt(3)),b}}}}var Jg=BigInt(0),fI=BigInt(1);function moe(t){return Df(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function yoe(t){let e=moe(t),{P:r}=e,n=E=>Lr(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>PL(E,r-BigInt(2),r));function u(E,_,I){let D=n(E*(_-I));return _=n(_-D),I=n(I+D),[_,I]}function d(E){if(typeof E=="bigint"&&Jg<=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),D=d(_),N=I,$=fI,F=Jg,z=I,B=fI,H=Jg,X;for(let j=BigInt(s-1);j>=Jg;j--){let x=D>>j&fI;H^=x,X=u(H,$,z),$=X[0],z=X[1],X=u(H,F,B),F=X[0],B=X[1],H=x;let P=$+F,b=n(P*P),k=$-F,A=n(k*k),O=b-A,K=z+B,G=z-B,V=n(G*P),W=n(K*k),J=V+W,q=V-W;z=n(J*J),B=n(N*n(q*q)),$=n(b*A),F=n(O*(b+n(l*O)))}X=u(H,$,z),$=X[0],z=X[1],X=u(H,F,B),F=X[0],B=X[1];let R=c(F);return n($*R)}function h(E){return Fh(n(E),a)}function p(E){let _=Cn("u coordinate",E,a);return o===32&&(_[31]&=127),Fu(_)}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 Fu(i(_))}function y(E,_){let I=p(_),D=m(E),N=f(I,D);if(N===Jg)throw new Error("Invalid private or public key received");return h(N)}let S=h(e.Gu);function w(E){return y(E,S)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>w(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var bw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),C$e=BigInt(0),goe=BigInt(1),kI=BigInt(2),woe=BigInt(5),GN=BigInt(10),voe=BigInt(20),boe=BigInt(40),WN=BigInt(80);function ML(t){let e=bw,r=t*t%e*t%e,n=dn(r,kI,e)*r%e,s=dn(n,goe,e)*t%e,a=dn(s,woe,e)*s%e,o=dn(a,GN,e)*a%e,i=dn(o,voe,e)*o%e,c=dn(i,boe,e)*i%e,u=dn(c,WN,e)*c%e,d=dn(u,WN,e)*c%e,l=dn(d,GN,e)*a%e;return{pow_p_5_8:dn(l,kI,e)*t%e,b2:r}}function BL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Poe(t,e){let r=bw,n=Lr(e*e*e,r),s=Lr(n*n*e,r),a=ML(t*s).pow_p_5_8,o=Lr(t*n*a,r),i=Lr(e*o*o,r),c=o,u=Lr(o*FN,r),d=i===t,l=i===Lr(-t,r),f=i===Lr(-t*FN,r);return d&&(o=c),(l||f)&&(o=u),nie(o,r)&&(o=Lr(-o,r)),{isValid:d||l,value:o}}var Vo=VI(bw,void 0,!0),Pw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Vo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:OL,randomBytes:WI,adjustScalarBytes:BL,uvRatio:Poe},gf=YI(Pw);function NL(t,e,r){if(e.length>255)throw new Error("Context is too big");return yL(mL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var j$e=YI({...Pw,domain:NL}),$$e=YI({...Pw,domain:NL,prehash:OL}),tw=yoe({P:bw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=bw,{pow_p_5_8:r,b2:n}=ML(t);return Lr(dn(r,BigInt(3),e)*n,e)},adjustScalarBytes:BL,randomBytes:WI});function xoe(t){let{y:e}=gf.ExtendedPoint.fromHex(t),r=BigInt(1);return Vo.toBytes(Vo.create((r+e)*Vo.inv(r-e)))}function Soe(t){let e=Pw.hash(t.subarray(0,32));return Pw.adjustScalarBytes(e).subarray(0,32)}var Eoe=(Vo.ORDER+BigInt(3))/BigInt(8),O$e=Vo.pow(kI,Eoe),M$e=Vo.sqrt(Vo.neg(Vo.ONE)),B$e=(Vo.ORDER-BigInt(5))/BigInt(8),N$e=BigInt(486662),U$e=cie(Vo,Vo.neg(BigInt(486664))),L$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),K$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),z$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),q$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),F$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Uo=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())})},koe=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 Lu{static bytesToPrivateKey(e){return Uo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=gf.getPublicKey(r),s={crv:"Ed25519",d:Je.uint8Array(r).toBase64Url(),kty:"OKP",x:Je.uint8Array(n).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return Uo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Je.uint8Array(r).toBase64Url()};return n.kid=yield ur({jwk:n}),n})}static computePublicKey(e){return Uo(this,arguments,void 0,function*({key:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=gf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Uo(this,arguments,void 0,function*({privateKey:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=Soe(n),a=tw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Je.uint8Array(s).toBase64Url(),x:Je.uint8Array(a).toBase64Url()};return o.kid=yield ur({jwk:o}),o})}static convertPublicKeyToX25519(e){return Uo(this,arguments,void 0,function*({publicKey:r}){let n=yield Lu.publicKeyToBytes({publicKey:r});if(!(yield Lu.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=xoe(n),a={kty:"OKP",crv:"X25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static generateKey(){return Uo(this,void 0,void 0,function*(){let e=gf.utils.randomPrivateKey(),r=yield Lu.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Uo(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=koe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Uo(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Uo(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 Je.base64Url(r.x).toUint8Array()})}static sign(e){return Uo(this,arguments,void 0,function*({key:r,data:n}){let s=yield Lu.privateKeyToBytes({privateKey:r});return gf.sign(n,s)})}static validatePublicKey(e){return Uo(this,arguments,void 0,function*({publicKeyBytes:r}){try{gf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Uo(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Lu.publicKeyToBytes({publicKey:r});return gf.verify(n,s,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())})},_oe=class extends nP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield $s.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield $s.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(!ZI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield $s.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"Ed25519":return yield $s.privateKeyToBytes({privateKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield $s.publicKeyToBytes({publicKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},Toe=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())})},Ioe=class extends nP{digest(t){return Toe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield CL.digest({data:r})}})}},Mu=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())})},Aoe=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},Ch=class rw{static bytesToPrivateKey(e){return Mu(this,arguments,void 0,function*({privateKeyBytes:r}){let n=tw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return Mu(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Je.uint8Array(r).toBase64Url()};return n.kid=yield ur({jwk:n}),n})}static computePublicKey(e){return Mu(this,arguments,void 0,function*({key:r}){let n=yield rw.privateKeyToBytes({privateKey:r}),s=tw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static generateKey(){return Mu(this,void 0,void 0,function*(){let e=tw.utils.randomPrivateKey(),r=yield rw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Mu(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=Aoe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Mu(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Mu(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 Je.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Mu(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 rw.privateKeyToBytes({privateKey:r}),a=yield rw.publicKeyToBytes({publicKey:n});return tw.getSharedSecret(s,a)})}},Zg=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())})},Roe=class extends nP{bytesToPrivateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Ch.bytesToPrivateKey({privateKeyBytes:r});default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.computePublicKey({key:e});default:throw new Wo(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ch.generateKey();default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.getPublicKey({key:e});default:throw new Wo(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Zg(this,arguments,void 0,function*({privateKey:e}){return Ch.privateKeyToBytes({privateKey:e})})}},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())})},pI={Ed25519:{implementation:_oe,names:["Ed25519"]},secp256k1:{implementation:qN,names:["ES256K","secp256k1"]},secp256r1:{implementation:qN,names:["ES256","secp256r1"]},"SHA-256":{implementation:Ioe,names:["SHA-256"]},X25519:{implementation:Roe,names:["X25519"]}},Aa=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new kse}digest(t){return wd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return wd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return wd(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=`${zN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return wd(this,arguments,void 0,function*({key:e}){let r=yield ur({jwk:e});return`${zN}${r}`})}getPublicKey(t){return wd(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 wd(this,arguments,void 0,function*({key:e}){var r;if(!Oie(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 ur({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return wd(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 wd(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=pI[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 pI){let s=pI[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 wd(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})}},Doe=class UL{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 kie(e)}static randomUuid(){return E1.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),n=Math.ceil(Math.log2(r)/8),s=Math.pow(2,n*8),a=s-s%r,o;do{o=0;let i=UL.randomBytes(n);for(let c of i)o=o*256+c}while(o>=a);return(o%r).toString().padStart(e,"0")}},Coe=["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 joe(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":$oe(t)||"Object"}function $oe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(Coe.includes(e))return e}var ve=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}};ve.uint=new ve(0,"uint",!0);ve.negint=new ve(1,"negint",!0);ve.bytes=new ve(2,"bytes",!0);ve.string=new ve(3,"string",!0);ve.array=new ve(4,"array",!1);ve.map=new ve(5,"map",!1);ve.tag=new ve(6,"tag",!1);ve.float=new ve(7,"float",!0);ve.false=new ve(7,"false",!0);ve.true=new ve(7,"true",!0);ve.null=new ve(7,"null",!0);ve.undefined=new ve(7,"undefined",!0);ve.break=new ve(7,"break",!0);var Ve=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}`}},Tw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Ooe=new TextEncoder;function W1(t){return Tw&&globalThis.Buffer.isBuffer(t)}function LL(t){return t instanceof Uint8Array?W1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var Moe=24,Boe=200,Noe=Tw?t=>t.length>=Moe?globalThis.Buffer.from(t):VN(t):t=>t.length>=Boe?Ooe.encode(t):VN(t),vd=t=>Uint8Array.from(t),Uoe=Tw?(t,e,r)=>W1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Loe=Tw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),LL(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=Tw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function KL(t,e){if(W1(t)&&W1(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 VN(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 zoe=256,zL=class{constructor(t=zoe){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=Uoe(r,0,this.cursor)}else e=Loe(this.chunks,this.cursor);return t&&this.reset(),e}},qoe=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}},un="CBOR decode error:",qL="CBOR encode error:",Iw=[];Iw[23]=1;Iw[24]=2;Iw[25]=3;Iw[26]=5;Iw[27]=9;function Jh(t,e,r){if(t.length-e<r)throw new Error(`${un} not enough data for type`)}var Os=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Cf(t,e,r){Jh(t,e,1);let n=t[e];if(r.strict===!0&&n<Os[0])throw new Error(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function jf(t,e,r){Jh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Os[1])throw new Error(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Jh(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(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function Of(t,e,r){Jh(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(`${un} 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(`${un} integers outside of the safe integer range are not supported`)}function Foe(t,e,r,n){return new Ve(ve.uint,Cf(t,e+1,n),2)}function Goe(t,e,r,n){return new Ve(ve.uint,jf(t,e+1,n),3)}function Woe(t,e,r,n){return new Ve(ve.uint,$f(t,e+1,n),5)}function Voe(t,e,r,n){return new Ve(ve.uint,Of(t,e+1,n),9)}function Mf(t,e){return Jo(t,0,e.value)}function Jo(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(`${un} encountered BigInt larger than allowable range`)}}Mf.encodedSize=function(t){return Jo.encodedSize(t.value)};Jo.encodedSize=function(t){return t<Os[0]?1:t<Os[1]?2:t<Os[2]?3:t<Os[3]?5:9};Mf.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Hoe(t,e,r,n){return new Ve(ve.negint,-1-Cf(t,e+1,n),2)}function Joe(t,e,r,n){return new Ve(ve.negint,-1-jf(t,e+1,n),3)}function Zoe(t,e,r,n){return new Ve(ve.negint,-1-$f(t,e+1,n),5)}var QI=BigInt(-1),FL=BigInt(1);function Yoe(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 Ve(ve.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${un} integers outside of the safe integer range are not supported`);return new Ve(ve.negint,QI-BigInt(s),9)}function XI(t,e){let r=e.value,n=typeof r=="bigint"?r*QI-FL:r*-1-1;Jo(t,e.type.majorEncoded,n)}XI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*QI-FL: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 Aw(t,e,r,n){Jh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Ve(ve.bytes,s,r+n)}function Qoe(t,e,r,n){return Aw(t,e,1,r)}function Xoe(t,e,r,n){return Aw(t,e,2,Cf(t,e+1,n))}function eae(t,e,r,n){return Aw(t,e,3,jf(t,e+1,n))}function tae(t,e,r,n){return Aw(t,e,5,$f(t,e+1,n))}function rae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer bytes lengths not supported`);return Aw(t,e,9,s)}function V1(t){return t.encodedBytes===void 0&&(t.encodedBytes=ve.equals(t.type,ve.string)?Noe(t.value):t.value),t.encodedBytes}function iP(t,e){let r=V1(e);Jo(t,e.type.majorEncoded,r.length),t.push(r)}iP.encodedSize=function(t){let e=V1(t);return Jo.encodedSize(e.length)+e.length};iP.compareTokens=function(t,e){return nae(V1(t),V1(e))};function nae(t,e){return t.length<e.length?-1:t.length>e.length?1:KL(t,e)}var HN=new TextDecoder,sae=32;function iae(t,e,r){if(r-e<sae){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return HN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return HN.decode(t.subarray(e,r))}function Rw(t,e,r,n,s){let a=r+n;Jh(t,e,a);let o=new Ve(ve.string,iae(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function oae(t,e,r,n){return Rw(t,e,1,r,n)}function aae(t,e,r,n){return Rw(t,e,2,Cf(t,e+1,n),n)}function cae(t,e,r,n){return Rw(t,e,3,jf(t,e+1,n),n)}function dae(t,e,r,n){return Rw(t,e,5,$f(t,e+1,n),n)}function uae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer string lengths not supported`);return Rw(t,e,9,s,n)}var lae=iP;function Zh(t,e,r,n){return new Ve(ve.array,n,r)}function fae(t,e,r,n){return Zh(t,e,1,r)}function pae(t,e,r,n){return Zh(t,e,2,Cf(t,e+1,n))}function hae(t,e,r,n){return Zh(t,e,3,jf(t,e+1,n))}function mae(t,e,r,n){return Zh(t,e,5,$f(t,e+1,n))}function yae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer array lengths not supported`);return Zh(t,e,9,s)}function gae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return Zh(t,e,1,1/0)}function eA(t,e){Jo(t,ve.array.majorEncoded,e.value)}eA.compareTokens=Mf.compareTokens;eA.encodedSize=function(t){return Jo.encodedSize(t.value)};function Yh(t,e,r,n){return new Ve(ve.map,n,r)}function wae(t,e,r,n){return Yh(t,e,1,r)}function vae(t,e,r,n){return Yh(t,e,2,Cf(t,e+1,n))}function bae(t,e,r,n){return Yh(t,e,3,jf(t,e+1,n))}function Pae(t,e,r,n){return Yh(t,e,5,$f(t,e+1,n))}function xae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer map lengths not supported`);return Yh(t,e,9,s)}function Sae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function tA(t,e){Jo(t,ve.map.majorEncoded,e.value)}tA.compareTokens=Mf.compareTokens;tA.encodedSize=function(t){return Jo.encodedSize(t.value)};function Eae(t,e,r,n){return new Ve(ve.tag,r,1)}function kae(t,e,r,n){return new Ve(ve.tag,Cf(t,e+1,n),2)}function _ae(t,e,r,n){return new Ve(ve.tag,jf(t,e+1,n),3)}function Tae(t,e,r,n){return new Ve(ve.tag,$f(t,e+1,n),5)}function Iae(t,e,r,n){return new Ve(ve.tag,Of(t,e+1,n),9)}function rA(t,e){Jo(t,ve.tag.majorEncoded,e.value)}rA.compareTokens=Mf.compareTokens;rA.encodedSize=function(t){return Jo.encodedSize(t.value)};var GL=20,WL=21,VL=22,HL=23;function Aae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${un} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Ve(ve.null,null,1):new Ve(ve.undefined,void 0,1)}function Rae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return new Ve(ve.break,void 0,1)}function nA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${un} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${un} Infinity values are not supported`)}return new Ve(ve.float,t,e)}function Dae(t,e,r,n){return nA(iA(t,e+1),3,n)}function Cae(t,e,r,n){return nA(oA(t,e+1),5,n)}function jae(t,e,r,n){return nA(QL(t,e+1),9,n)}function sA(t,e,r){let n=e.value;if(n===!1)t.push([ve.float.majorEncoded|GL]);else if(n===!0)t.push([ve.float.majorEncoded|WL]);else if(n===null)t.push([ve.float.majorEncoded|VL]);else if(n===void 0)t.push([ve.float.majorEncoded|HL]);else{let s,a=!1;(!r||r.float64!==!0)&&(ZL(n),s=iA(Ta,1),n===s||Number.isNaN(n)?(Ta[0]=249,t.push(Ta.slice(0,3)),a=!0):(YL(n),s=oA(Ta,1),n===s&&(Ta[0]=250,t.push(Ta.slice(0,5)),a=!0))),a||($ae(n),s=QL(Ta,1),Ta[0]=251,t.push(Ta.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){ZL(r);let n=iA(Ta,1);if(r===n||Number.isNaN(r))return 3;if(YL(r),n=oA(Ta,1),r===n)return 5}return 9};var JL=new ArrayBuffer(9),Ko=new DataView(JL,1),Ta=new Uint8Array(JL,0);function ZL(t){if(t===1/0)Ko.setUint16(0,31744,!1);else if(t===-1/0)Ko.setUint16(0,64512,!1);else if(Number.isNaN(t))Ko.setUint16(0,32256,!1);else{Ko.setFloat32(0,t);let e=Ko.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Ko.setUint16(0,31744,!1);else if(r===0)Ko.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?Ko.setUint16(0,0):s<-14?Ko.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Ko.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function iA(t,e){if(t.length-e<2)throw new Error(`${un} 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 YL(t){Ko.setFloat32(0,t,!1)}function oA(t,e){if(t.length-e<4)throw new Error(`${un} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function $ae(t){Ko.setFloat64(0,t,!1)}function QL(t,e){if(t.length-e<8)throw new Error(`${un} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}sA.compareTokens=Mf.compareTokens;function er(t,e,r){throw new Error(`${un} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function oP(t){return()=>{throw new Error(`${un} ${t}`)}}var De=[];for(let t=0;t<=23;t++)De[t]=er;De[24]=Foe;De[25]=Goe;De[26]=Woe;De[27]=Voe;De[28]=er;De[29]=er;De[30]=er;De[31]=er;for(let t=32;t<=55;t++)De[t]=er;De[56]=Hoe;De[57]=Joe;De[58]=Zoe;De[59]=Yoe;De[60]=er;De[61]=er;De[62]=er;De[63]=er;for(let t=64;t<=87;t++)De[t]=Qoe;De[88]=Xoe;De[89]=eae;De[90]=tae;De[91]=rae;De[92]=er;De[93]=er;De[94]=er;De[95]=oP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)De[t]=oae;De[120]=aae;De[121]=cae;De[122]=dae;De[123]=uae;De[124]=er;De[125]=er;De[126]=er;De[127]=oP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)De[t]=fae;De[152]=pae;De[153]=hae;De[154]=mae;De[155]=yae;De[156]=er;De[157]=er;De[158]=er;De[159]=gae;for(let t=160;t<=183;t++)De[t]=wae;De[184]=vae;De[185]=bae;De[186]=Pae;De[187]=xae;De[188]=er;De[189]=er;De[190]=er;De[191]=Sae;for(let t=192;t<=215;t++)De[t]=Eae;De[216]=kae;De[217]=_ae;De[218]=Tae;De[219]=Iae;De[220]=er;De[221]=er;De[222]=er;De[223]=er;for(let t=224;t<=243;t++)De[t]=oP("simple values are not supported");De[244]=er;De[245]=er;De[246]=er;De[247]=Aae;De[248]=oP("simple values are not supported");De[249]=Dae;De[250]=Cae;De[251]=jae;De[252]=er;De[253]=er;De[254]=er;De[255]=Rae;var _d=[];for(let t=0;t<24;t++)_d[t]=new Ve(ve.uint,t,1);for(let t=-1;t>=-24;t--)_d[31-t]=new Ve(ve.negint,t,1);_d[64]=new Ve(ve.bytes,new Uint8Array(0),1);_d[96]=new Ve(ve.string,"",1);_d[128]=new Ve(ve.array,0,1);_d[160]=new Ve(ve.map,0,1);_d[244]=new Ve(ve.false,!1,1);_d[245]=new Ve(ve.true,!0,1);_d[246]=new Ve(ve.null,null,1);function Oae(t){switch(t.type){case ve.false:return vd([244]);case ve.true:return vd([245]);case ve.null:return vd([246]);case ve.bytes:return t.value.length?void 0:vd([64]);case ve.string:return t.value===""?vd([96]):void 0;case ve.array:return t.value===0?vd([128]):void 0;case ve.map:return t.value===0?vd([160]):void 0;case ve.uint:return t.value<24?vd([Number(t.value)]):void 0;case ve.negint:if(t.value>=-24)return vd([31-Number(t.value)])}}var Mae=Object.freeze({float64:!0,mapSorter:Kae,quickEncodeToken:Oae});function Bae(){let t=[];return t[ve.uint.major]=Mf,t[ve.negint.major]=XI,t[ve.bytes.major]=iP,t[ve.string.major]=lae,t[ve.array.major]=eA,t[ve.map.major]=tA,t[ve.tag.major]=rA,t[ve.float.major]=sA,t}var Nae=Bae(),Uae=new zL,JN=class XL{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(`${qL} object contains circular references`);return new XL(r,e)}},Bu={null:new Ve(ve.null,null),undefined:new Ve(ve.undefined,void 0),true:new Ve(ve.true,!0),false:new Ve(ve.false,!1),emptyArray:new Ve(ve.array,0),emptyMap:new Ve(ve.map,0)},Wu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Ve(ve.float,t):t>=0?new Ve(ve.uint,t):new Ve(ve.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Ve(ve.uint,t):new Ve(ve.negint,t)},Uint8Array(t,e,r,n){return new Ve(ve.bytes,t)},string(t,e,r,n){return new Ve(ve.string,t)},boolean(t,e,r,n){return t?Bu.true:Bu.false},null(t,e,r,n){return Bu.null},undefined(t,e,r,n){return Bu.undefined},ArrayBuffer(t,e,r,n){return new Ve(ve.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Ve(ve.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Bu.emptyArray,new Ve(ve.break)]:Bu.emptyArray;n=JN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=k1(o,r,n);return r.addBreakTokens?[new Ve(ve.array,t.length),s,new Ve(ve.break)]:[new Ve(ve.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=JN.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++]=[k1(d,r,n),k1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(Lae(i,r),r.addBreakTokens?[new Ve(ve.map,i.length),i,new Ve(ve.break)]:[new Ve(ve.map,i.length),i]):r.addBreakTokens===!0?[Bu.emptyMap,new Ve(ve.break)]:Bu.emptyMap}};Wu.Map=Wu.Object;Wu.Buffer=Wu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Wu[`${t}Array`]=Wu.DataView;function k1(t,e={},r){let n=joe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Wu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Wu[n];if(!a)throw new Error(`${qL} unsupported type: ${n}`);return a(t,n,e,r)}function Lae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Kae(t,e){if(t[0]instanceof Ve&&e[0]instanceof Ve){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=ZN(r.value)),n._keyBytes||(n._keyBytes=ZN(n.value)),KL(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function ZN(t){return zae(t,Nae,Mae)}function eK(t,e,r,n){if(Array.isArray(e))for(let s of e)eK(t,s,r,n);else r[e.type.major](t,e,n)}var G$e=ve.uint.majorEncoded,W$e=ve.negint.majorEncoded,V$e=ve.bytes.majorEncoded,H$e=ve.string.majorEncoded,J$e=ve.array.majorEncoded,Z$e=ve.float.majorEncoded|GL,Y$e=ve.float.majorEncoded|WL,Q$e=ve.float.majorEncoded|VL,X$e=ve.float.majorEncoded|HL,e3e=BigInt(-1),t3e=BigInt(1);function zae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new qoe(n):Uae,o=k1(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 zL(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():LL(a.chunks[0])}}return a.reset(),eK(a,o,e,r),a.toBytes(!0)}var r3e=Symbol.for("DONE"),n3e=Symbol.for("BREAK"),YN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(YN||(YN={}));var Xs;(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"})(Xs||(Xs={}));var Go;(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"})(Go||(Go={}));var QN;(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"})(QN||(QN={}));var XN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(XN||(XN={}));var s3e={"P-256":Xs.P256,"P-384":Xs.P384,"P-521":Xs.P521,X25519:Xs.X25519,Ed25519:Xs.Ed25519,Ed448:Xs.Ed448,secp256k1:Xs.Secp256k1},i3e={[Xs.P256]:"P-256",[Xs.P384]:"P-384",[Xs.P521]:"P-521",[Xs.X25519]:"X25519",[Xs.Ed25519]:"Ed25519",[Xs.Ed448]:"Ed448",[Xs.Secp256k1]:"secp256k1"},o3e={EdDSA:Go.EdDSA,ES256:Go.ES256,ES384:Go.ES384,ES512:Go.ES512,ES256K:Go.ES256K},a3e={[Go.EdDSA]:"EdDSA",[Go.ES256]:"ES256",[Go.ES384]:"ES384",[Go.ES512]:"ES512",[Go.ES256K]:"ES256K"},eU;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(eU||(eU={}));var tU;(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"})(tU||(tU={}));var rU;(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"})(rU||(rU={}));var nU;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(nU||(nU={}));var qae={};NI(qae,{extractDidFragment:()=>Si,getServices:()=>Fae,getVerificationMethodByKey:()=>Gae,getVerificationMethodTypes:()=>tK,getVerificationMethods:()=>aP,getVerificationRelationshipsById:()=>rK,isDidService:()=>nK,isDidVerificationMethod:()=>H1,isDwnDidService:()=>Wae,isPortableDid:()=>Vae,keyBytesToMultibaseId:()=>sK,multibaseIdToKeyBytes:()=>iK});function Si(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Fae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Gae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=aP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await ur({jwk:e})===await ur({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function aP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(H1)??[]),Object.keys(rP).forEach(r=>{e.push(...t[r]?.filter(H1)??[])}),e}function tK({didDocument:t}){let e=aP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function rK({didDocument:t,methodId:e}){let r=[];return Object.keys(rP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=Si(e);s.some(o=>{let i=Si(o)===a,c=H1(o)&&Si(o.id)===a;return i||c})&&r.push(n)}}),r}function nK(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Wae(t){return!(!nK(t)||t.type!=="DecentralizedWebNode")}function H1(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 Vae(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 sK({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Ho.addPrefix({code:e,data:t,name:r}),s=Je.uint8Array(n).toBase58Btc();return Je.base58Btc(s).toMultibase()}function iK({multibaseKeyId:t}){try{let e=Je.multibase(t).toBase58Btc(),r=Je.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Ho.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new We("invalidDid",`Invalid multibase identifier: ${t}`)}}var Ec=class oK{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=>Si(o.id)===(Si(e?.methodId)??Si(this.document.assertionMethod?.[0])));if(!r?.publicKeyJwk)throw new We("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:Doe.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 Aa}){let n=aP({didDocument:e.document});if(n.length===0)throw new We("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 oK({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Dw=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()")}},aK=(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))(aK||{}),aA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(aA||{}),cK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(cK||{}),sU="0123456789abcdef",dK=[],iU=[];for(let t=0;t<256;t++)dK[t]=sU[t>>4&15]+sU[t&15],t<16&&(t<10?iU[48+t]=t:iU[87+t]=t);var Hae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=dK[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},oU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Yg=0;Yg<oU.length;Yg++)Zae[oU.charCodeAt(Yg)]=Yg;var Yg,Yae=new TextDecoder,uK=(t,e)=>e?new TextDecoder(e).decode(t):Yae.decode(t),Qae=new TextEncoder,kd=t=>Qae.encode(t),aU=typeof window<"u"?window:self,cU=aU.crypto||aU.msCrypto||{},c3e=cU.subtle||cU.webkitSubtle;function Cw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function lK(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 or(t,e,r){let n=[],s=null;return or._encode(n,t),s=Jae(n),or.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}or.bytes=-1;or._floatConversionDetected=!1;or._encode=function(t,e){if(e!=null)switch(lK(e)){case"object":or.dict(t,e);break;case"map":or.dictMap(t,e);break;case"array":or.list(t,e);break;case"set":or.listSet(t,e);break;case"string":or.string(t,e);break;case"number":or.number(t,e);break;case"boolean":or.number(t,e);break;case"arraybufferview":or.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":or.buffer(t,new Uint8Array(e));break}};var cP=new Uint8Array([101]),fK=new Uint8Array([100]),pK=new Uint8Array([108]);or.buffer=function(t,e){t.push(kd(e.length+":"),e)};or.string=function(t,e){t.push(kd(kd(e).byteLength+":"+e))};or.number=function(t,e){if(Number.isInteger(e))return t.push(kd("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(kd("i"+a+"e")),a!==e&&!or._floatConversionDetected&&(or._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())};or.dict=function(t,e){t.push(fK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(or.string(t,n),or._encode(t,e[n]));t.push(cP)};or.dictMap=function(t,e){t.push(fK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?or._encode(t,n):or.string(t,String(n)),or._encode(t,e.get(n)));t.push(cP)};or.list=function(t,e){let r=0,n=e.length;for(t.push(pK);r<n;r++)e[r]!=null&&or._encode(t,e[r]);t.push(cP)};or.listSet=function(t,e){t.push(pK);for(let r of e)r!=null&&or._encode(t,r);t.push(cP)};var Xae=or,ece=105,tce=58,rce=100,nce=108,cA=101;function hK(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 at(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),at.position=0,at.encoding=n||null,at.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):kd(t),at.bytes=at.data.length,at.next())}at.bytes=0;at.position=0;at.data=null;at.encoding=null;at.next=function(){switch(at.data[at.position]){case rce:return at.dictionary();case nce:return at.list();case ece:return at.integer();default:return at.buffer()}};at.find=function(t){let e=at.position,r=at.data.length,n=at.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)+"]")};at.dictionary=function(){at.position++;let t={};for(;at.data[at.position]!==cA;){let e=at.buffer(),r=uK(e);r.includes("\uFFFD")&&(r=Hae(e)),t[r]=at.next()}return at.position++,t};at.list=function(){at.position++;let t=[];for(;at.data[at.position]!==cA;)t.push(at.next());return at.position++,t};at.integer=function(){let t=at.find(cA),e=hK(at.data,at.position+1,t);return at.position+=t+1-at.position,e};at.buffer=function(){let t=at.find(tce),e=hK(at.data,at.position,t),r=++t+e;return at.position=r,at.encoding?uK(at.data.slice(t,r)):at.data.slice(t,r)};var sce=at;function ice(t){let e=2;for(let r of t)e+=dP(r);return e}function oce(t){let e=2;for(let[r,n]of t){let s=kd(r).byteLength;e+=Cw(s)+1+s,e+=dP(n)}return e}function ace(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=kd(r[n]).byteLength;e+=Cw(s)+1+s,e+=dP(t[r[n]])}return e}function cce(t){let e=kd(t).byteLength;return Cw(e)+1+e}function dce(t){let e=t.byteLength-t.byteOffset;return Cw(e)+1+e}function dP(t){if(t==null)return 0;let e=lK(t);switch(e){case"arraybufferview":return dce(t);case"string":return cce(t);case"array":case"set":return ice(t);case"number":return 1+Cw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return ace(t);case"map":return oce(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var mK=dP,uce=mK,yK={encode:Xae,decode:sce,byteLength:mK,encodingLength:uce},lce=/^(\d{1,3}\.){3,3}\d{1,3}$/,fce=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Pc={name:"v4",size:4,isFormat:t=>lce.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]}`}},Gu={name:"v6",size:16,isFormat:t=>t.length>0&&fce.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 gK(t){if(Pc.isFormat(t))return Pc.size;if(Gu.isFormat(t))return Gu.size;throw Error(`Invalid ip address: ${t}`)}function pce(t){return gK(t)===Pc.size?1:2}function hce(t,e,r){r=~~r;let n=gK(t);return typeof e=="function"&&(e=e(r+n)),n===Pc.size?Pc.encode(t,e,r):Gu.encode(t,e,r)}function mce(t,e,r){if(e=~~e,r=r||t.length-e,r===Pc.size)return Pc.decode(t,e,r);if(r===Gu.size)return Gu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Pc.size} for v4 or ${Gu.size} for v6.`)}function uP(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 xw(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 yce(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 gce(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 wK(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 vK(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 wce(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 dU(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 bK(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 Sw(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(bK(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 Sw.bytes=s-r,e}Sw.bytes=0;function jw(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 jw.bytes=r-e,n}jw.bytes=0;var Af=t=>t instanceof Uint8Array;function Vu(t){return typeof t=="string"?bK(t):t.byteLength}function dA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Sw(t)}function uA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Sw(e,t,r),Sw.bytes}var nw={},PK=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}`;PK[o]=i,nw[i]=o,nw[`${r}${s}`]=o,nw[`${e}${a}`]=o,nw[`${r}${a}`]=o}}function vce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=PK[a]}return n}function uU(t){return t.length>>>1}function bce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=nw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var Pce=Math.pow(2,24),xce=Math.pow(2,16),Sce=Math.pow(2,8),xd=(t,e)=>t[e]*Pce+t[e+1]*xce+t[e+2]*Sce+t[e+3],kt=(t,e)=>t[e]<<8|t[e+1],Sd=(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),Ze=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mo(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:Ece(t,e,r,n,s)}function Ece(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 kce=0,lU=32768,_I=32768,_ce=~_I,xK=32768,Tce=~xK;function $r({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Le=$r({encode(t,e,r){e||(e=new Uint8Array(Le.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,Le.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=kt(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(jw(t,e,e+i)),e+=i,a+=o?0:i}}return Le.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Vu(t.replace(/^\.|\.$/gm,""))+2}}),Yn=$r({encode(t,e,r){e||(e=new Uint8Array(Yn.encodingLength(t))),r||(r=0);let n=uA(e,t,r+1);return e[r]=n,Yn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=jw(t,e+1,e+1+r);return Yn.decode.bytes=r+1,n},encodingLength(t){return Vu(t)+1}}),jh=$r({bytes:12,encode(t,e,r){e||(e=new Uint8Array(jh.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?lU:kce;return Ze(e,t.id||0,r),Ze(e,n|s,r+2),Ze(e,t.questions.length,r+4),Ze(e,t.answers.length,r+6),Ze(e,t.authorities.length,r+8),Ze(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=kt(t,e+2);return{id:kt(t,e),type:r&lU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:gce(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:yce(r&15),questions:new Array(kt(t,e+4)),answers:new Array(kt(t,e+6)),authorities:new Array(kt(t,e+8)),additionals:new Array(kt(t,e+10))}},encodingLength(){return 12}}),_1=$r({encode(t,e,r){e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0);let n=t.length;return Ze(e,n,r),mo(t,e,r+2,0,n),_1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n=t.slice(e+2,e+2+r);return _1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),T1=$r({encode(t,e,r){return e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),Ze(e,Le.encode.bytes,r),T1.encode.bytes=Le.encode.bytes+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n=Le.decode(t,e+2);return T1.decode.bytes=r+2,n},encodingLength(t){return Le.encodingLength(t)+2}}),I1=$r({encode(t,e,r){e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mname,e,r),r+=Le.encode.bytes,Le.encode(t.rname,e,r),r+=Le.encode.bytes,Sd(e,t.serial||0,r),r+=4,Sd(e,t.refresh||0,r),r+=4,Sd(e,t.retry||0,r),r+=4,Sd(e,t.expire||0,r),r+=4,Sd(e,t.minimum||0,r),r+=4,Ze(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Le.decode(t,e),e+=Le.decode.bytes,n.rname=Le.decode(t,e),e+=Le.decode.bytes,n.serial=xd(t,e),e+=4,n.refresh=xd(t,e),e+=4,n.retry=xd(t,e),e+=4,n.expire=xd(t,e),e+=4,n.minimum=xd(t,e),e+=4,I1.decode.bytes=e-r,n},encodingLength(t){return 22+Le.encodingLength(t.mname)+Le.encodingLength(t.rname)}}),A1=$r({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])),!Af(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,mo(s,e,r,0,s.length),r+=s.length}),Ze(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=kt(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 A1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Vu(r)+1:e+=r.length+1}),e}}),R1=$r({encode(t,e,r){e||(e=new Uint8Array(R1.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 mo(t,e,r,0,s),r+=s,Ze(e,r-n-2,n),R1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=kt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,R1.decode.bytes=e-r,s},encodingLength(t){return t?(Af(t)?t.length:Vu(t))+2:2}}),D1=$r({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Yn.encode(t.cpu,e,r),r+=Yn.encode.bytes,Yn.encode(t.os,e,r),r+=Yn.encode.bytes,Ze(e,r-n-2,n),D1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Yn.decode(t,e),e+=Yn.decode.bytes,n.os=Yn.decode(t,e),e+=Yn.decode.bytes,D1.decode.bytes=e-r,n},encodingLength(t){return Yn.encodingLength(t.cpu)+Yn.encodingLength(t.os)+2}}),Lh=$r({encode(t,e,r){return e||(e=new Uint8Array(Lh.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),Ze(e,Le.encode.bytes,r),Lh.encode.bytes=Le.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Le.decode(t,e+2);return Lh.decode.bytes=Le.decode.bytes+2,r},encodingLength(t){return Le.encodingLength(t)+2}}),C1=$r({encode(t,e,r){e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0),Ze(e,t.priority||0,r+2),Ze(e,t.weight||0,r+4),Ze(e,t.port||0,r+6),Le.encode(t.target,e,r+8);let n=Le.encode.bytes+6;return Ze(e,n,r),C1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n={};return n.priority=kt(t,e+2),n.weight=kt(t,e+4),n.port=kt(t,e+6),n.target=Le.decode(t,e+8),C1.decode.bytes=r+2,n},encodingLength(t){return 8+Le.encodingLength(t.target)}}),zu=$r({encode(t,e,r){let n=zu.encodingLength(t);return e||(e=new Uint8Array(zu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=zu.ISSUER_CRITICAL),Ze(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Yn.encode(t.tag,e,r),r+=Yn.encode.bytes,uA(e,t.value,r),r+=Vu(t.value),zu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=kt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Yn.decode(t,e),e+=Yn.decode.bytes,s.value=jw(t,e,n+r),s.issuerCritical=!!(s.flags&zu.ISSUER_CRITICAL),zu.decode.bytes=r+2,s},encodingLength(t){return Yn.encodingLength(t.tag)+Yn.encodingLength(t.value)+2}});zu.ISSUER_CRITICAL=128;var j1=$r({encode(t,e,r){e||(e=new Uint8Array(j1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze(e,t.preference||0,r),r+=2,Le.encode(t.exchange,e,r),r+=Le.encode.bytes,Ze(e,r-n-2,n),j1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=kt(t,e),e+=2,n.exchange=Le.decode(t,e),e+=Le.decode.bytes,j1.decode.bytes=e-r,n},encodingLength(t){return 4+Le.encodingLength(t.exchange)}}),SK=$r({encode(t,e,r){return e||(e=new Uint8Array(SK.encodingLength(t))),r||(r=0),Ze(e,4,r),r+=2,Pc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Pc.decode(t,e)},bytes:6}),$1=$r({encode(t,e,r){return e||(e=new Uint8Array($1.encodingLength(t))),r||(r=0),Ze(e,16,r),r+=2,Gu.encode(t,e,r),$1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Gu.decode(t,e);return $1.decode.bytes=18,r},bytes:18}),fU=t=>new Uint8Array(t),bd=$r({encode(t,e,r){e||(e=new Uint8Array(bd.encodingLength(t))),r||(r=0);let n=r,s=dU(t.code);if(Ze(e,s,r),r+=2,t.data)Ze(e,t.data.length,r),r+=2,mo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||pce(t.ip,fU),i=hce(t.ip,fU),c=Math.ceil(a/8);Ze(e,c+4,r),r+=2,Ze(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,mo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Ze(e,2,r),r+=2,Ze(e,t.timeout,r),r+=2):(Ze(e,0,r),r+=2);break;case 12:{let a=t.length||0;Ze(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Ze(e,a,r),r+=2;for(let o of t.tags)Ze(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return bd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=kt(t,e),r.type=wce(r.code),e+=2;let n=kt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=kt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);mo(t,s,0,e,e+n-4),r.ip=mce(s)}break;case 11:n>0&&(r.timeout=kt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(kt(t,e)),e+=2}return bd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(dU(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}`)}}),qu=$r({encode(t,e,r){e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0);let n=r,s=Nh(t,bd);return Ze(e,s,r),r=dw(t,bd,e,r+2),qu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=kt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=bd.decode(t,e),e+=bd.decode.bytes,s-=bd.decode.bytes;return qu.decode.bytes=e-r,n},encodingLength(t){return 2+Nh(t||[],bd)}}),bc=$r({encode(t,e,r){e||(e=new Uint8Array(bc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Af(s))throw new Error("Key must be a Buffer");return r+=2,Ze(e,t.flags,r),r+=2,e[r]=bc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mo(s,e,r,0,s.length),r+=s.length,bc.encode.bytes=r-n,Ze(e,bc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);if(e+=2,n.flags=kt(t,e),e+=2,t[e]!==bc.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,bc.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.key)}});bc.PROTOCOL_DNSSEC=3;bc.ZONE_KEY=128;bc.SECURE_ENTRYPOINT=32768;var sw=$r({encode(t,e,r){e||(e=new Uint8Array(sw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Af(s))throw new Error("Signature must be a Buffer");return r+=2,Ze(e,xw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Sd(e,t.originalTTL,r),r+=4,Sd(e,t.expiration,r),r+=4,Sd(e,t.inception,r),r+=4,Ze(e,t.keyTag,r),r+=2,Le.encode(t.signersName,e,r),r+=Le.encode.bytes,mo(s,e,r,0,s.length),r+=s.length,sw.encode.bytes=r-n,Ze(e,sw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.typeCovered=uP(kt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=xd(t,e),e+=4,n.expiration=xd(t,e),e+=4,n.inception=xd(t,e),e+=4,n.keyTag=kt(t,e),e+=2,n.signersName=Le.decode(t,e),e+=Le.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,sw.decode.bytes=e-r,n},encodingLength(t){return 20+Le.encodingLength(t.signersName)+Vu(t.signature)}}),iw=$r({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mbox||".",e,r),r+=Le.encode.bytes,Le.encode(t.txt||".",e,r),r+=Le.encode.bytes,iw.encode.bytes=r-n,Ze(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Le.decode(t,e)||".",e+=Le.decode.bytes,n.txt=Le.decode(t,e)||".",e+=Le.decode.bytes,iw.decode.bytes=e-r,n},encodingLength(t){return 2+Le.encodingLength(t.mbox||".")+Le.encodingLength(t.txt||".")}}),ho=$r({encode(t,e,r){e||(e=new Uint8Array(ho.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=xw(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,mo(o,e,r,0,o.length),r+=o.length}return ho.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=uP(a<<8|i<<3|u);s.push(d)}}e+=o}return ho.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=xw(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}}),ow=$r({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.nextDomain,e,r),r+=Le.encode.bytes,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,ow.encode.bytes=r-n,Ze(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.nextDomain=Le.decode(t,e),e+=Le.decode.bytes,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Le.encodingLength(t.nextDomain)+ho.encodingLength(t.rrtypes)}}),aw=$r({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Af(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Af(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Ze(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,mo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,mo(a,e,r,0,a.length),r+=a.length,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,aw.encode.bytes=r-n,Ze(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=kt(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=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+ho.encodingLength(t.rrtypes)}}),cw=$r({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Af(s))throw new Error("Digest must be a Buffer");return r+=2,Ze(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mo(s,e,r,0,s.length),r+=s.length,cw.encode.bytes=r-n,Ze(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.keyTag=kt(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,cw.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.digest)}}),Bh=$r({encode(t,e,r){e||(e=new Uint8Array(Bh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=uU(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 bce(e,t.fingerprint,r,r+=s),Bh.encode.bytes=r-n,Ze(e,Bh.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=vce(t,e,e+s),e+=s,Bh.decode.bytes=e-r,n},encodingLength(t){return 4+uU(t.fingerprint)}});function TI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Bh.getFingerprintLengthForHashType=TI;function hI(t){switch(t.toUpperCase()){case"A":return SK;case"PTR":return Lh;case"CNAME":return Lh;case"DNAME":return Lh;case"TXT":return A1;case"NULL":return R1;case"AAAA":return $1;case"SRV":return C1;case"HINFO":return D1;case"CAA":return zu;case"NS":return T1;case"SOA":return I1;case"MX":return j1;case"OPT":return qu;case"DNSKEY":return bc;case"RRSIG":return sw;case"RP":return iw;case"NSEC":return ow;case"NSEC3":return aw;case"SSHFP":return Bh;case"DS":return cw}return _1}var zo=$r({encode(t,e,r){e||(e=new Uint8Array(zo.encodingLength(t))),r||(r=0);let n=r;if(Le.encode(t.name,e,r),r+=Le.encode.bytes,Ze(e,xw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Ze(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Ze(e,t.flags||0,r+6),r+=8,qu.encode(t.options||[],e,r),r+=qu.encode.bytes}else{let s=vK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Ze(e,s,r+2),Sd(e,t.ttl||0,r+4),r+=8;let a=hI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return zo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Le.decode(t,e),e+=Le.decode.bytes,r.type=uP(kt(t,e)),r.type==="OPT")r.udpPayloadSize=kt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=kt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=qu.decode(t,e+8),e+=8+qu.decode.bytes;else{let s=kt(t,e+2);r.ttl=xd(t,e+4),r.class=wK(s&_ce),r.flush=!!(s&_I);let a=hI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return zo.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Le.encodingLength(t.name)+8+hI(t.type).encodingLength(e)}}),Kh=$r({encode(t,e,r){e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0);let n=r;return Le.encode(t.name,e,r),r+=Le.encode.bytes,Ze(e,xw(t.type),r),r+=2,Ze(e,vK(t.class===void 0?"IN":t.class),r),r+=2,Kh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Le.decode(t,e),e+=Le.decode.bytes,n.type=uP(kt(t,e)),e+=2,n.class=wK(kt(t,e)),e+=2,n.class&xK&&(n.class&=Tce),Kh.decode.bytes=e-r,n},encodingLength(t){return Le.encodingLength(t.name)+4}}),Ice=1024,Ms={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(Ace(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),jh.encode(t,e,r),r+=jh.encode.bytes,r=dw(t.questions,Kh,e,r),r=dw(t.answers,zo,e,r),r=dw(t.authorities,zo,e,r),r=dw(t.additionals,zo,e,r),Ms.encode.bytes=r-s,n&&Q1.bytes!==e.length?e.slice(0,Q1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=jh.decode(t,e);return e+=jh.decode.bytes,e=g1(n.questions,Kh,t,e),e=g1(n.answers,zo,t,e),e=g1(n.authorities,zo,t,e),e=g1(n.additionals,zo,t,e),Ms.decode.bytes=e-r,n},encodingLength:function(t){return jh.encodingLength(t)+Nh(t.questions||[],Kh)+Nh(t.answers||[],zo)+Nh(t.authorities||[],zo)+Nh(t.additionals||[],zo)}};Ms.encode.bytes=0;Ms.decode.bytes=0;function J1(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 Z1={encode:function(t,e,r){return e=Ms.encode(J1(t,"query"),e,r),Z1.encode.bytes=Ms.encode.bytes,e},decode:function(t,e){let r=Ms.decode(t,e);return Z1.decode.bytes=Ms.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Ms.encodingLength(J1(t,"query"))}};Z1.encode.bytes=0;Z1.decode.bytes=0;var Y1={encode:function(t,e,r){return e=Ms.encode(J1(t,"response"),e,r),Y1.encode.bytes=Ms.encode.bytes,e},decode:function(t,e){let r=Ms.decode(t,e);return Y1.decode.bytes=Ms.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Ms.encodingLength(J1(t,"response"))}};Y1.encode.bytes=0;Y1.decode.bytes=0;var Q1=Ms.encode,II=Ms.decode,Ace=Ms.encodingLength;function EK(t){let e=Q1(t),r=new Uint8Array(2+e.byteLength);return Ze(r,e.byteLength),mo(e,r,2,0,e.length),EK.bytes=r.byteLength,r}EK.bytes=0;function kK(t){let e=kt(t,0);if(t.byteLength<e+2)return null;let r=II(t.slice(2));return kK.bytes=II.bytes,r}kK.bytes=0;function Nh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function dw(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 _K(t,e){let r=Je.uint8Array(t).toBase32Z();return new URL(r,e).href}async function TK(t,e,r){if(r)return fetch(t,e);try{return await oL(t,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof S1?new We("invalidGatewayUri",n.message):n}}async function Rce({gatewayUri:t,publicKeyBytes:e,allowPrivateGatewayUri:r=!1}){let n=Je.uint8Array(e).toBase32Z(),s=_K(e,t),a;try{if(a=await TK(s,{method:"GET",signal:AbortSignal.timeout(3e4)},r),!a.ok)throw new We("notFound",`Pkarr record not found for: ${n}`)}catch(i){throw i instanceof We?i:new We("internalError",`Failed to fetch Pkarr record: ${i.message}`)}let o=await a.arrayBuffer();if(!o)throw new We("notFound",`Pkarr record not found for: ${n}`);if(o.byteLength<72)throw new We("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${o.byteLength}`);if(o.byteLength>1072)throw new We("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${o.byteLength}`);return{k:e,seq:Number(new DataView(o).getBigUint64(64)),sig:new Uint8Array(o,0,64),v:new Uint8Array(o,72)}}async function Dce({gatewayUri:t,bep44Message:e,allowPrivateGatewayUri:r=!1}){let n=Je.uint8Array(e.k).toBase32Z(),s=_K(e.k,t),a=new Uint8Array(e.v.length+72);a.set(e.sig,0),new DataView(a.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),a.set(e.v,e.sig.length+8);let o;try{o=await TK(s,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:a,signal:AbortSignal.timeout(3e4)},r)}catch(i){throw i instanceof We?i:new We("internalError",`Failed to put Pkarr record for identifier ${n}: ${i.message}`)}return o.ok}async function Cce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Q1(t),a=yK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new We("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 jce({bep44Message:t}){let e=await $s.bytesToPublicKey({publicKeyBytes:t.k}),r=yK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await $s.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new We("invalidSignature","Invalid signature for DHT BEP44 message");return II(t.v)}var IK="dht";async function AK({didUri:t}){let e=lA({didUri:t});return await $s.bytesToPublicKey({publicKeyBytes:e})}function lA({didUri:t}){let e=ls.parse(t);if(!e)throw new We("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==IK)throw new We("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Je.base32Z(e.id).toUint8Array()}catch{throw new We("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new We("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function $ce({identityKey:t}){let e=await $s.publicKeyToBytes({publicKey:t}),r=Je.uint8Array(e).toBase32Z();return`did:${IK}:${r}`}function fA(t){let e={Ed25519:$s,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await Qs.publicKeyToBytes({publicKey:r});return await Qs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Qs.bytesToPublicKey,privateKeyToBytes:Qs.privateKeyToBytes,bytesToPrivateKey:Qs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await js.publicKeyToBytes({publicKey:r});return await js.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:js.bytesToPublicKey,privateKeyToBytes:js.privateKeyToBytes,bytesToPrivateKey:js.bytesToPrivateKey},X25519:Ch}[t];if(!e)throw new We("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function RK({newDid:t,previousDidProof:e}){let r=await AK({didUri:e.previousDid}),n=lA({didUri:t}),s=Je.base64Url(e.signature).toUint8Array();if(!await $s.verify({key:r,data:n,signature:s}))throw new We("invalidPreviousDidProof","The previous DID proof is invalid.")}var Oce=0,Nu=7200,O1=";",xi=",",DK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},CK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function Ew(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Je.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Ew(e)).join("");throw new We("internalError","Pkarr returned DNS TXT record with invalid data type")}function uw(t){return Ew(t).split(O1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function jK(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 Mce({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=Ew(a.data);r.alsoKnownAs=i.split(xi);break}case o.startsWith("cnt"):{let i=Ew(a.data);r.controller=i.includes(xi)?i.split(xi):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=uw(a.data),f=Je.base64Url(u).toUint8Array(),h=aA[Number(c)],p=await fA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||CK[Number(c)];let m=o==="k0"?"0":i===void 0?await ur({jwk:p}):i;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}=uw(a.data),l=u.includes(xi)?u.split(xi):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(xi)?p.split(xi):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=uw(a.data);n.types=i.split(xi).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(xi).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=uw(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 Bce({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 RK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Nu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Nu,data:t.alsoKnownAs.join(xi)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(xi):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Nu,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 DK))throw new We("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=Je.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${S}`];h!=="0"&&await ur({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==CK[m]&&w.push(`a=${p.alg}`),l.controller!==t.id&&w.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:w.join(O1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=Si(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,_])=>`${E}=${_}`).join(O1),w=jK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:w})});let u=[`v=${Oce}`];if(c.length&&u.push(`vm=${c.join(xi)}`),Object.keys(rP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=cK[d];u.push(`${f}=${l.join(xi)}`)}}),i.length&&u.push(`svc=${i.join(xi)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?aK[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Nu,data:`id=${d.join(xi)}`})}s.push({type:"TXT",name:"_did."+pU(t.id)+".",ttl:Nu,data:u.join(O1)});for(let d of r||[])a.push({type:"NS",name:"_did."+pU(t.id)+".",ttl:Nu,data:d+"."});return{id:0,type:"response",flags:Ice,answers:[...s,...a]}}function pU(t){return t.split(":")[2]}var Nce="https://enbox-did-dht.fly.dev";function Uce(){return U.DID_DHT_GATEWAY_URI||Nce}function Lce(){return U.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function hU(t,e){return{gatewayUri:t??Uce(),allowPrivateGatewayUri:e??Lce()}}var $K=class AI extends Dw{static async create({keyManager:e=new Aa,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in DK)))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 Uh.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?.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await ur({jwk:f});h=`${o}#${Si(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 Ec({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,allowPrivateGatewayUri:r.allowPrivateGatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Aa}){if(ls.parse(e.uri)?.method!==AI.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new We("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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>Si(a.id)===(Si(r)??Si(e.assertionMethod?.[0])));if(!s?.publicKeyJwk)throw new We("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r,allowPrivateGatewayUri:n}){let s=hU(r,n);return mU.put({did:e,...s})}static async resolve(e,r={}){let{gatewayUri:n,allowPrivateGatewayUri:s}=hU(r.gatewayUri,r.allowPrivateGatewayUri);try{await Uh.identifierToIdentityKey({didUri:e});let{didDocument:a,didDocumentMetadata:o}=await mU.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:s});return{...Bs,didDocument:a,didDocumentMetadata:o}}catch(a){if(!(a instanceof We))throw new Error(a);return{...Bs,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};$K.methodName="dht";var OK=$K,mU=class lw{static async get({didUri:e,gatewayUri:r,allowPrivateGatewayUri:n=!1}){let s=Uh.identifierToIdentityKeyBytes({didUri:e}),a=await lw.pkarrGet({gatewayUri:r,publicKeyBytes:s,allowPrivateGatewayUri:n}),o=await Uh.parseBep44GetMessage({bep44Message:a}),i=await lw.fromDnsPacket({didUri:e,dnsPacket:o});return i.didDocumentMetadata.versionId=a.seq.toString(),i}static async put({did:e,gatewayUri:r,allowPrivateGatewayUri:n=!1}){let s=await lw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),a=await Uh.createBep44PutMessage({dnsPacket:s,publicKeyBytes:Uh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),o=await lw.pkarrPut({gatewayUri:r,bep44Message:a,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o,versionId:a.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return Rce(e)}static async pkarrPut(e){return Dce(e)}static async fromDnsPacket(e){return Mce(e)}static async toDnsPacket(e){return Bce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Uh=class{static async createBep44PutMessage(t){return Cce(t)}static async identifierToIdentityKey(t){return AK(t)}static identifierToIdentityKeyBytes(t){return lA(t)}static async identityKeyToIdentifier(t){return $ce(t)}static keyConverter(t){return fA(t)}static async parseBep44GetMessage(t){return jce(t)}static parseTxtDataToObject(t){return uw(t)}static parseTxtDataToString(t){return Ew(t)}static async validatePreviousDidProof(t){return RK(t)}static chunkDataIfNeeded(t){return jK(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)}},d3e=new Uint8Array(0),Kce=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")},zce=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")}},qce=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 MK(this,t)}},Fce=class{constructor(t){this.decoders=t}or(t){return MK(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`)}},MK=(t,e)=>new Fce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Gce=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new zce(t,e,r),this.decoder=new qce(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},Wce=({name:t,prefix:e,encode:r,decode:n})=>new Gce(t,e,r,n),Vce=(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},Hce=(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},lP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Wce({prefix:e,name:t,encode(s){return Hce(s,n,r)},decode(s){return Vce(s,n,r,t)}}),u3e=lP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),l3e=lP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yU=lP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),f3e=lP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Gh=class M1{static encode(e){return yU.baseEncode(e)}static decodeAsBytes(e,r){if(!M1.isBase64UrlString(e))throw new Dn(Rn.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return yU.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)}},Jce=Rf($ne(),1),RI;(function(t){t.Public="public",t.Private="private"})(RI||(RI={}));var vc=RI,lo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===vc.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===vc.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(!Gh.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 Ia=pA,Zce=Rf(One(),1),kw=class DI{static canonicalizeAsBytes(e){let r=DI.removeAllUndefinedProperties(e),n=Zce.default(r);return Gh.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}},Yce=BK,gU=128,Qce=127,Xce=~Qce,ede=Math.pow(2,31);function BK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=ede;)e[r++]=t&255|gU,t/=128;for(;t&Xce;)e[r++]=t&255|gU,t>>>=7;return e[r]=t|0,BK.bytes=r-n+1,e}var tde=CI,rde=128,wU=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&wU)<<s:(o&wU)*Math.pow(2,s),s+=7}while(o>=rde);return CI.bytes=a-n,r}var nde=Math.pow(2,7),sde=Math.pow(2,14),ide=Math.pow(2,21),ode=Math.pow(2,28),ade=Math.pow(2,35),cde=Math.pow(2,42),dde=Math.pow(2,49),ude=Math.pow(2,56),lde=Math.pow(2,63),fde=function(t){return t<nde?1:t<sde?2:t<ide?3:t<ode?4:t<ade?5:t<cde?6:t<dde?7:t<ude?8:t<lde?9:10},pde={encode:Yce,decode:tde,encodingLength:fde},hde=pde,X1=hde,vU=(t,e=0)=>[X1.decode(t,e),X1.decode.bytes],bU=(t,e,r=0)=>(X1.encode(t,e,r),e),PU=t=>X1.encodingLength(t),xU=(t,e)=>{let r=e.byteLength,n=PU(t),s=n+PU(r),a=new Uint8Array(s+r);return bU(t,a,0),bU(r,a,n),a.set(e,s),new NK(t,r,e,a)},mde=t=>{let e=Kce(t),[r,n]=vU(e),[s,a]=vU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new NK(r,s,o,e)},NK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},UK=({name:t,code:e,encode:r})=>new yde(t,e,r),yde=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?xU(this.code,e):e.then(r=>xU(this.code,r))}else throw Error("Unknown type, must be binary type")}},LK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),SU=UK({name:"sha2-256",code:18,encode:LK("SHA-256")}),p3e=UK({name:"sha2-512",code:19,encode:LK("SHA-512")}),Qg=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())})},po=class fw{static hash(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield SU.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 Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield SU.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 Qg(this,void 0,void 0,function*(){let n=kw.canonicalizeAsBytes(e);return yield fw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=kw.canonicalizeAsBytes(e),s=yield fw.hashAsNonMultihashBytes(n,r);return yield fw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=yield fw.hash(e,r);return Gh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Gh.decodeAsBytes(e,r);try{n=mde(s)}catch{throw new Dn(Rn.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Ia.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 Dh=$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())})},KK=class Lo{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;lo.validateEs256kOperationKey(r,vc.Public),lo.validateEs256kOperationKey(n,vc.Public),Lo.validateDidDocumentKeys(s),Lo.validateServices(a);let o=Ia.hashAlgorithmInMultihashCode,i=[{action:Dh.Replace,document:e.document}],c={updateCommitment:yield po.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Lo.validateDeltaSize(c);let u={deltaHash:yield po.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:w1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return v1(this,void 0,void 0,function*(){Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public);let r=Ia.hashAlgorithmInMultihashCode,n=yield po.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*(){Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextRecoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Lo.validateDidDocumentKeys(e.document.publicKeys),Lo.validateServices(e.document.services);let r=Ia.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Dh.Replace,document:e.document}],a=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield po.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield po.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(Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.updatePublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Lo.validateServices(e.servicesToAdd),Lo.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)lo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)lo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Dh.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Dh.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Dh.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Dh.RemovePublicKeys,ids:o};r.push(p)}let i=Ia.hashAlgorithmInMultihashCode,c=yield po.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield po.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){po.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(lo.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),lo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Lo.validateService(n),r.has(n.id))throw new Dn(Rn.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){lo.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"&&Jce.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=kw.canonicalizeAsBytes(e);if(r.length>Ia.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Ia.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Dn(Rn.DeltaExceedsMaximumSize,n)}}},EU=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())})},gde=class zK{static createLongFormDid(e){return EU(this,void 0,void 0,function*(){let r=yield KK.createCreateRequest(e),n=yield zK.computeDidUniqueSuffix(r.suffixData),s;Ia.network===void 0||Ia.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Ia.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=kw.canonicalizeAsBytes(a),i=Gh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return EU(this,void 0,void 0,function*(){let r=kw.canonicalizeAsBytes(e),n=yield po.hash(r,Ia.hashAlgorithmInMultihashCode);return Gh.encode(n)})}},Cs=2n**255n-19n,B1=2n**252n+27742317777372353535851937790883648493n,OI=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,MI=0x6666666666666666666666666666666666666666666666666666666666666658n,b1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Cs,n:B1,h:8,Gx:OI,Gy:MI},Ui=(t="")=>{throw new Error(t)},qK=t=>typeof t=="string",hA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Ui("Uint8Array expected"):t,Wh=t=>new Uint8Array(t),wde=(t,e)=>hA(qK(t)?yA(t):Wh(t),e),Xe=(t,e=Cs)=>{let r=t%e;return r>=0n?r:e+r},kU=t=>t instanceof Vh?t:Ui("Point expected"),_U,Vh=class $h{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new $h(e.x,e.y,1n,Xe(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=b1;e=wde(e,32);let s=e.slice();s[31]=e[31]&-129;let a=bde(s);a===0n||(r&&!(0n<a&&a<Cs)&&Ui("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Ui("bad y coord 2"));let o=Xe(a*a),i=Xe(o-1n),c=Xe(n*o+1n),{isValid:u,value:d}=xde(i,c);u||Ui("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=Xe(-d)),new $h(d,a,1n,Xe(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}=kU(e),c=Xe(r*i),u=Xe(a*s),d=Xe(n*i),l=Xe(o*s);return c===u&&d===l}is0(){return this.equals(N1)}negate(){return new $h(Xe(-this.ex),this.ey,this.ez,Xe(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=b1,a=Xe(e*e),o=Xe(r*r),i=Xe(2n*Xe(n*n)),c=Xe(s*a),u=e+r,d=Xe(Xe(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=Xe(d*f),m=Xe(l*h),y=Xe(d*h),S=Xe(f*l);return new $h(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=kU(e),{a:d,d:l}=b1,f=Xe(r*o),h=Xe(n*i),p=Xe(a*l*u),m=Xe(s*c),y=Xe((r+n)*(o+i)-f-h),S=Xe(m-p),w=Xe(m+p),E=Xe(h-d*f),_=Xe(y*S),I=Xe(w*E),D=Xe(y*E),N=Xe(S*w);return new $h(_,I,N,D)}mul(e,r=!0){if(e===0n)return r===!0?Ui("cannot multiply by 0"):N1;if(typeof e=="bigint"&&0n<e&&e<B1||Ui("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(eP))return kde(e).p;let n=N1,s=eP;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(B1/2n,!1).double();return B1%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=GK(n);return Xe(n*s)!==1n&&Ui("invalid inverse"),{x:Xe(e*s),y:Xe(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=vde(r);return n[31]|=e&1n?128:0,n}toHex(){return mA(this.toRawBytes())}};Vh.BASE=new Vh(OI,MI,1n,Xe(OI*MI));Vh.ZERO=new Vh(0n,1n,1n,0n);var{BASE:eP,ZERO:N1}=Vh,FK=(t,e)=>t.toString(16).padStart(e,"0"),mA=t=>Array.from(t).map(e=>FK(e,2)).join(""),yA=t=>{let e=t.length;(!qK(t)||e%2)&&Ui("hex invalid 1");let r=Wh(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)&&Ui("hex invalid 2"),r[n]=o}return r},vde=t=>yA(FK(t,32*2)).reverse(),bde=t=>BigInt("0x"+mA(Wh(hA(t)).reverse())),TU=(...t)=>{let e=Wh(t.reduce((n,s)=>n+hA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},GK=(t,e=Cs)=>{(t===0n||e<=0n)&&Ui("no inverse n="+t+" mod="+e);let r=Xe(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?Xe(s,e):Ui("no inverse")},yc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Cs;return r},Pde=t=>{let e=t*t%Cs*t%Cs,r=yc(e,2n)*e%Cs,n=yc(r,1n)*t%Cs,s=yc(n,5n)*n%Cs,a=yc(s,10n)*s%Cs,o=yc(a,20n)*a%Cs,i=yc(o,40n)*o%Cs,c=yc(i,80n)*i%Cs,u=yc(c,80n)*i%Cs,d=yc(u,10n)*s%Cs;return{pow_p_5_8:yc(d,2n)*t%Cs,b2:e}},IU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,xde=(t,e)=>{let r=Xe(e*e*e),n=Xe(r*r*e),s=Pde(t*n).pow_p_5_8,a=Xe(t*r*s),o=Xe(e*a*a),i=a,c=Xe(a*IU),u=o===t,d=o===Xe(-t),l=o===Xe(-t*IU);return u&&(a=i),(d||l)&&(a=c),(Xe(a)&1n)===1n&&(a=Xe(-a)),{isValid:u||d,value:a}},mI,AU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Sde={bytesToHex:mA,hexToBytes:yA,concatBytes:TU,mod:Xe,invert:GK,randomBytes:t=>{let e=AU();return e||Ui("crypto.getRandomValues must be defined"),e.getRandomValues(Wh(t))},sha512Async:async(...t)=>{let e=AU();e||Ui("crypto.subtle or etc.sha512Async must be defined");let r=TU(...t);return Wh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(Sde,{sha512Sync:{configurable:!1,get(){return mI},set(t){mI||(mI=t)}}});var bf=8,Ede=()=>{let t=[],e=256/bf+1,r=eP,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(bf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},kde=t=>{let e=_U||(_U=Ede()),r=(d,l)=>{let f=l.negate();return d?f:l},n=N1,s=eP,a=1+256/bf,o=2**(bf-1),i=BigInt(2**bf-1),c=2**bf,u=BigInt(bf);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,_f=gA-0x1000003d1n,wA=gA-0x14551231950b75fc4402da1732fc9bebfn,WK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,VK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,HK={p:_f,n:wA,a:0n,b:7n,Gx:WK,Gy:VK},zh=32,RU=t=>Ge(Ge(t*t)*t+HK.b),us=(t="")=>{throw new Error(t)},fP=t=>typeof t=="bigint",JK=t=>typeof t=="string",yI=t=>fP(t)&&0n<t&&t<_f,ZK=t=>fP(t)&&0n<t&&t<wA,YK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?us("Uint8Array expected"):t,_w=t=>new Uint8Array(t),vA=(t,e)=>YK(JK(t)?pP(t):_w(t),e),Ge=(t,e=_f)=>{let r=t%e;return r>=0n?r:e+r},DU=t=>t instanceof Hh?t:us("Point expected"),CU,Hh=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=jU(s,0,zh),o=e.length;if(o===33&&[2,3].includes(n)){yI(a)||us("Point hex invalid: x not FE");let i=_de(RU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=Ge(-i)),r=new Oh(a,i,1n)}return o===65&&n===4&&(r=new Oh(a,jU(s,zh,2*zh),1n)),r?r.ok():us("Point is not on curve")}static fromPrivateKey(e){return yw.mul(Tde(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}=DU(e),c=Ge(r*i),u=Ge(a*s),d=Ge(n*i),l=Ge(o*s);return c===u&&d===l}negate(){return new Oh(this.px,Ge(-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}=DU(e),{a:c,b:u}=HK,d=0n,l=0n,f=0n,h=Ge(u*3n),p=Ge(r*a),m=Ge(n*o),y=Ge(s*i),S=Ge(r+n),w=Ge(a+o);S=Ge(S*w),w=Ge(p+m),S=Ge(S-w),w=Ge(r+s);let E=Ge(a+i);return w=Ge(w*E),E=Ge(p+y),w=Ge(w-E),E=Ge(n+s),d=Ge(o+i),E=Ge(E*d),d=Ge(m+y),E=Ge(E-d),f=Ge(c*w),d=Ge(h*y),f=Ge(d+f),d=Ge(m-f),f=Ge(m+f),l=Ge(d*f),m=Ge(p+p),m=Ge(m+p),y=Ge(c*y),w=Ge(h*w),m=Ge(m+y),y=Ge(p-y),y=Ge(c*y),w=Ge(w+y),p=Ge(m*w),l=Ge(l+p),p=Ge(E*w),d=Ge(S*d),d=Ge(d-p),p=Ge(S*m),f=Ge(E*f),f=Ge(f+p),new Oh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return U1;if(ZK(e)||us("invalid scalar"),this.equals(yw))return Dde(e).p;let n=U1,s=yw;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(U1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=XK(n);return Ge(n*s)!==1n&&us("invalid inverse"),{x:Ge(e*s),y:Ge(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!yI(e)||!yI(r))&&us("Point invalid: x or y"),Ge(r*r)===RU(e)?this:us("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")+$U(r)+(e?"":$U(n))}toRawBytes(e=!0){return pP(this.toHex(e))}};Hh.BASE=new Hh(WK,VK,1n);Hh.ZERO=new Hh(0n,1n,0n);var{BASE:yw,ZERO:U1}=Hh,QK=(t,e)=>t.toString(16).padStart(e,"0"),bA=t=>Array.from(t).map(e=>QK(e,2)).join(""),pP=t=>{let e=t.length;(!JK(t)||e%2)&&us("hex invalid 1");let r=_w(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)&&us("hex invalid 2"),r[n]=o}return r},hP=t=>BigInt("0x"+(bA(t)||"0")),jU=(t,e,r)=>hP(t.slice(e,r)),PA=t=>fP(t)&&t>=0n&&t<gA?pP(QK(t,2*zh)):us("bigint expected"),$U=t=>bA(PA(t)),OU=(...t)=>{let e=_w(t.reduce((n,s)=>n+YK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},XK=(t,e=_f)=>{(t===0n||e<=0n)&&us("no inverse n="+t+" mod="+e);let r=Ge(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?Ge(s,e):us("no inverse")},_de=t=>{let e=1n;for(let r=t,n=(_f+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%_f),r=r*r%_f;return Ge(e*e)===t?e:us("sqrt invalid")},Tde=t=>(fP(t)||(t=hP(vA(t,zh))),ZK(t)?t:us("private key out of range")),MU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,L1;function Ide(t){t=vA(t);let e=zh+8;(t.length<e||t.length>1024)&&us("expected proper params");let r=Ge(hP(t),wA-1n)+1n;return PA(r)}var Ade={hexToBytes:pP,bytesToHex:bA,concatBytes:OU,bytesToNumberBE:hP,numberToBytesBE:PA,mod:Ge,invert:XK,hmacSha256Async:async(t,...e)=>{let r=MU();if(!r)return us("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return _w(await n.sign("HMAC",s,OU(...e)))},hmacSha256Sync:L1,hashToPrivateKey:Ide,randomBytes:t=>{let e=MU();return e||us("crypto.getRandomValues must be defined"),e.getRandomValues(_w(t))}};Object.defineProperties(Ade,{hmacSha256Sync:{configurable:!1,get(){return L1},set(t){L1||(L1=t)}}});var Pf=8,Rde=()=>{let t=[],e=256/Pf+1,r=yw,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},Dde=t=>{let e=CU||(CU=Rde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=U1,s=yw,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}},BU;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(BU||(BU={}));var NU;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(NU||(NU={}));var Xg=class wf{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 wf.createIonDocument({services:n,verificationMethods:s}),o=wf.normalizeJwk(e),i=wf.normalizeJwk(r);return await gde.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await KK.createCreateRequest({document:e,recoveryKey:wf.normalizeJwk(r),updateKey:wf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await ur({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:wf.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}},Cde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(Cde||{}),jde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},UU="https://ion.tbd.engineering",$de=class pw extends Dw{static async create({keyManager:e=new Aa,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in jde)))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 Xg.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await pw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ec({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 pw.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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!s?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==pw.methodName)throw new We("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=UU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:rK({didDocument:e.document,methodId:o.id})}))??[],s=await Xg.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await Xg.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=Xg.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{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==pw.methodName)return{...Bs,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??UU;try{let a=Xg.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new We("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...Bs,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof We))throw new Error(a);return{...Bs,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};$de.methodName="ion";var e9=class hw extends Dw{static async create({keyManager:e=new Aa,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=Je.object(a).toBase64Url(),i=`did:${hw.methodName}:${o}`,c=(await hw.resolve(i)).didDocument;return new Ec({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 We("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==hw.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new We("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?Je.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...Bs,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{...Bs,didDocument:a}}};e9.methodName="jwk";var t9=e9,Ode={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},K1=class Mh{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=Mh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ho.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":Qs.compressPublicKey,secp256k1:js.compressPublicKey}[e];if(!r)throw new We("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:$s,"P-256":Qs,secp256k1:js}[e];if(!r)throw new We("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?Ho.getNameFromCode({code:e}):r;let n=r,s=Mh.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 Ode))throw new We("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Mh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Mh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Mh.jwkToMulticodec({jwk:e});return sK({keyBytes:r,multicodecName:n})}};K1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},K1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},K1.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=K1,Mde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(Mde||{}),LU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},r9=class Ku extends Dw{static async create({keyManager:e=new Aa,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:${Ku.methodName}:${o}`,c=(await Ku.resolve(i,r)).didDocument;return new Ec({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 We("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!s?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==Ku.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new We("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await Ku.createDocument({didUri:e,options:r});return{...Bs,didDocument:n}}catch(n){if(!(n instanceof We))throw new Error(n);return{...Bs,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 We("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==Ku.methodName)throw new We("methodNotSupported",`Method not supported: ${i.method}`);if(!Ku.validateIdentifier(i))throw new We("invalidDid",`Invalid DID URI: ${e}`);let u=await Ku.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 tK({didDocument:o}).forEach(l=>{let f=LU[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}=iK({multibaseKeyId:r}),d=i.byteLength,l=P1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new We("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await js.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new We("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new We("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in LU))throw new We("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new We("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&&gI(n)==="String"&&n.startsWith("z")}};r9.methodName="key";var $w=r9,Bde=3e4,n9=class z1 extends Dw{static async create({keyManager:e=new Aa,options:r}){if(!r.domain)throw new We("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:${z1.methodName}:${n}`;if(!ls.parse(s))throw new We("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 Ec({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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=Si(r)??Si(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>Si(o.id)===s):e.verificationMethod?.[0];if(!a?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==z1.methodName)throw new We("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=ls.parse(e);if(!n)return{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==z1.methodName)return{...Bs,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=await oL(a,{signal:AbortSignal.timeout(Bde)},{description:"did:web document URL"});if(!o.ok)throw new Error("HTTP error status code returned");let i=await o.json();return{...Bs,didDocument:i}}catch{return{...Bs,didResolutionMetadata:{error:"notFound"}}}}};n9.methodName="web";var s9=n9,h3e=Rf(ZU(),1),m3e=Rf(YU(),1);var Nde=Rf(YU(),1),i9=class{constructor({ttl:t="15m"}={}){this.cache=new Bne.default({ttl:(0,Nde.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(){}},Ude={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()}},o9=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=t||Ude;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{...Bs,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...Bs,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};if(e!==void 0)return n.resolve(r.uri,e);let s=await this.cache.get(r.uri);if(s)return s;let a=this._inFlight.get(r.uri);if(a)return a;let o=(async()=>{let i=await n.resolve(r.uri,e);if(!i.didResolutionMetadata.error)try{await this.cache.set(r.uri,i)}catch{}return i})();this._inFlight.set(r.uri,o);try{return await o}finally{this._inFlight.delete(r.uri)}}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:{}}}};Jt();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 Rh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new c1(e.resumableTaskStore,this.storageController),this._coreProtocols=new ag,this._coreProtocols.register(new kr);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 o9({didResolvers:[OK,t9,$w,s9],cache:new i9}),e.ownsResolver=!0),e.tenantGate??=new cg;let r=new t(e);return await r.open(),r}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,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{ge.validateJsonSchema(e)}catch(s){return ot(s,400)}}};ut();Jt();pn();Dy();wi();v();function Lde(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,Lde(e)]):t}Ba();sr();fa();_0();Mn();c0();r2();Za();gi();FE();Al();v();Xm();v();import{Level as Kde}from"level";async function Ki(t,e){return new Kde(t,{...e,keyEncoding:"utf8"})}var Ra=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...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 Bf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...e},this.db=r??new Ra({...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),Nt.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:Nt.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()}};v();Vd();v();var IP=Kn(_o(),1);v();function zde(t){return t[Symbol.asyncIterator]!=null}function qde(t){if(zde(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 a9=qde;Fc();v();Tp();To();var q9=Kn(_o(),1);fy();v();Qu();rp();var c9=0,Fde="identity",d9=Yo,Gde=t=>sl(c9,d9(t)),u9={code:c9,name:Fde,encode:d9,digest:Gde};v();Tp();var l9=Kn(_o(),1);Fc();var Wde=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=G2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=Nt.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,l9.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}}}},f9=Wde;v();var p9=Kn(_o(),1);rp();Wc();v();function Vde(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 Nf=Vde;v();var Ow=Kn(_o(),1),Hde=(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}},Qh=Hde;var Jde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new yn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Zde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,p9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=a0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Jde(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},h9=Zde;v();var m9=Kn(_o(),1);Wc();var Yde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new yn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Qde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,m9.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:Yde(c),depth:a,size:BigInt(c.length),node:c}}},y9=Qde;v();To();var qw=Kn(_o(),1);Zd();v();To();GS();WS();var Xde=async function(t){return(await dv.encode(t)).slice(0,8).reverse()},eue=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 Ga({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},g9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),tue=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},w9=async(t,e,r,n,s)=>{if(n==null){let d=fv({hashFn:Xde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await eue(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=g9(a.pos),i=tue(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=g9(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=Gc(u),w9(t,e,r,n,s)},v9=w9;v();v();v();function rue(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 mP=rue;function nue(t){return t[Symbol.asyncIterator]!=null}function sue(t,e){let r=0;if(nue(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=mP(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 b9=sue;v();function iue(t){return t[Symbol.asyncIterator]!=null}function oue(t,e){let r=0;if(iue(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=mP(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 Xh=oue;v();v();function zi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var yP=globalThis.CustomEvent??Event;async function*Uf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=zi(),i=zi(),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=zi(),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 yP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new yP("task-complete"))})}c=!0,s.dispatchEvent(new yP("task-complete"))}catch(p){u=p,s.dispatchEvent(new yP("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=zi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}v();v();v();var gP=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}},em=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new gP(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 gP(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 wP(t={}){return aue(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 aue(t,e){e=e??{};let r=e.onEnd,n=new em,s,a,o,i=zi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=w=>{a=null,n.push(w);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=zi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new em,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 em,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 w,E;S!=null&&(w=new Promise((_,I)=>{E=()=>{I(new SA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,w])}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}v();v();v();function cue(t){return t.reason}async function P9(t,e,r){if(e==null)return t;let n=r?.translateError??cue;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=zi(),this.haveNext=zi()}[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=zi(),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=zi(),await P9(this.readNext.promise,r?.signal,r)}};function x9(){return new EA}function due(t){return t[Symbol.asyncIterator]!=null}async function uue(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*lue(t){let e=new AbortController,r=x9();uue(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*fue(t){for(let e of t)yield*e}function pue(...t){let e=[];for(let r of t)due(r)||e.push(r);return e.length===t.length?fue(e):lue(t)}var S9=pue;function tm(t,...e){if(t==null)throw new Error("Empty pipeline");if(kA(t)){let n=t;t=()=>n.source}else if(k9(t)||E9(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]=mue(r[n]));return hue(...r)}var hue=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},E9=t=>t?.[Symbol.asyncIterator]!=null,k9=t=>t?.[Symbol.iterator]!=null,kA=t=>t==null?!1:t.sink!=null&&t.source!=null,mue=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=wP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(E9(a))s=async function*(){yield*a,n.end()};else if(k9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return S9(n,s())}return t.source};Wc();var yue=(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 yn("unixfs:exporter:walk:directory",{cid:t})),yield*tm(l,f=>Xh(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Uf(f,{ordered:!0}),f=>b9(f,h=>h!=null))}return i},_9=yue;v();To();var Kf=Kn(_o(),1);Zd();fy();v();v();var TA=Kn(I9(),1);v();var Bw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},IA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},A9=t=>globalThis.DOMException===void 0?new IA(t):new DOMException(t),R9=t=>{let e=t.reason===void 0?A9("This operation was aborted."):t.reason;return e instanceof Error?e:A9(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(R9(c)),c.addEventListener("abort",()=>{i(R9(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 Bw(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}v();v();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 Lf=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)},Td,DA=class{constructor(){Td.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Lf(this,Td,"f")[this.size-1].priority>=r.priority){Lf(this,Td,"f").push(n);return}let s=RA(Lf(this,Td,"f"),n,(a,o)=>o.priority-a.priority);Lf(this,Td,"f").splice(s,0,n)}dequeue(){let e=Lf(this,Td,"f").shift();return e?.run}filter(e){return Lf(this,Td,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Lf(this,Td,"f").length}};Td=new WeakMap;var D9=DA;var ln=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},Ke=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,Uw,Lw,Ju,kP,Kw,bP,Da,Nw,go,PP,wo,zw,Hu,xP,C9,j9,M9,$9,O9,SP,CA,jA,_P,B9,EP,TP=class extends Error{},$A=class extends TA.default{constructor(e){var r,n,s,a;if(super(),jn.add(this),Uw.set(this,void 0),Lw.set(this,void 0),Ju.set(this,0),kP.set(this,void 0),Kw.set(this,void 0),bP.set(this,0),Da.set(this,void 0),Nw.set(this,void 0),go.set(this,void 0),PP.set(this,void 0),wo.set(this,0),zw.set(this,void 0),Hu.set(this,void 0),xP.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:D9,...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})`);ln(this,Uw,e.carryoverConcurrencyCount,"f"),ln(this,Lw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),ln(this,kP,e.intervalCap,"f"),ln(this,Kw,e.interval,"f"),ln(this,go,new e.queueClass,"f"),ln(this,PP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,ln(this,xP,e.throwOnTimeout===!0,"f"),ln(this,Hu,e.autoStart===!1,"f")}get concurrency(){return Ke(this,zw,"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})`);ln(this,zw,e,"f"),Ke(this,jn,"m",_P).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ke(this,xP,"f"),...r},new Promise((n,s)=>{Ke(this,go,"f").enqueue(async()=>{var a,o,i;ln(this,wo,(o=Ke(this,wo,"f"),o++,o),"f"),ln(this,Ju,(i=Ke(this,Ju,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new TP("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,Ke(this,jn,"m",B9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Bw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ke(this,jn,"m",M9).call(this)}},r),this.emit("add"),Ke(this,jn,"m",SP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ke(this,Hu,"f")?(ln(this,Hu,!1,"f"),Ke(this,jn,"m",_P).call(this),this):this}pause(){ln(this,Hu,!0,"f")}clear(){ln(this,go,new(Ke(this,PP,"f")),"f")}async onEmpty(){Ke(this,go,"f").size!==0&&await Ke(this,jn,"m",EP).call(this,"empty")}async onSizeLessThan(e){Ke(this,go,"f").size<e||await Ke(this,jn,"m",EP).call(this,"next",()=>Ke(this,go,"f").size<e)}async onIdle(){Ke(this,wo,"f")===0&&Ke(this,go,"f").size===0||await Ke(this,jn,"m",EP).call(this,"idle")}get size(){return Ke(this,go,"f").size}sizeBy(e){return Ke(this,go,"f").filter(e).length}get pending(){return Ke(this,wo,"f")}get isPaused(){return Ke(this,Hu,"f")}};Uw=new WeakMap,Lw=new WeakMap,Ju=new WeakMap,kP=new WeakMap,Kw=new WeakMap,bP=new WeakMap,Da=new WeakMap,Nw=new WeakMap,go=new WeakMap,PP=new WeakMap,wo=new WeakMap,zw=new WeakMap,Hu=new WeakMap,xP=new WeakMap,jn=new WeakSet,C9=function(){return Ke(this,Lw,"f")||Ke(this,Ju,"f")<Ke(this,kP,"f")},j9=function(){return Ke(this,wo,"f")<Ke(this,zw,"f")},M9=function(){var e;ln(this,wo,(e=Ke(this,wo,"f"),e--,e),"f"),Ke(this,jn,"m",SP).call(this),this.emit("next")},$9=function(){Ke(this,jn,"m",jA).call(this),Ke(this,jn,"m",CA).call(this),ln(this,Nw,void 0,"f")},O9=function(){let e=Date.now();if(Ke(this,Da,"f")===void 0){let r=Ke(this,bP,"f")-e;if(r<0)ln(this,Ju,Ke(this,Uw,"f")?Ke(this,wo,"f"):0,"f");else return Ke(this,Nw,"f")===void 0&&ln(this,Nw,setTimeout(()=>{Ke(this,jn,"m",$9).call(this)},r),"f"),!0}return!1},SP=function(){if(Ke(this,go,"f").size===0)return Ke(this,Da,"f")&&clearInterval(Ke(this,Da,"f")),ln(this,Da,void 0,"f"),this.emit("empty"),Ke(this,wo,"f")===0&&this.emit("idle"),!1;if(!Ke(this,Hu,"f")){let e=!Ke(this,jn,"a",O9);if(Ke(this,jn,"a",C9)&&Ke(this,jn,"a",j9)){let r=Ke(this,go,"f").dequeue();return r?(this.emit("active"),r(),e&&Ke(this,jn,"m",CA).call(this),!0):!1}}return!1},CA=function(){Ke(this,Lw,"f")||Ke(this,Da,"f")!==void 0||(ln(this,Da,setInterval(()=>{Ke(this,jn,"m",jA).call(this)},Ke(this,Kw,"f")),"f"),ln(this,bP,Date.now()+Ke(this,Kw,"f"),"f"))},jA=function(){Ke(this,Ju,"f")===0&&Ke(this,wo,"f")===0&&Ke(this,Da,"f")&&(clearInterval(Ke(this,Da,"f")),ln(this,Da,void 0,"f")),ln(this,Ju,Ke(this,Uw,"f")?Ke(this,wo,"f"):0,"f"),Ke(this,jn,"m",_P).call(this)},_P=function(){for(;Ke(this,jn,"m",SP).call(this););},B9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new TP("The task was aborted."))},{once:!0})})},EP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var N9=$A;Wc();async function U9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Nf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,Kf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=ss.unmarshal(e.Data)}catch(u){throw(0,Kf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Nf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,Kf.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 tm(c,u=>Xh(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Uf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case sy:h=Gc(l);break;case Yd:h=l;break;default:r.end((0,Kf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new N9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new yn("unixfs:exporter:walk:file",{cid:d.Hash})),await U9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var vue=(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}=Qh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=wP();c.onProgress?.(new yn("unixfs:exporter:walk:file",{cid:t})),U9(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,Kf.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 yn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,Kf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},OA=vue;v();To();Wc();var bue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new yn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),L9(e,n,s,a,o,c)}return i};async function*L9(t,e,r,n,s,a){let o=t.Links,i=tm(o,c=>Xh(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=Gc(l),a.onProgress?.(new yn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:L9(t,e,r,n,s,a)}}}),c=>Uf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var K9=bue;var Pue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,xue={raw:OA,file:OA,directory:_9,"hamt-sharded-directory":K9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},Sue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Gc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,qw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=ss.unmarshal(u.Data)}catch(h){throw(0,qw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await v9(u,n[0],o):h=Pue(u,n[0]),h==null)throw(0,qw.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=xue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,qw.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}},z9=Sue;var Eue={[sy]:z9,[Yd]:y9,[Wd]:f9,[u9.code]:h9},F9=async(t,e,r,n,s,a,o)=>{let i=Eue[t.code];if(i==null)throw(0,q9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,F9,s,a,o)},G9=F9;var kue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),_ue=t=>{if(t instanceof Uint8Array)return{cid:Nt.decode(t),toResolve:[]};let e=Nt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=kue(t);return{cid:Nt.parse(r[0]),toResolve:r.slice(1)}}throw(0,IP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*Tue(t,e,r={}){let{cid:n,toResolve:s}=_ue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await G9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,IP.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 W9(t,e,r={}){let n=await a9(Tue(t,e,r));if(n==null)throw(0,IP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}JS();var MA=new TextEncoder,AP=new TextDecoder,BA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ki,...e},this.blockstore=new Bf({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(AP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(AP.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=my([{content:ns.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,MA.encode(JSON.stringify({dataSize:d}))),await i.put(n,MA.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(AP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await W9(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(AP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,MA.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")}};v();Vt();YS();Za();v();ga();Za();var RP="";async function V9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function H9(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(RP),c=n(o);return i+RP+c+s+t}function J9(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(RP)+RP}function Z9(t,e,r,n,s,a){let o=H9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return Q9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function Y9(t,e,r,n,s,a,o){let i=H9(r,n,s,a,o);if(i!==void 0)return Q9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function Q9(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 X9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=J9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await V9(t,e,s),p={};if(d===void 0)u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);else{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)}let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let w=[];for await(let[E,_]of h.iterator(p,c)){if(l!==void 0&&w.length===l)break;let I=JSON.parse(_);S&&!Ut.matchFilter(I.indexes,y)||w.push(I)}return w}async function ez(t,e,r,n,s,a,o){let i=J9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await V9(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);Ut.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ut();ga();var tz="index",rm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ki,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Ra({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 re("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=Y9(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(tz,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(tz)}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 X9(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 ez(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;Ut.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 re("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new re("IndexInvalidCursorValueType",`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,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?0:this.findCursorStartingIndex(l,o,a,u);if(f<0)return[];let h=c===void 0?void 0:f+c;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)||!Ut.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new re("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(Ut.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Ut.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Ut.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?yy(i,c):yy(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}};v();v();Xm();Y2();function DP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Iue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=Nt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*UA(n,s))}else{let r=Nt.asCID(e);r?yield[t.join("/"),r]:yield*UA(e,t)}}function*UA(t,e){if(t==null||t instanceof Uint8Array)return;let r=Nt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*Iue(a,s)}}function*Aue(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!Nt.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"&&!Nt.asCID(n)&&(yield*Aue(s,n))}}function Rue(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=Nt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var CP=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:DP(),bytes:DP(),value:DP(),asBlock:DP()})}links(){return UA(this.value,[])}tree(){return LA(this.value,[])}get(e="/"){return Rue(this.value,e.split("/").filter(Boolean))}};async function rz({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=Nt.create(1,e.code,s);return new CP({value:t,bytes:n,cid:a})}async function nz({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=Nt.create(1,e.code,s);return new CP({value:n,bytes:t,cid:a})}Tp();Vc();Fc();sr();Rd();Za();var Cue=[{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:Ki,...e},this.blockstore=new Bf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new rm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??Cue})}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=Nt.parse(r),o=await s.get(a,n);return o?(await Nn(nz({bytes:o,codec:qc,hasher:xn}),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=rm.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=Nt.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(rz({value:r,codec:qc,hasher:xn}),s?.signal),i=Rr.parseCid(await ge.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()}};v();Vc();var zA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ki,...e},this.db=new Ra({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 Rr.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()}};v();v();function sz(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)})}}}ga();ut();var iz="events",qA=class t{emitter=sz();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){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}else s="epoch_mismatch";let a=await this.getReplayBounds(e),o={requested:r,oldestAvailable:a?.oldest??r,latestAvailable:a?.latest??r,reason:s},i=new re("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 re("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}_${iz}`;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?void 0:t.parsePosition(n.position),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&&!Ut.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 re("EventLogNotOpenError",`invalid cursor position: '${e}'`);return Number(r)}catch(r){throw r instanceof re?r:new re("EventLogNotOpenError",`invalid cursor position: '${e}'`)}}async subscribe(e,r,n,s){let a=`${e}_${iz}`,{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&&!Ut.matchAnyFilter(S.indexes,i)||(f?c(S).then(w=>{n({type:"event",cursor:w,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?d:t.parsePosition(p.cursor.position);for(let S of p.events){let w=await this.buildToken(e,S.seq,S.messageCid??"");n({type:"event",cursor:w,event:S.event})}f=!0;for(let S of l)if(S.seq>y){let w=await this.buildToken(e,S.seq,S.messageCid);n({type:"event",cursor:w,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&&!Ut.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)}};v();vu();v();vu();var Fw=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=Zn(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=Zn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Zn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return ef(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Zn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Zn(e.leftHash),rightHash:Zn(e.rightHash)}:{type:"leaf",keyHash:Zn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:ef(e.leftHash),rightHash:ef(e.rightHash)}:{type:"leaf",keyHash:ef(e.keyHash),valueCid:e.valueCid}}};v();vu();var Gw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await ph()}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 Xl(e),n=await ug(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 Xl(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 Xl(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await Xl(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(tn(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?.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(tn(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(tn(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>=vi||tn(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return tn(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=co(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 wu(u,d);if(!tn(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<vi&&co(e.keyHash,o)===co(n.keyHash,o);)o++;if(o>=vi)return s;let i=co(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await wu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=co(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await wu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=vi)return this.defaultHashes[vi];if(tn(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 tn(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=co(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),tn(i,this.defaultHashes[n+1])&&tn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=tn(i,this.defaultHashes[n+1]),d=tn(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let l=await wu(i,c);if(!tn(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>=vi||tn(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return tn(s.keyHash,r);let a=s;return co(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=vi)return{siblings:[],leafNode:void 0,depth:n};if(tn(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=co(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(co(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await ug(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(co(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=vi||tn(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(tn(e,r)||n>=vi)return;let c=tn(e,this.defaultHashes[n]),u=tn(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"){tn(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:Ki,...e}}async open(){this.db=new Ra({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await ph()}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 Fw(n),a=new Gw(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")}};v();vu();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(Zn(e))}async putNode(e,r){this.nodes.set(Zn(e),r)}async deleteNode(e){this.nodes.delete(Zn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};vu();v();Tp();Fc();Vd();QP();pn();Ba();_0();Mn();wi();Vt();c0();Rd();gi();Up();Dy();Jt();Kp();var jue={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 wn.generateKey();o={publicJwk:await wn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await fd.create({definition:jue,signer:pt.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=pt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await fd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=pt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Ot(s);let a=await hf.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=pt.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 kr.createGrant(c);return{dataStream:ns.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=pt.createSigner(r),s=pt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=ns.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 gt.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 ya.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:w}=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},D=await gt.getEntryId(n.did,y.descriptor),N=ke.constructKeyDerivationPathUsingProtocolContextScheme(D),$=await Ha.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 w.encryptSymmetricEncryptionKey(E),await w.sign({signer:pt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:w,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=ns.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:pt.createSigner(e.author)},u=await gt.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=pt.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};Ot(a);let i=(await Jl.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=pt.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};Ot(a);let i=(await mf.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=pt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};Ot(a);let i=(await Hl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await pd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:pt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=pt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Ot(s);let a=await Yl.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:pt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Zl.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 fm.generateKeyPair(),r=await fm.sign(t.randomBytes(32),e.privateJwk);return _e.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 xn.digest(e);return(await Nt.createV1(Wd,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 $w.create(),r=await $w.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await wn.generateKey(),c={publicJwk:await wn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};v();Vt();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 mv(r)}}};export{cg as AllowAllTenantGate,Bf as BlockstoreLevel,Rr as Cid,KE as ContentEncryptionAlgorithm,ag as CoreProtocolRegistry,BA as DataStoreLevel,ns as DataStream,$p as DateSort,xA as Dwn,Co as DwnConstant,re as DwnError,dt as DwnErrorCode,Ht as DwnInterfaceName,ir as DwnMethodName,_e as Encoder,ya as Encryption,qA as EventEmitterEventLog,Ha as HdKey,rm as IndexLevel,pt as Jws,v3 as KeyAgreementAlgorithm,Lp as KeyDerivationScheme,Ra as LevelWrapper,ge as Message,KA as MessageStoreLevel,Zl as MessagesRead,Yl as MessagesSubscribe,lg as MessagesSync,zE as PERMISSIONS_REVOCATION_PATH,P3 as PermissionConditionPublication,Qr as PermissionGrant,dg as PermissionRequest,kr as PermissionsProtocol,VA as Poller,Ud as PrivateKeySigner,cm as ProtocolRecordLimitStrategy,iI as Protocols,fd as ProtocolsConfigure,hf as ProtocolsQuery,ke as Records,Hl as RecordsCount,pd as RecordsDelete,Jl as RecordsQuery,Wg as RecordsRead,mf as RecordsSubscribe,gt as RecordsWrite,zA as ResumableTaskStoreLevel,Fw as SMTStoreLevel,GA as SMTStoreMemory,vi as SMT_DEPTH,Oa as Secp256k1,Nd as Secp256r1,Ja as SortDirection,Gw as SparseMerkleTree,FA as StateIndexLevel,WA as TestDataGenerator,yt as Time,i_ as ZERO_HASH,cn as authenticate,Ki as createLevelDatabase,Nn as executeUnlessAborted,co as getBit,vM as getDefaultHashes,ld as getRuleSetAtPath,wu as hashChildren,tn as hashEquals,Xl as hashKey,ug as hashLeaf,Zn as hashToHex,ef as hexToHash,ph as initDefaultHashes,pf as isCrossProtocolRef,Bi as parseCrossProtocolRef};
|
|
10
|
+
deps: ${r}}`};var Hee={keyword:"dependencies",type:"object",schemaType:"object",error:pc.error,code(t){let[e,r]=Jee(t);fB(t,e),pB(t,r)}};function Jee({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 fB(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,Lg.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,Lg.checkReportMissingProp)(t,u)}):(r.if((0,ST._)`${c} && (${(0,Lg.checkMissingProp)(t,i,a)})`),(0,Lg.reportMissingProp)(t,a),r.else())}}pc.validatePropertyDeps=fB;function pB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Vee.alwaysValidSchema)(a,e[i])||(r.if((0,Lg.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))}pc.validateSchemaDeps=pB;pc.default=Hee});var mB=xe(ET=>{"use strict";v();Object.defineProperty(ET,"__esModule",{value:!0});var hB=vt(),Zee=$t(),Yee={message:"property name must be valid",params:({params:t})=>(0,hB._)`{propertyName: ${t.propertyName}}`},Qee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Yee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Zee.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,hB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};ET.default=Qee});var _T=xe(kT=>{"use strict";v();Object.defineProperty(kT,"__esModule",{value:!0});var Qb=Oo(),ka=vt(),Xee=$o(),Xb=$t(),ete={message:"must NOT have additional properties",params:({params:t})=>(0,ka._)`{additionalProperty: ${t.additionalProperty}}`},tte={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ete,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,ka._)`${a} === ${Xee.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 w=(0,Xb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Qb.isOwnProperty)(e,w,y)}else u.length?S=(0,ka.or)(...u.map(w=>(0,ka._)`${y} === ${w}`)):S=ka.nil;return d.length&&(S=(0,ka.or)(S,...d.map(w=>(0,ka._)`${(0,Qb.usePattern)(t,w)}.test(${y})`))),(0,ka.not)(S)}function h(y){e.code((0,ka._)`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,ka.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,ka.not)(S),()=>e.break()))}}function m(y,S,w){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Xb.Type.Str};w===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};kT.default=tte});var wB=xe(IT=>{"use strict";v();Object.defineProperty(IT,"__esModule",{value:!0});var rte=kg(),yB=Oo(),TT=$t(),gB=_T(),nte={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&&gB.default.code(new rte.KeywordCxt(a,gB.default,"additionalProperties"));let o=(0,yB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=TT.mergeEvaluated.props(e,(0,TT.toHash)(o),a.props));let i=o.filter(l=>!(0,TT.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,yB.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)}}};IT.default=nte});var xB=xe(AT=>{"use strict";v();Object.defineProperty(AT,"__esModule",{value:!0});var vB=Oo(),e1=vt(),bB=$t(),PB=$t(),ste={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,vB.allSchemaProperties)(r),c=i.filter(m=>(0,bB.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,PB.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,bB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,e1._)`${(0,vB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:PB.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())})})}}};AT.default=ste});var SB=xe(RT=>{"use strict";v();Object.defineProperty(RT,"__esModule",{value:!0});var ite=$t(),ote={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,ite.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"}};RT.default=ote});var EB=xe(DT=>{"use strict";v();Object.defineProperty(DT,"__esModule",{value:!0});var ate=Oo(),cte={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ate.validateUnion,error:{message:"must match a schema in anyOf"}};DT.default=cte});var kB=xe(CT=>{"use strict";v();Object.defineProperty(CT,"__esModule",{value:!0});var t1=vt(),dte=$t(),ute={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},lte={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ute,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,dte.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)})})}}};CT.default=lte});var _B=xe(jT=>{"use strict";v();Object.defineProperty(jT,"__esModule",{value:!0});var fte=$t(),pte={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,fte.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};jT.default=pte});var AB=xe($T=>{"use strict";v();Object.defineProperty($T,"__esModule",{value:!0});var r1=vt(),IB=$t(),hte={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},mte={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:hte,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,IB.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=TB(n,"then"),a=TB(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 TB(t,e){let r=t.schema[e];return r!==void 0&&!(0,IB.alwaysValidSchema)(t,r)}$T.default=mte});var RB=xe(OT=>{"use strict";v();Object.defineProperty(OT,"__esModule",{value:!0});var yte=$t(),gte={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,yte.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};OT.default=gte});var DB=xe(MT=>{"use strict";v();Object.defineProperty(MT,"__esModule",{value:!0});var wte=wT(),vte=cB(),bte=vT(),Pte=uB(),xte=lB(),Ste=Yb(),Ete=mB(),kte=_T(),_te=wB(),Tte=xB(),Ite=SB(),Ate=EB(),Rte=kB(),Dte=_B(),Cte=AB(),jte=RB();function $te(t=!1){let e=[Ite.default,Ate.default,Rte.default,Dte.default,Cte.default,jte.default,Ete.default,kte.default,Ste.default,_te.default,Tte.default];return t?e.push(vte.default,Pte.default):e.push(wte.default,bte.default),e.push(xte.default),e}MT.default=$te});var NT=xe(Kg=>{"use strict";v();Object.defineProperty(Kg,"__esModule",{value:!0});Kg.dynamicAnchor=void 0;var BT=vt(),Ote=$o(),CB=Tg(),Mte=Gb(),Bte={keyword:"$dynamicAnchor",schemaType:"string",code:t=>jB(t,t.schema)};function jB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,BT._)`${Ote.default.dynamicAnchors}${(0,BT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Nte(t);r.if((0,BT._)`!${s}`,()=>r.assign(s,a))}Kg.dynamicAnchor=jB;function Nte(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 CB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return CB.compileSchema.call(n,u),(0,Mte.getValidate)(t,u)}Kg.default=Bte});var UT=xe(zg=>{"use strict";v();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicRef=void 0;var $B=vt(),Ute=$o(),OB=Gb(),Lte={keyword:"$dynamicRef",schemaType:"string",code:t=>MB(t,t.schema)};function MB(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,$B._)`${Ute.default.dynamicAnchors}${(0,$B.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,OB.callRef)(t,c),r.let(u,!0)}):()=>(0,OB.callRef)(t,c)}}zg.dynamicRef=MB;zg.default=Lte});var BB=xe(LT=>{"use strict";v();Object.defineProperty(LT,"__esModule",{value:!0});var Kte=NT(),zte=$t(),qte={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,Kte.dynamicAnchor)(t,""):(0,zte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};LT.default=qte});var NB=xe(KT=>{"use strict";v();Object.defineProperty(KT,"__esModule",{value:!0});var Fte=UT(),Gte={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Fte.dynamicRef)(t,t.schema)};KT.default=Gte});var UB=xe(zT=>{"use strict";v();Object.defineProperty(zT,"__esModule",{value:!0});var Wte=NT(),Vte=UT(),Hte=BB(),Jte=NB(),Zte=[Wte.default,Vte.default,Hte.default,Jte.default];zT.default=Zte});var KB=xe(qT=>{"use strict";v();Object.defineProperty(qT,"__esModule",{value:!0});var LB=Yb(),Yte={keyword:"dependentRequired",type:"object",schemaType:"object",error:LB.error,code:t=>(0,LB.validatePropertyDeps)(t)};qT.default=Yte});var zB=xe(FT=>{"use strict";v();Object.defineProperty(FT,"__esModule",{value:!0});var Qte=Yb(),Xte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Qte.validateSchemaDeps)(t)};FT.default=Xte});var qB=xe(GT=>{"use strict";v();Object.defineProperty(GT,"__esModule",{value:!0});var ere=$t(),tre={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,ere.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};GT.default=tre});var FB=xe(WT=>{"use strict";v();Object.defineProperty(WT,"__esModule",{value:!0});var rre=KB(),nre=zB(),sre=qB(),ire=[rre.default,nre.default,sre.default];WT.default=ire});var WB=xe(VT=>{"use strict";v();Object.defineProperty(VT,"__esModule",{value:!0});var Tu=vt(),GB=$t(),ore=$o(),are={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Tu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},cre={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:are,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 Tu.Name?e.if((0,Tu._)`${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,Tu._)`${s} === ${ore.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,GB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:GB.Type.Str},f),o||e.if((0,Tu.not)(f),()=>e.break())}}function u(l,f){return(0,Tu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Tu._)`${f} !== ${p}`);return(0,Tu.and)(...h)}}};VT.default=cre});var HB=xe(HT=>{"use strict";v();Object.defineProperty(HT,"__esModule",{value:!0});var ff=vt(),VB=$t(),dre={message:({params:{len:t}})=>(0,ff.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ff._)`{limit: ${t}}`},ure={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:dre,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,ff._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,ff._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,VB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,ff._)`${o} <= ${a}`);e.if((0,ff.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:VB.Type.Num},c),s.allErrors||e.if((0,ff.not)(c),()=>e.break())})}}};HT.default=ure});var JB=xe(JT=>{"use strict";v();Object.defineProperty(JT,"__esModule",{value:!0});var lre=WB(),fre=HB(),pre=[lre.default,fre.default];JT.default=pre});var ZB=xe(ZT=>{"use strict";v();Object.defineProperty(ZT,"__esModule",{value:!0});var An=vt(),hre={message:({schemaCode:t})=>(0,An.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,An._)`{format: ${t}}`},mre={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hre,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)(w(),E()));function w(){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){w();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(_());function w(){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 D=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:D});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})`}}}};ZT.default=mre});var YB=xe(YT=>{"use strict";v();Object.defineProperty(YT,"__esModule",{value:!0});var yre=ZB(),gre=[yre.default];YT.default=gre});var QB=xe(kh=>{"use strict";v();Object.defineProperty(kh,"__esModule",{value:!0});kh.contentVocabulary=kh.metadataVocabulary=void 0;kh.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kh.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var eN=xe(QT=>{"use strict";v();Object.defineProperty(QT,"__esModule",{value:!0});var wre=W4(),vre=sB(),bre=DB(),Pre=UB(),xre=FB(),Sre=JB(),Ere=YB(),XB=QB(),kre=[Pre.default,wre.default,vre.default,(0,bre.default)(!0),Ere.default,XB.metadataVocabulary,XB.contentVocabulary,xre.default,Sre.default];QT.default=kre});var rN=xe(n1=>{"use strict";v();Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var tN;(function(t){t.Tag="tag",t.Mapping="mapping"})(tN||(n1.DiscrError=tN={}))});var sN=xe(eI=>{"use strict";v();Object.defineProperty(eI,"__esModule",{value:!0});var _h=vt(),XT=rN(),nN=Tg(),_re=_g(),Tre=$t(),Ire={message:({params:{discrError:t,tagName:e}})=>t===XT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,_h._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Are={keyword:"discriminator",type:"object",schemaType:"object",error:Ire,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,_h._)`${r}${(0,_h.getProperty)(i)}`);e.if((0,_h._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:XT.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,_h._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:XT.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,_h.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,Tre.schemaHasRulesButRef)(I,a.self.RULES)){let N=I.$ref;if(I=nN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,N),I instanceof nN.SchemaEnv&&(I=I.schema),I===void 0)throw new _re.default(a.opts.uriResolver,a.baseId,N)}let D=(h=I?.properties)===null||h===void 0?void 0:h[i];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(I)),w(D,_)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:_}){return Array.isArray(_)&&_.includes(i)}function w(_,I){if(_.const)E(_.const,I);else if(_.enum)for(let D of _.enum)E(D,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}}}};eI.default=Are});var iN=xe((c5e,Rre)=>{Rre.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 oN=xe((d5e,Dre)=>{Dre.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 aN=xe((u5e,Cre)=>{Cre.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 cN=xe((l5e,jre)=>{jre.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 dN=xe((f5e,$re)=>{$re.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 uN=xe((p5e,Ore)=>{Ore.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 lN=xe((h5e,Mre)=>{Mre.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 fN=xe((m5e,Bre)=>{Bre.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 pN=xe(tI=>{"use strict";v();Object.defineProperty(tI,"__esModule",{value:!0});var Nre=iN(),Ure=oN(),Lre=aN(),Kre=cN(),zre=dN(),qre=uN(),Fre=lN(),Gre=fN(),Wre=["/properties"];function Vre(t){return[Nre,Ure,Lre,Kre,zre,e(this,qre),Fre,e(this,Gre)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Wre):n}}tI.default=Vre});var sI=xe((Vr,nI)=>{"use strict";v();Object.defineProperty(Vr,"__esModule",{value:!0});Vr.MissingRefError=Vr.ValidationError=Vr.CodeGen=Vr.Name=Vr.nil=Vr.stringify=Vr.str=Vr._=Vr.KeywordCxt=Vr.Ajv2020=void 0;var Hre=K4(),Jre=eN(),Zre=sN(),Yre=pN(),rI="https://json-schema.org/draft/2020-12/schema",Th=class extends Hre.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Jre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Zre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(Yre.default.call(this,e),this.refs["http://json-schema.org/schema"]=rI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rI)?rI:void 0)}};Vr.Ajv2020=Th;nI.exports=Vr=Th;nI.exports.Ajv2020=Th;Object.defineProperty(Vr,"__esModule",{value:!0});Vr.default=Th;var Qre=kg();Object.defineProperty(Vr,"KeywordCxt",{enumerable:!0,get:function(){return Qre.KeywordCxt}});var Ih=vt();Object.defineProperty(Vr,"_",{enumerable:!0,get:function(){return Ih._}});Object.defineProperty(Vr,"str",{enumerable:!0,get:function(){return Ih.str}});Object.defineProperty(Vr,"stringify",{enumerable:!0,get:function(){return Ih.stringify}});Object.defineProperty(Vr,"nil",{enumerable:!0,get:function(){return Ih.nil}});Object.defineProperty(Vr,"Name",{enumerable:!0,get:function(){return Ih.Name}});Object.defineProperty(Vr,"CodeGen",{enumerable:!0,get:function(){return Ih.CodeGen}});var Xre=Mb();Object.defineProperty(Vr,"ValidationError",{enumerable:!0,get:function(){return Xre.default}});var ene=_g();Object.defineProperty(Vr,"MissingRefError",{enumerable:!0,get:function(){return ene.default}})});var I9=xe((x4e,_A)=>{"use strict";v();var gue=Object.prototype.hasOwnProperty,Ei="~";function Mw(){}Object.create&&(Mw.prototype=Object.create(null),new Mw().__proto__||(Ei=!1));function wue(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function T9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new wue(r,n||t,s),o=Ei?Ei+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 vP(t,e){--t._eventsCount===0?t._events=new Mw:delete t._events[e]}function ei(){this._events=new Mw,this._eventsCount=0}ei.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)gue.call(r,n)&&e.push(Ei?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ei.prototype.listeners=function(e){var r=Ei?Ei+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};ei.prototype.listenerCount=function(e){var r=Ei?Ei+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ei.prototype.emit=function(e,r,n,s,a,o){var i=Ei?Ei+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};ei.prototype.on=function(e,r,n){return T9(this,e,r,n,!1)};ei.prototype.once=function(e,r,n){return T9(this,e,r,n,!0)};ei.prototype.removeListener=function(e,r,n,s){var a=Ei?Ei+e:e;if(!this._events[a])return this;if(!r)return vP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&vP(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:vP(this,a)}return this};ei.prototype.removeAllListeners=function(e){var r;return e?(r=Ei?Ei+e:e,this._events[r]&&vP(this,r)):(this._events=new Mw,this._eventsCount=0),this};ei.prototype.off=ei.prototype.removeListener;ei.prototype.addListener=ei.prototype.on;ei.prefixed=Ei;ei.EventEmitter=ei;typeof _A<"u"&&(_A.exports=ei)});v();v();var cm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(cm||{});v();v();pn();Ba();v();v();var Cm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,L6=new Set,s2=typeof process=="object"&&process?process:{},K6=(t,e,r,n)=>{typeof s2.emitWarning=="function"?s2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},T0=globalThis.AbortController,U6=globalThis.AbortSignal;if(typeof T0>"u"){U6=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},T0=class{constructor(){e()}signal=new U6;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=s2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,K6("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 BF=t=>!L6.has(t),hme=Symbol("type"),Ld=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),z6=t=>Ld(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?hp:null:null,hp=class extends Array{constructor(e){super(e),this.fill(0)}},i2=class t{heap;length;static#c=!1;static create(e){let r=z6(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]}},I0=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:w,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:_,ignoreFetchAbort:I}=e;if(r!==0&&!Ld(r))throw new TypeError("max option must be a nonnegative integer");let D=r?z6(r):Array;if(!D)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 D(r),this.#f=new D(r),this.#a=0,this.#i=0,this.#y=i2.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&&!Ld(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Ld(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Ld(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Ld(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";BF(N)&&(L6.add(N),K6("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 hp(this.#c),r=new hp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=Cm.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?Cm.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=Cm.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 hp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#O=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Ld(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Ld(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)=>{};#O=(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.#M(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.#M(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#M(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=Cm.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=Cm.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.#O(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 T0,{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,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!w&&!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,w=S||n.allowStaleOnFetchRejection,E=w||n.noDeleteOnFetchRejection,_=h;if(this.#e[r]===h&&(!E||_.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=_.__staleWhileFetching)),w)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(w=>m(w),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=w=>u(w,!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 T0}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:w}=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:w},_=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 D=this.#p(_);if(!y&&!D)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=D?"stale":"refresh",F&&D&&(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 A0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new I0({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)}};C0();ut();var zd=class t{static _singleton;cache;constructor(e){this.cache=e||new A0(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=_e.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new re("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new re("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 pt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=pt.extractDid(i);if(a)n.push(l);else throw new re("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=pt.extractDid(e),{didDocument:s,didResolutionMetadata:a}=await r.resolve(n),{verificationMethod:o=[]}=s||{},i;for(let u of o)if(e.endsWith(u.id)){i=u;break}if(!i)throw new re("GeneralJwsVerifierGetPublicKeyNotFound",t.buildPublicKeyNotFoundMessage(e,n,s,a,o));Lc("JwkVerificationMethod",i);let{publicKeyJwk:c}=i;return c}static buildPublicKeyNotFoundMessage(e,r,n,s,a){let o=s?.error;if(o!==void 0){let c=s?.errorMessage,u=c?`${o} \u2014 ${c}`:o;return`unable to resolve DID '${r}' to verify signature with kid '${e}': ${u}`}if(n==null)return`DID Document not found for '${r}' when verifying signature with kid '${e}'`;if(a.length===0)return`DID Document for '${r}' has no verification methods to verify signature with kid '${e}'`;let i=a.map(c=>c.id).join(", ");return`public key for kid '${e}' not found in DID Document for '${r}' (available verification methods: [${i}])`}};wi();ut();async function cn(t,e,r){if(t===void 0)throw new re("AuthenticateJwsMissing","Missing JWS.");if(await zd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await zd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await gt.parse(t.authorDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await gt.parse(t.ownerDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await zd.verifySignatures(r,e)}v();var ag=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}}};qE();v();var cg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Vc();v();v();Ba();sr();var Pn=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 ge.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=ge.getSigner(e),e.authorization.authorDelegatedGrant===void 0?this._author=this._signer:this._author=ge.getSigner(e.authorization.authorDelegatedGrant),this._signaturePayload=pt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var Hl=class t extends Pn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter)};Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};v();Al();sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var Jl=class t extends Pn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new re("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new re("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Vd();Kp();v();sr();v();function ot(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}v();Vd();pn();v();Jt();Ov();v();v();var Co=class{static maxDataSizeAllowedToBeEncoded=3e4};pn();ga();sr();fa();v();pn();sr();ut();var dg=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 re("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(ge.getSigner(e)===void 0)throw new re("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(_e.base64UrlToObject(e.encodedData).scope===void 0)throw new re("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=ge.getSigner(e);let r=e.encodedData,n=_e.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};Mn();wi();gi();C0();ut();Jt();Ao();var kr=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 re("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>Co.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>ge.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,...ke.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Ut.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return _e.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new re("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=_e.objectToBytes(n),o=await gt.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:_e.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 re("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=_e.objectToBytes(n),o=await gt.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:_e.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:li(e.grant.scope.protocol)});let a=_e.objectToBytes(r),o=await gt.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:_e.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=_e.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Lc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Lc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Lc("PermissionRevocationData",s);else throw new re("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 re("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Qr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new re("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?Qr.parse(n).scope:dg.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=li(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?.protocol===void 0)throw new re("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new re("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(Gn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new re("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};Mn();wi();ut();var gu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await ro.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 ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),kr.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new re("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 re("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=ke.isRecordsWrite(a)?a:await gt.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===kr.uri){let i=await kr.getScopeFromPermissionRecord(e,s,o);if(kr.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new re("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};v();Vc();sr();gi();ut();Jt();var Zl=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await ge.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 ge.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return ge.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Rr.parseCid(e)}catch{throw new re("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};Mn();ut();var bb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ot(o,400)}try{await cn(r.authorization,this.deps.didResolver)}catch(o){return ot(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 ot(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(ke.isRecordsWrite(s)){let o=a.message;if(o.encodedData===void 0){let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}else{let i=_e.base64UrlToBytes(o.encodedData);a.data=ns.fromBytes(i),delete o.encodedData}}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 kr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await gu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new re("MessagesReadAuthorizationFailed","protocol message failed authorization")}};v();sr();v();ga();Ao();Vt();var Pb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol===void 0?void 0:li(n.protocol),a={...n,protocol:s};Ot(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=Ut.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?Ut.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}};v();sr();Vt();gi();Ao();Jt();var Yl=class t extends Pn{static async parse(e){ge.validateJsonSchema(e),await ge.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&Gn(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};Ot(n);let{permissionGrantId:s,signer:a}=e,o=await ge.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return ge.validateJsonSchema(i),new t(i)}};ut();var xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ot(new re("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Yl.parse(r)}catch(u){return ot(u,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ot(u,401)}let{filters:a,cursor:o}=r.descriptor,i=Pb.convertFilters(a,this.deps.coreProtocols),c=await ge.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 re&&u.code==="EventLogProgressGap"){let d=u.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:d===void 0?void 0:{code:"ProgressGap",...d}}}return ot(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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("MessagesSubscribeAuthorizationFailed","message failed authorization")}};v();pn();vu();v();sr();Vt();gi();Ao();Jt();var lg=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),await ge.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&Gn(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};Ot(r);let{permissionGrantId:n,signer:s}=e,a=await ge.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return ge.validateJsonSchema(o),new t(o)}};ut();var AZ=Co.maxDataSizeAllowedToBeEncoded,Sb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await lg.parse(r)}catch(i){return ot(i,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ot(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.getRoot(e):await this.deps.stateIndex.getProtocolRoot(e,a);return{status:{code:200,detail:"OK"},root:Zn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a===void 0?await this.deps.stateIndex.getSubtreeHash(e,i):await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i);return{status:{code:200,detail:"OK"},hash:Zn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a===void 0?await this.deps.stateIndex.getLeaves(e,i):await this.deps.stateIndex.getProtocolLeaves(e,a,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 ot(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 w=t.parseBitPrefix(h),E=n===void 0?await o.getLeaves(e,w):await o.getProtocolLeaves(e,n,w);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n===void 0?await o.getLeaves(e,y):await o.getProtocolLeaves(e,n,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.getSubtreeHash(e,d):await s.getProtocolSubtreeHash(e,r,d),f=Zn(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(()=>(vu(),bM)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Zn(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<=AZ&&(c.encodedData=_e.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 re("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new re("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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("MessagesSyncAuthorizationFailed","message failed authorization")}};v();sr();v();var hN=Kn(sI(),1);sr();fa();v();Ov();ut();var Iu=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await ro.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 ro.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 re("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 re("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};gi();ut();Jt();v();Up();Kp();function Bi(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 pf(t){return t.includes(":")}function s1(t){return t.split("/").slice(-1)[0]}function ld(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 iI=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 Ha.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await wn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Ha.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ao();var fd=class t extends Pn{static async parse(e){return ge.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await ge.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 ge.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),s={descriptor:r,authorization:n};return ge.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await Iu.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;Gn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Ya(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 re("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{Gn(e[s])}catch{throw new re("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new re("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 re("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 re("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 re("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 re("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(cm);if(!l.includes(d))throw new re("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new hN.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 re("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(pf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new re("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new re("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 re("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 re("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(pf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new re("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new re("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 re("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 re("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.role===f.role)throw new re("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.who===f.who&&d.of===f.of)throw new re("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} 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 re("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=Bi(s);if(a===void 0)throw new re("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n?.[a.alias]===void 0)throw new re("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 re("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=Bi(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new re(o,`cross-protocol '${s}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r?.[a.alias]===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new re(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=Dl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=li(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:li(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ut();Jt();var i1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fd.parse(r)}catch(d){return ot(d,400)}try{await cn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return ot(d,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(d){return ot(d,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await ge.getCid(r);for(let d of a)if(await ge.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let i=await ge.getNewestMessage(a),c=!1;(i===void 0||await ge.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 ge.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 ge.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 fd.parse(d),f=t.constructIndexes(l,!1),h=await ge.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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Iu.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new re("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 re("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=Bi(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new re("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 re("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 re("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=Bi(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new re("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);if(!ld(u.protocolPath,d.structure)?.$role)throw new re("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Bi(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new re("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(ld(u.protocolPath,d.structure)===void 0)throw new re("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)}}};v();ut();v();sr();Vt();gi();ut();Jt();Ao();var hf=class t extends Pn{static async parse(e){return e.authorization!==void 0&&await ge.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&Gn(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};Ot(r);let n;e.signer!==void 0&&(n=await ge.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return ge.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:li(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await kr.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Iu.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new re("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};Vt();Jt();var o1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hf.parse(r)}catch(o){return ot(o,400)}try{await cn(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 ot(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};Ot(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}};v();sr();v();Za();ut();Jt();v();ga();wi();ut();Jt();async function qg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(pf(c)){let p=Bi(c);if(p===void 0)throw new re("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses?.[p.alias]===void 0)throw new re("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);if(!ld(d,m.structure)?.$role)throw new re("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else if(!ld(c,s.structure)?.$role)throw new re("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 re("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Ut.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new re("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function nne(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await gt.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 gt.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Fg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await nne(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new re("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 sne(c,l,n,a))return}throw new re("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function sne(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(pf(s)&&n?.uses!==void 0){let o=Bi(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 gt.parse(a)).author;return t===o}}v();wi();ut();Jt();async function Ah(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 gt.getInitialWrite(s)}async function Gg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Ah(t,s,r);if(a===void 0)throw new re("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 oI(t,e,r){let n=await Ah(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}v();var mN=Kn(sI(),1);ga();Mn();ut();Jt();async function yN(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 re("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await ine(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 re("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new re("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new re("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new re("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function ine(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=Bi(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 gN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=s1(o),c=await one(t,o,r,n,s,a);ane(e,c,i)}async function one(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=Bi(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 ane(t,e,r){let n=r??s1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new re("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 re("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 re("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new re("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function wN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new re("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new re("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function vN(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 mN.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 re("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function bN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new re("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=ke.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Ut.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 re("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function PN(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=ke.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Ut.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new re("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 re("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function xN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new re("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 re("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function SN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new re("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Zs=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await oI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await gN(e,r.message,o,n,i,a),await yN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await bN(e,r,c,n),wN(r,c),vN(r,c),await SN(r,c),await xN(r,c),await PN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Ah(e,r.message.recordId,n),o;a===void 0?o=await Gg(e,r.message.descriptor.parentId,n):o=await Gg(e,r.message.recordId,n);let i=await oI(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 qg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Fg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Gg(e,n.message.recordId,s),i=await Ah(e,n.message.recordId,s),c=i===void 0?n.message.descriptor.messageTimestamp:i.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 qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(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 qg(e,r,a,i,c,n,d),await Fg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Gg(e,r.message.descriptor.recordId,s),i=await Ah(e,r.message.descriptor.recordId,s),c=i===void 0?n.message.descriptor.messageTimestamp:i.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 qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(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.isLatestBaseState=!0:o.messageTimestamp={lte:s};let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new re("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=ld(e,r.structure);if(n===void 0)throw new re("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};Mn();Jt();var a1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Hl.parse(r)}catch(a){return ot(a,400)}let s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ot(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={...ke.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 ke.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.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{...ke.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Jt();sr();Mn();v();sr();fa();Mn();Qa();Vt();gi();Jt();var pd=class t extends Pn{static async parse(e){let r;return e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.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 ge.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return ge.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 Ot(d),d}async authorizeDelegate(e,r){let n=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Qa();wi();v();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 pd.parse(r)}catch(u){return ot(u,400)}try{await cn(r.authorization,this.deps.didResolver)}catch(u){return ot(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await ge.getNewestMessage(a);if(!ke.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await ge.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await gt.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ot(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(ge.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 kr.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 Zs.authorizeDelete(e,r,n,s,a)}};v();Al();sr();Mn();wi();Za();Jt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(o){return ot(o,400)}let s,a;if(ke.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 cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ot(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 gt.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={...ke.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=[];ke.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(a)&&(ke.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Vd();pn();sr();Mn();Qa();v();Al();sr();fa();Mn();Qa();Vt();gi();ut();Jt();var Wg=class t extends Pn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new re("RecordsReadParseFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.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 re("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:ke.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};Ot(c);let u;n!==void 0&&(u=await ge.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return ge.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};wi();ut();Jt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Wg.parse(r)}catch(l){return ot(l,400)}try{n.author!==void 0&&await cn(r.authorization,this.deps.didResolver)}catch(l){return ot(l,401)}let s={interface:"Records",isLatestBaseState:!0,...ke.convertFilter(r.descriptor.filter)},a=ke.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 gt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ot(new re("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await gt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await gt.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ot(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await gt.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ot(l,401)}let u;if(c.encodedData===void 0){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}else{let l=_e.base64UrlToBytes(c.encodedData);u=ns.fromBytes(l),delete c.encodedData}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await gt.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){ge.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 kr.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 Zs.authorizeRead(e,r,n,s,a)}}};v();Al();sr();Mn();v();sr();fa();Mn();Qa();Vt();gi();ut();Jt();Ao();var mf=class t extends Pn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await ge.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new re("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&Gn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Ya(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:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Ot(r);let n=e.signer,s;n&&(s=await ge.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return ge.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Qr.parse(this.message.authorization.authorDelegatedGrant);await kn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};wi();Za();ut();Jt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ot(new re("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await mf.parse(r)}catch(f){return ot(f,400)}let a=[],o=[];if(ke.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await cn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ot(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await ge.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 re&&f.code==="EventLogProgressGap"){let h=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:h===void 0?void 0:{code:"ProgressGap",...h}}}return ot(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 gt.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await u.close(),ot(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[{...ke.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...ke.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return ke.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({...ke.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{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){ge.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Zs.authorizeQueryOrSubscribe(e,r,n,s)}};v();Vc();Vd();pn();ga();sr();Mn();Qa();wi();Za();v();ga();sr();Mn();wi();Jt();var Rh=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 ge.getNewestMessage(s);if(!ke.canPerformDeleteAgainstRecord(r,a))return;let o=await pd.parse(r),i=await gt.getInitialWrite(s),c=o.constructIndexes(i),u=await ge.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=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Ut.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;ke.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f===void 0?u.set(l,[d]):f.push(d)}for(let[d,l]of u){if(d===r.recordId)continue;let f=await ge.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<=Co.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;ke.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 ge.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>ge.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 ge.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ge.getCid(c);if(await s.delete(e,d),await gt.isInitialWrite(c)){let p=await(await gt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await ge.getCid(c);i.push(f)}}await o.delete(e,i)}}};ut();Jt();var p1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await gt.parse(r),await Zs.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(m){return ot(m,400)}try{await cn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(m){return ot(m,401)}let a={interface:"Records",recordId:r.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),i=await ge.getCid(r);for(let m of o){if(await ge.getCid(m)!==i)continue;if(!await this.existingInitialWriteLacksData(e,m,r,n!==void 0))return{status:{code:409,detail:"Conflict"}}}let c=await s.isInitialWrite(),u;if(!c)try{u=await gt.getInitialWrite(o),gt.verifyEqualityOfImmutableProperties(u,r)}catch(m){return ot(m,400)}try{await this.enforceSquashBackstop(e,r)}catch(m){return ot(m,409)}let d=await ge.getNewestMessage(o),l=!1,f;if(d===void 0||await ge.isNewer(r,d)?(l=!0,f=r):f=d,!l){let m=!1;if(d&&(m=await this.existingInitialWriteLacksData(e,d,r,n!==void 0)),!m)return{status:{code:409,detail:"Conflict"}}}let h=r.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(r.descriptor.protocol);try{if(d?.descriptor.method==="Delete")throw new re("RecordsWriteNotAllowedAfterDelete","RecordsWrite is not allowed after a RecordsDelete.");h?.preProcessWrite!==void 0&&await h.preProcessWrite(e,r,this.deps.messageStore);let m=!1,y=r;if(n===void 0){if(!c){let E=d;y=await this.processMessageWithoutDataStream(e,r,E),m=!0}}else y=await this.processMessageWithDataStream(e,r,n),m=!0;let S=await s.constructIndexes(m);await this.deps.messageStore.put(e,y,S);let w=await ge.getCid(r);await this.deps.stateIndex.insert(e,w,S),this.deps.eventLog!==void 0&&m&&await this.deps.eventLog.emit(e,{message:y,initialWrite:u},S,w)}catch(m){if(m instanceof re&&(m.code==="RecordsWriteMissingEncodedDataInPrevious"||m.code==="RecordsWriteMissingDataInPrevious"||m.code==="RecordsWriteNotAllowedAfterDelete"||m.code==="RecordsWriteDataCidMismatch"||m.code==="RecordsWriteDataSizeMismatch"||m.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(m.code)!==void 0))return ot(m,400);throw m}let p={status:c&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Rh.deleteAllOlderMessagesButKeepInitialWrite(e,o,f,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}}),h?.postProcessWrite!==void 0&&await h.postProcessWrite(e,s,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),p}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=_e.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=Co.maxDataSizeAllowedToBeEncoded){let a=await ns.toBytes(n),o=await Rr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(r.descriptor.protocol);i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=ns.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Rr.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 existingInitialWriteLacksData(e,r,n,s){if(!s||!await gt.isInitialWrite(r))return!1;let o=!!r.encodedData,i=this.deps.dataStore?!!await this.deps.dataStore.get(e,r.recordId,n.descriptor.dataCid):!1;return!o&&!i}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<=Co.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new re("RecordsWriteMissingEncodedDataInPrevious","No dataStream was provided and unable to get data from previous message");s.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new re("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 re("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new re("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 Zs.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?.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Ut.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 re("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 re("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 kr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await kn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Zs.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};v();var dne=Object.create,BI=Object.defineProperty,une=Object.getOwnPropertyDescriptor,lne=Object.getOwnPropertyNames,fne=Object.getPrototypeOf,pne=Object.prototype.hasOwnProperty,Bt=(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})},hne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lne(e))!pne.call(t,s)&&s!==r&&BI(t,s,{get:()=>e[s],enumerable:!(n=une(e,s))||n.enumerable});return t},Rf=(t,e,r)=>(r=t!=null?dne(fne(t)):{},hne(e||!t||!t.__esModule?BI(r,"default",{value:t,enumerable:!0}):r,t)),mne=Bt((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 KU{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!==KU.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}),yne=Bt(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)})}}),kc=Bt((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)}}}),gne=Bt(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],w=y[1],E=new n(u(p,S,w)),_=0,I=w>0?S-4:S,D;for(D=0;D<I;D+=4)m=r[p.charCodeAt(D)]<<18|r[p.charCodeAt(D+1)]<<12|r[p.charCodeAt(D+2)]<<6|r[p.charCodeAt(D+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return w===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,E[_++]=m&255),w===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+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,w=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),w.push(l(S));return w.join("")}function h(p){for(var m,y=p.length,S=y%3,w=[],E=16383,_=0,I=y-S;_<I;_+=E)w.push(f(p,_,_+E>I?I:_+E));return S===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),wne=Bt(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=Bt(t=>{"use strict";var e=gne(),r=wne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=w,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(ze(T,ArrayBuffer)||T&&ze(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ze(T,SharedArrayBuffer)||T&&ze(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(ze(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"||Ft(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 w(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(ze(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),ze(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(ze(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)||ze(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 Ee(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return Tr(T).length;default:if(ae)return te?-1:Ee(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 R(this,M,L);case"ascii":return P(this,M,L);case"latin1":case"binary":return b(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?R(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(ze(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,be=L-M,Rt=Math.min(he,be),Ln=this.slice(te,ae),Or=T.slice(M,L);for(let lr=0;lr<Rt;++lr)if(Ln[lr]!==Or[lr]){he=Ln[lr],be=Or[lr];break}return he<be?-1:be<he?1:0};function D(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,Ft(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,be=T.length,Rt=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,be/=2,Rt/=2,L/=2}function Ln(lr,rr){return he===1?lr[rr]:lr.readUInt16BE(rr*he)}let Or;if(ae){let lr=-1;for(Or=L;Or<be;Or++)if(Ln(T,Or)===Ln(M,lr===-1?0:Or-lr)){if(lr===-1&&(lr=Or),Or-lr+1===Rt)return lr*he}else lr!==-1&&(Or-=Or-lr),lr=-1}else for(L+Rt>be&&(L=be-Rt),Or=L;Or>=0;Or--){let lr=!0;for(let rr=0;rr<Rt;rr++)if(Ln(T,Or+rr)!==Ln(M,rr)){lr=!1;break}if(lr)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 D(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return D(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 be;for(be=0;be<te;++be){let Rt=parseInt(M.substr(be*2,2),16);if(Ft(Rt))return be;T[L+be]=Rt}return be}function F(T,M,L,te){return ki(Ee(M,T.length-L),T,L,te)}function z(T,M,L,te){return ki(bt(M),T,L,te)}function B(T,M,L,te){return ki(Tr(M),T,L,te)}function H(T,M,L,te){return ki(Un(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 H(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 R(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],be=null,Rt=he>239?4:he>223?3:he>191?2:1;if(ae+Rt<=L){let Ln,Or,lr,rr;switch(Rt){case 1:he<128&&(be=he);break;case 2:Ln=T[ae+1],(Ln&192)===128&&(rr=(he&31)<<6|Ln&63,rr>127&&(be=rr));break;case 3:Ln=T[ae+1],Or=T[ae+2],(Ln&192)===128&&(Or&192)===128&&(rr=(he&15)<<12|(Ln&63)<<6|Or&63,rr>2047&&(rr<55296||rr>57343)&&(be=rr));break;case 4:Ln=T[ae+1],Or=T[ae+2],lr=T[ae+3],(Ln&192)===128&&(Or&192)===128&&(lr&192)===128&&(rr=(he&15)<<18|(Ln&63)<<12|(Or&63)<<6|lr&63,rr>65535&&rr<1114112&&(be=rr))}}be===null?(be=65533,Rt=1):be>65535&&(be-=65536,te.push(be>>>10&1023|55296),be=56320|be&1023),te.push(be),ae+=Rt}return x(te)}var j=4096;function x(T){let M=T.length;if(M<=j)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=j));return L}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]&127);return te}function b(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+=Ir[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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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=tr(function(T){T=T>>>0,fe(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&ue(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 K(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 be=Math.pow(2,8*L)-1;K(this,T,M,L,be,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 be=Math.pow(2,8*L)-1;K(this,T,M,L,be,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||K(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||K(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||K(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||K(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||K(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){ce(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 be=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=be,be=be>>8,T[L++]=be,be=be>>8,T[L++]=be,be=be>>8,T[L++]=be,L}function V(T,M,L,te,ae){ce(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 be=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=be,be=be>>8,T[L+2]=be,be=be>>8,T[L+1]=be,be=be>>8,T[L]=be,L+8}i.prototype.writeBigUInt64LE=tr(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=tr(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 Rt=Math.pow(2,8*L-1);K(this,T,M,L,Rt-1,-Rt)}let ae=0,he=1,be=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&be===0&&this[M+ae-1]!==0&&(be=1),this[M+ae]=(T/he>>0)-be&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Rt=Math.pow(2,8*L-1);K(this,T,M,L,Rt-1,-Rt)}let ae=L-1,he=1,be=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&be===0&&this[M+ae+1]!==0&&(be=1),this[M+ae]=(T/he>>0)-be&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||K(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||K(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||K(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||K(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||K(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=tr(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=tr(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function W(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 J(T,M,L,te,ae){return M=+M,L=L>>>0,ae||W(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return J(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return J(this,T,M,!1,L)};function q(T,M,L,te,ae){return M=+M,L=L>>>0,ae||W(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return q(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return q(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),be=he.length;if(be===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%be]}return this};var Y={};function ne(T,M,L){Y[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}`}}}ne("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ne("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),ne("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=se(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=se(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function se(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){fe(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&ue(M,T.length-(L+1))}function ce(T,M,L,te,ae,he){if(T>L||T<M){let be=typeof M=="bigint"?"n":"",Rt;throw he>3?M===0||M===BigInt(0)?Rt=`>= 0${be} and < 2${be} ** ${(he+1)*8}${be}`:Rt=`>= -(2${be} ** ${(he+1)*8-1}${be}) and < 2 ** ${(he+1)*8-1}${be}`:Rt=`>= ${M}${be} and <= ${L}${be}`,new Y.ERR_OUT_OF_RANGE("value",Rt,T)}Z(te,ae,he)}function fe(T,M){if(typeof T!="number")throw new Y.ERR_INVALID_ARG_TYPE(M,"number",T)}function ue(T,M,L){throw Math.floor(T)!==T?(fe(T,L),new Y.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Y.ERR_BUFFER_OUT_OF_BOUNDS:new Y.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var Pe=/[^+/0-9A-Za-z-_]/g;function pe(T){if(T=T.split("=")[0],T=T.trim().replace(Pe,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Ee(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let be=0;be<te;++be){if(L=T.charCodeAt(be),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(be+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 bt(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Un(T,M){let L,te,ae,he=[];for(let be=0;be<T.length&&!((M-=2)<0);++be)L=T.charCodeAt(be),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function Tr(T){return e.toByteArray(pe(T))}function ki(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 ze(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function Ft(T){return T!==T}var Ir=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 tr(T){return typeof BigInt>"u"?At:T}function At(){throw new Error("BigInt not supported")}}),zU=Bt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),qU=Bt(t=>{"use strict";var e=kc(),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}),FU=Bt(t=>{"use strict";var{Buffer:e}=UI()||{},{Encoding:r}=qU(),n=zU(),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}),vne=Bt(t=>{"use strict";var{Buffer:e}=UI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=zU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=FU(),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"})}),bne=Bt(t=>{"use strict";var e=kc(),r=vne(),{Encoding:n}=qU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=FU(),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(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}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:w,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 '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,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,w=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new o({...y,name:w});case"buffer":return new s({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var h={binary:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),Pne=Bt((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,w,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,w=new Array(S-1);E<S;E++)w[E-1]=arguments[E];y.fn.apply(y.context,w)}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(!w)for(I=1,w=new Array(S-1);I<S;I++)w[I-1]=arguments[I];y[E].fn.apply(y[E].context,w)}}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)}),xne=Bt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),tP=Bt(t=>{"use strict";var e=xne();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=Bt(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:{}}}),Sf=Bt(t=>{"use strict";var{fromCallback:e}=tP(),r=kc(),{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"),w=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),I=Symbol("keys"),D=Symbol("values"),N=Symbol("limit"),$=Symbol("count"),F=Object.freeze({}),z=()=>{},B=!1,H=class{constructor(P,b,k){if(typeof P!="object"||P===null){let A=P===null?"null":typeof P;throw new TypeError(`The first argument must be an abstract-level database, received ${A}`)}if(typeof b!="object"||b===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]=b[S],this[w]=b[w],this[_]=k,this[N]=Number.isInteger(b.limit)&&b.limit>=0?b.limit:1/0,this[$]=0,this[E]=!!b.abortOnClose,this.db=P,this.db.attachResource(this),this.nextTick=P.nextTick}get count(){return this[$]}get limit(){return this[N]}next(P){let b;if(P===void 0)b=new Promise((k,A)=>{P=(O,K,G)=>{O?A(O):this[_]?K===void 0&&G===void 0?k():k([K,G]):k(K)}});else if(typeof P!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(P,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[$]>=this[N]?this.nextTick(this[c],null):this._next(this[c])),b}_next(P){this.nextTick(P)}nextv(P,b,k){return k=s(b,k),k=e(k,a),b=n(b,F),Number.isInteger(P)?(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"})):(P<1&&(P=1),this[N]<1/0&&(P=Math.min(P,this[N]-this[$])),this[i]=!0,this[o]=k,P<=0?this.nextTick(this[u],null,[]):this._nextv(P,b,this[u])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(P,b,k){let A=[],O=(K,G,V)=>{if(K)return k(K);if(this[_]?G===void 0&&V===void 0:G===void 0)return k(null,A);A.push(this[_]?[G,V]:G),A.length===P?k(null,A):this._next(O)};this._next(O)}all(P,b){return b=s(P,b),b=e(b,a),P=n(P,F),this[h]?this.nextTick(b,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(b,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=b,this[d]=!0,this[$]>=this[N]?this.nextTick(this[u],null,[]):this._all(P,this[u])),b[a]}_all(P,b){let k=this[$],A=[],O=()=>{let G=this[N]<1/0?Math.min(1e3,this[N]-k):1e3;G<=0?this.nextTick(b,null,A):this._nextv(G,F,K)},K=(G,V)=>{G?b(G):V.length===0?b(null,A):(A.push.apply(A,V),k+=V.length,O())};O()}[l](){let P=this[o];return this[E]&&P===null?z:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),P)}[f](P,b,k){this[d]?this.close(P.bind(null,b,k)):P(b,k)}seek(P,b){if(b=n(b,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(b.keyEncoding||this[S]),A=k.format;b.keyEncoding!==A&&(b={...b,keyEncoding:A});let O=this.db.prefixKey(k.encode(P),A);this._seek(O,b)}}}_seek(P,b){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(P){return P=e(P,a),this[m]?this.nextTick(P):this[h]?this[y].push(P):(this[h]=!0,this[y].push(P),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),P[a]}_close(P){this.nextTick(P)}[p](){this[m]=!0,this.db.detachResource(this);let P=this[y];this[y]=[];for(let b of P)b()}async*[Symbol.asyncIterator](){try{let P;for(;(P=await this.next())!==void 0;)yield P}finally{this[m]||await this.close()}}},X=class extends H{constructor(P,b){super(P,b,!0),this[I]=b.keys!==!1,this[D]=b.values!==!1}[c](P,b,k){let A=this[l]();if(P)return A(P);try{b=this[I]&&b!==void 0?this[S].decode(b):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(O){return A(new x("entry",O))}b===void 0&&k===void 0||this[$]++,A(null,b,k)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A of b){let O=A[0],K=A[1];A[0]=this[I]&&O!==void 0?this[S].decode(O):void 0,A[1]=this[D]&&K!==void 0?this[w].decode(K):void 0}}catch(A){return this[f](k,new x("entries",A))}this[$]+=b.length,this[f](k,null,b)}end(P){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(P)}},R=class extends H{constructor(P,b){super(P,b,!1)}[c](P,b){let k=this[l]();if(P)return k(P);try{b=b!==void 0?this[S].decode(b):void 0}catch(A){return k(new x("key",A))}b!==void 0&&this[$]++,k(null,b)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A=0;A<b.length;A++){let O=b[A];b[A]=O!==void 0?this[S].decode(O):void 0}}catch(A){return this[f](k,new x("keys",A))}this[$]+=b.length,this[f](k,null,b)}},j=class extends H{constructor(P,b){super(P,b,!1)}[c](P,b){let k=this[l]();if(P)return k(P);try{b=b!==void 0?this[w].decode(b):void 0}catch(A){return k(new x("value",A))}b!==void 0&&this[$]++,k(null,b)}[u](P,b){let k=this[l]();if(P)return this[f](k,P);try{for(let A=0;A<b.length;A++){let O=b[A];b[A]=O!==void 0?this[w].decode(O):void 0}}catch(A){return this[f](k,new x("values",A))}this[$]+=b.length,this[f](k,null,b)}},x=class extends r{constructor(P,b){super(`Iterator could not decode ${P}`,{code:"LEVEL_DECODE_ERROR",cause:b})}};for(let P of["_ended property","_nexting property","_end method"])Object.defineProperty(X.prototype,P.split(" ")[0],{get(){throw new r(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${P} has been removed`,{code:"LEVEL_LEGACY"})}});X.keyEncoding=S,X.valueEncoding=w,t.AbstractIterator=X,t.AbstractKeyIterator=R,t.AbstractValueIterator=j}),Sne=Bt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Sf(),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}),Ene=Bt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=kc(),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}),GU=Bt(t=>{"use strict";var{fromCallback:e}=tP(),r=kc(),{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),w=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let _=m.prefixKey(S.encode(l),E),I=w.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}),kne=Bt(t=>{"use strict";var{AbstractChainedBatch:e}=GU(),r=kc(),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}),_ne=Bt((t,e)=>{"use strict";var r=kc(),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}}),WU=Bt((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))}),Tne=Bt((t,e)=>{"use strict";var r=WU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),Ine=Bt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),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}),Ane=Bt((t,e)=>{"use strict";var r=kc(),{Buffer:n}=UI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=Ine(),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(D){if(typeof D=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?h:D.separator?D:{...D,separator:"!"}}constructor(D,N,$){let{separator:F,manifest:z,...B}=_.defaults($);N=w(N,F);let H=F.charCodeAt(0)+1,X=D[d]||D;if(!f.encode(N).every(x=>x>H&&x<127))throw new r(`Prefix must use bytes > ${H} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(X,z),B);let R=(D.prefix||"")+F+N+F,j=R.slice(0,-1)+String.fromCharCode(H);this[d]=X,this[i]=new y(R),this[c]=new y(j),this[l]=new S,this.nextTick=X.nextTick}prefixKey(D,N){if(N==="utf8")return this[i].utf8+D;if(D.byteLength===0)return this[i][N];if(N==="view"){let $=this[i].view,F=new Uint8Array($.byteLength+D.byteLength);return F.set($,0),F.set(D,$.byteLength),F}else{let $=this[i].buffer;return n.concat([$,D],$.byteLength+D.byteLength)}}[u](D,N){D.gte!==void 0?D.gte=this.prefixKey(D.gte,N):D.gt!==void 0?D.gt=this.prefixKey(D.gt,N):D.gte=this[i][N],D.lte!==void 0?D.lte=this.prefixKey(D.lte,N):D.lt!==void 0?D.lt=this.prefixKey(D.lt,N):D.lte=this[c][N]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(D,N){this[d].open({passive:!0},N)}_put(D,N,$,F){this[d].put(D,N,$,F)}_get(D,N,$){this[d].get(D,N,$)}_getMany(D,N,$){this[d].getMany(D,N,$)}_del(D,N,$){this[d].del(D,N,$)}_batch(D,N,$){this[d].batch(D,N,$)}_clear(D,N){this[u](D,D.keyEncoding),this[d].clear(D,N)}_iterator(D){this[u](D,D.keyEncoding);let N=this[d].iterator(D),$=this[l].get(this[i].utf8.length,D.keyEncoding);return new s(this,D,N,$)}_keys(D){this[u](D,D.keyEncoding);let N=this[d].keys(D),$=this[l].get(this[i].utf8.length,D.keyEncoding);return new a(this,D,N,$)}_values(D){this[u](D,D.keyEncoding);let N=this[d].values(D);return new o(this,D,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(D,N){return N.subarray(D)}).bind(null,E):I=(function(D,N){return N.slice(D)}).bind(null,E),this.cache.set(_,I)),I}},w=function(E,_){let I=0,D=E.length;for(;I<D&&E[I]===_;)I++;for(;D>I&&E[D-1]===_;)D--;return E.slice(I,D)}}),EN=Bt(t=>{"use strict";var{supports:e}=yne(),{Transcoder:r}=bne(),{EventEmitter:n}=Pne(),{fromCallback:s}=tP(),a=kc(),{AbstractIterator:o}=Sf(),{DefaultKeyIterator:i,DefaultValueIterator:c}=Sne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=Ene(),{DefaultChainedBatch:f}=kne(),{getCallback:h,getOptions:p}=LI(),m=_ne(),y=Symbol("promise"),S=Symbol("landed"),w=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),I=Symbol("undefer"),D=Symbol("deferOpen"),N=Symbol("options"),$=Symbol("status"),F=Symbol("defaultOptions"),z=Symbol("transcoder"),B=Symbol("keyEncoding"),H=Symbol("valueEncoding"),X=()=>{},R=class extends n{constructor(b,k){if(super(),typeof b!="object"||b===null)throw new TypeError("The first argument 'manifest' must be an object");k=p(k);let{keyEncoding:A,valueEncoding:O,passive:K,...G}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[N]=G,this[$]="opening",this.supports=e(b,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:b.snapshots!==!1,permanence:b.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:b.encodings||{},events:Object.assign({},b.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(P(this)),this[B]=this[z].encoding(A||"utf8"),this[H]=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[H].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},X)})}get status(){return this[$]}keyEncoding(b){return this[z].encoding(b??this[B])}valueEncoding(b){return this[z].encoding(b??this[H])}open(b,k){k=h(b,k),k=s(k,y),b={...this[N],...p(b)},b.createIfMissing=b.createIfMissing!==!1,b.errorIfExists=!!b.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 b.passive?this[$]==="opening"?this.once(S,A):this.nextTick(A):this[$]==="closed"||this[D]?(this[D]=!1,this[$]="opening",this.emit("opening"),this._open(b,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(b,k)),k[y]}_open(b,k){this.nextTick(k)}close(b){b=s(b,y);let k=A=>{this[$]==="opening"||this[$]==="closing"?this.once(S,A?k(A):k):this[$]!=="closed"?b(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:A})):b()};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(b));return b[y]}[E](b){if(this[w].size===0)return this.nextTick(b);let k=this[w].size,A=!0,O=()=>{--k===0&&(A?this.nextTick(b):b())};for(let K of this[w])K.close(O);A=!1,this[w].clear()}_close(b){this.nextTick(b)}get(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.get(b,k,A)),A[y];if(x(this,A))return A[y];let O=this._checkKey(b);if(O)return this.nextTick(A,O),A[y];let K=this.keyEncoding(k.keyEncoding),G=this.valueEncoding(k.valueEncoding),V=K.format,W=G.format;return(k.keyEncoding!==V||k.valueEncoding!==W)&&(k=Object.assign({},k,{keyEncoding:V,valueEncoding:W})),this._get(this.prefixKey(K.encode(b),V),k,(J,q)=>{if(J)return(J.code==="LEVEL_NOT_FOUND"||J.notFound||/NotFound/i.test(J))&&(J.code||(J.code="LEVEL_NOT_FOUND"),J.notFound||(J.notFound=!0),J.status||(J.status=404)),A(J);try{q=G.decode(q)}catch(Y){return A(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Y}))}A(null,q)}),A[y]}_get(b,k,A){this.nextTick(A,new Error("NotFound"))}getMany(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].entry),this[$]==="opening")return this.defer(()=>this.getMany(b,k,A)),A[y];if(x(this,A))return A[y];if(!Array.isArray(b))return this.nextTick(A,new TypeError("The first argument 'keys' must be an array")),A[y];if(b.length===0)return this.nextTick(A,null,[]),A[y];let O=this.keyEncoding(k.keyEncoding),K=this.valueEncoding(k.valueEncoding),G=O.format,V=K.format;(k.keyEncoding!==G||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:G,valueEncoding:V}));let W=new Array(b.length);for(let J=0;J<b.length;J++){let q=b[J],Y=this._checkKey(q);if(Y)return this.nextTick(A,Y),A[y];W[J]=this.prefixKey(O.encode(q),G)}return this._getMany(W,k,(J,q)=>{if(J)return A(J);try{for(let Y=0;Y<q.length;Y++)q[Y]!==void 0&&(q[Y]=K.decode(q[Y]))}catch(Y){return A(new a(`Could not decode one or more of ${q.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Y}))}A(null,q)}),A[y]}_getMany(b,k,A){this.nextTick(A,null,new Array(b.length).fill(void 0))}put(b,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(b,k,A,O)),O[y];if(x(this,O))return O[y];let K=this._checkKey(b)||this._checkValue(k);if(K)return this.nextTick(O,K),O[y];let G=this.keyEncoding(A.keyEncoding),V=this.valueEncoding(A.valueEncoding),W=G.format,J=V.format;(A.keyEncoding!==W||A.valueEncoding!==J)&&(A=Object.assign({},A,{keyEncoding:W,valueEncoding:J}));let q=this.prefixKey(G.encode(b),W),Y=V.encode(k);return this._put(q,Y,A,ne=>{if(ne)return O(ne);this.emit("put",b,k),O()}),O[y]}_put(b,k,A,O){this.nextTick(O)}del(b,k,A){if(A=h(k,A),A=s(A,y),k=p(k,this[F].key),this[$]==="opening")return this.defer(()=>this.del(b,k,A)),A[y];if(x(this,A))return A[y];let O=this._checkKey(b);if(O)return this.nextTick(A,O),A[y];let K=this.keyEncoding(k.keyEncoding),G=K.format;return k.keyEncoding!==G&&(k=Object.assign({},k,{keyEncoding:G})),this._del(this.prefixKey(K.encode(b),G),k,V=>{if(V)return A(V);this.emit("del",b),A()}),A[y]}_del(b,k,A){this.nextTick(A)}batch(b,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 b=="function"?A=b:A=h(k,A),A=s(A,y),k=p(k,this[F].empty),this[$]==="opening")return this.defer(()=>this.batch(b,k,A)),A[y];if(x(this,A))return A[y];if(!Array.isArray(b))return this.nextTick(A,new TypeError("The first argument 'operations' must be an array")),A[y];if(b.length===0)return this.nextTick(A),A[y];let O=new Array(b.length),{keyEncoding:K,valueEncoding:G,...V}=k;for(let W=0;W<b.length;W++){if(typeof b[W]!="object"||b[W]===null)return this.nextTick(A,new TypeError("A batch operation must be an object")),A[y];let J=Object.assign({},b[W]);if(J.type!=="put"&&J.type!=="del")return this.nextTick(A,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),A[y];let q=this._checkKey(J.key);if(q)return this.nextTick(A,q),A[y];let Y=J.sublevel!=null?J.sublevel:this,ne=Y.keyEncoding(J.keyEncoding||K),se=ne.format;if(J.key=Y.prefixKey(ne.encode(J.key),se),J.keyEncoding=se,J.type==="put"){let Z=this._checkValue(J.value);if(Z)return this.nextTick(A,Z),A[y];let ce=Y.valueEncoding(J.valueEncoding||G);J.value=ce.encode(J.value),J.valueEncoding=ce.format}Y!==this&&(J.sublevel=null),O[W]=J}return this._batch(O,V,W=>{if(W)return A(W);this.emit("batch",b),A()}),A[y]}_batch(b,k,A){this.nextTick(A)}sublevel(b,k){return this._sublevel(b,j.defaults(k))}_sublevel(b,k){return new j(this,b,k)}prefixKey(b,k){return b}clear(b,k){if(k=h(b,k),k=s(k,y),b=p(b,this[F].empty),this[$]==="opening")return this.defer(()=>this.clear(b,k)),k[y];if(x(this,k))return k[y];let A=b,O=this.keyEncoding(b.keyEncoding);return b=m(b,O),b.keyEncoding=O.format,b.limit===0?this.nextTick(k):this._clear(b,K=>{if(K)return k(K);this.emit("clear",A),k()}),k[y]}_clear(b,k){this.nextTick(k)}iterator(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b.keys=b.keys!==!1,b.values=b.values!==!1,b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new u(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(b)}_iterator(b){return new o(this,b)}keys(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new d(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(b)}_keys(b){return new i(this,b)}values(b){let k=this.keyEncoding(b&&b.keyEncoding),A=this.valueEncoding(b&&b.valueEncoding);if(b=m(b,k),b[o.keyEncoding]=k,b[o.valueEncoding]=A,b.keyEncoding=k.format,b.valueEncoding=A.format,this[$]==="opening")return new l(this,b);if(this[$]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(b)}_values(b){return new c(this,b)}defer(b){if(typeof b!="function")throw new TypeError("The first argument must be a function");this[_].push(b)}[I](){if(this[_].length===0)return;let b=this[_];this[_]=[];for(let k of b)k()}attachResource(b){if(typeof b!="object"||b===null||typeof b.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(b)}detachResource(b){this[w].delete(b)}_chainedBatch(){return new f(this)}_checkKey(b){if(b==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(b){if(b==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=Tne();var{AbstractSublevel:j}=Ane()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=j;var x=function(b,k){return b[$]!=="open"?(b.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},P=function(b){return Object.keys(b.supports.encodings).filter(k=>!!b.supports.encodings[k])}}),VU=Bt(t=>{"use strict";t.AbstractLevel=EN().AbstractLevel,t.AbstractSublevel=EN().AbstractSublevel,t.AbstractIterator=Sf().AbstractIterator,t.AbstractKeyIterator=Sf().AbstractKeyIterator,t.AbstractValueIterator=Sf().AbstractValueIterator,t.AbstractChainedBatch=GU().AbstractChainedBatch}),Rne=Bt((t,e)=>{e.exports=n;var r=WU();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,w){if(i[y]=w,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(w,E){m(y,w,E)}),S===a-1}):s.some(function(y,S){return y(function(w,E){m(S,w,E)}),S===a-1}):p(null),f=!1}}),HU=Bt((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}}),JU=Bt((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)}}),Dne=Bt(t=>{"use strict";var{AbstractIterator:e}=VU(),r=HU(),n=JU(),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 w=this.db.db.transaction([this[u]],"readonly"),E=w.objectStore(this[u]),_=[];if(this[o].reverse){let I=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[I](S,"prev").onsuccess=D=>{let N=D.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(w)}else this[a]=!0}}else{let I,D,N=()=>{if(I===void 0||D===void 0)return;let $=Math.max(I.length,D.length);$===0||p===1/0?this[a]=!0:this[c]=I[$-1],_.length=$;for(let F=0;F<$;F++){let z=I[F],B=D[F];_[F]=[this[o].keys&&z!==void 0?n(z):void 0,this[o].values&&B!==void 0?n(B):void 0]}h(w)};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=$=>{D=$.target.result,N()}:(D=[],this.nextTick(N))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(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,(w,E)=>{if(w)return m(w);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()}}),Cne=Bt((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()})}}}),jne=Bt(t=>{"use strict";var{AbstractLevel:e}=VU(),r=kc(),n=Rne(),{fromCallback:s}=tP(),{Iterator:a}=Dne(),o=JU(),i=Cne(),c=HU(),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(w,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:D,...N}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},N),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[l]=I??u,this[h]=parseInt(D||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(w,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 D=I.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,E){let _=w.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,w.result)}}_get(w,E,_){let I=this[p]("readonly"),D;try{D=I.get(w)}catch(N){return this.nextTick(_,N)}this[m](D,function(N,$){if(N)return _(N);if($===void 0)return _(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,o($))})}_getMany(w,E,_){let I=this[p]("readonly"),D=w.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(D,16,_)}_del(w,E,_){let I=this[p]("readwrite"),D;try{D=I.delete(w)}catch(N){return this.nextTick(_,N)}this[m](D,_)}_put(w,E,_,I){let D=this[p]("readwrite"),N;try{N=D.put(E,w)}catch($){return this.nextTick(I,$)}this[m](N,I)}_iterator(w){return new a(this,this[f],w)}_batch(w,E,_){let I=this[p]("readwrite"),D=I.transaction,N=0,$;D.onabort=function(){_($||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function F(){let z=w[N++],B=z.key,H;try{H=z.type==="del"?I.delete(B):I.put(z.value,B)}catch(X){$=X,D.abort();return}N<w.length?H.onsuccess=F:typeof D.commit=="function"&&D.commit()}F()}_clear(w,E){let _,I;try{_=c(w)}catch{return this.nextTick(E)}if(w.limit>=0)return i(this,this[f],_,w,E);try{let D=this[p]("readwrite");I=_?D.delete(_):D.clear()}catch(D){return this.nextTick(E,D)}this[m](I,E)}_close(w){this[d].close(),this.nextTick(w)}};S.destroy=function(w,E,_){typeof E=="function"&&(_=E,E=u),_=s(_,y);let I=indexedDB.deleteDatabase(E+w);return I.onsuccess=function(){_()},I.onerror=function(D){_(D)},_[y]},t.BrowserLevel=S}),ZU=Bt(t=>{t.Level=jne().BrowserLevel}),$ne=Bt((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 Q=arguments.length,ie=Array(Q),oe=0;oe<Q;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,we=1;we<ye;++we)ie[we]=ie[we].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(Q){return"(?:"+Q+")"}function a(Q){return Q===void 0?"undefined":Q===null?"null":Object.prototype.toString.call(Q).split(" ").pop().split("]").shift().toLowerCase()}function o(Q){return Q.toUpperCase()}function i(Q){return Q!=null?Q instanceof Array?Q:typeof Q.length!="number"||Q.split||Q.setInterval||Q.call?[Q]:Array.prototype.slice.call(Q):[]}function c(Q,ie){var oe=Q;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(Q){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",we="[\\x22]",Ue=n(ye,"[A-Fa-f]"),St="[\\x0A]",ar="[\\x20]",Kr=s(s("%[EFef]"+Ue+"%"+Ue+Ue+"%"+Ue+Ue)+"|"+s("%[89A-Fa-f]"+Ue+"%"+Ue+Ue)+"|"+s("%"+Ue+Ue)),zr="[\\:\\/\\?\\#\\[\\]\\@]",Yt="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",fn=n(zr,Yt),$n=Q?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",nn=Q?"[\\uE000-\\uF8FF]":"[]",mr=n(ie,ye,"[\\-\\.\\_\\~]",$n),fr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Ns=s(s(Kr+"|"+n(mr,Yt,"[\\:]"))+"*"),nm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),_i=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Zo=s(_i+"\\."+_i+"\\."+_i+"\\."+_i),yr=s(Ue+"{1,4}"),qi=s(s(yr+"\\:"+yr)+"|"+Zo),vo=s(s(yr+"\\:")+"{6}"+qi),_c=s("\\:\\:"+s(yr+"\\:")+"{5}"+qi),Zu=s(s(yr)+"?\\:\\:"+s(yr+"\\:")+"{4}"+qi),Ca=s(s(s(yr+"\\:")+"{0,1}"+yr)+"?\\:\\:"+s(yr+"\\:")+"{3}"+qi),Ww=s(s(s(yr+"\\:")+"{0,2}"+yr)+"?\\:\\:"+s(yr+"\\:")+"{2}"+qi),Vw=s(s(s(yr+"\\:")+"{0,3}"+yr)+"?\\:\\:"+yr+"\\:"+qi),qf=s(s(s(yr+"\\:")+"{0,4}"+yr)+"?\\:\\:"+qi),Ff=s(s(s(yr+"\\:")+"{0,5}"+yr)+"?\\:\\:"+yr),Gf=s(s(s(yr+"\\:")+"{0,6}"+yr)+"?\\:\\:"),Yu=s([vo,_c,Zu,Ca,Ww,Vw,qf,Ff,Gf].join("|")),Wf=s(s(mr+"|"+Kr)+"+"),Vf=s(Yu+"\\%25"+Wf),yz=s(Yu+s("\\%25|\\%(?!"+Ue+"{2})")+Wf),gz=s("[vV]"+Ue+"+\\."+n(mr,Yt,"[\\:]")+"+"),wz=s("\\["+s(yz+"|"+Yu+"|"+gz)+"\\]"),QA=s(s(Kr+"|"+n(mr,Yt))+"*"),sm=s(wz+"|"+Zo+"(?!"+QA+")|"+QA),im=s(ye+"*"),XA=s(s(Ns+"@")+"?"+sm+s("\\:"+im)+"?"),om=s(Kr+"|"+n(mr,Yt,"[\\:\\@]")),vz=s(om+"*"),eR=s(om+"+"),bz=s(s(Kr+"|"+n(mr,Yt,"[\\@]"))+"+"),Tc=s(s("\\/"+vz)+"*"),Hf=s("\\/"+s(eR+Tc)+"?"),$P=s(bz+Tc),Hw=s(eR+Tc),Jf="(?!"+om+")",$ue=s(Tc+"|"+Hf+"|"+$P+"|"+Hw+"|"+Jf),Zf=s(s(om+"|"+n("[\\/\\?]",nn))+"*"),am=s(s(om+"|[\\/\\?]")+"*"),tR=s(s("\\/\\/"+XA+Tc)+"|"+Hf+"|"+Hw+"|"+Jf),Pz=s(fr+"\\:"+tR+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),xz=s(s("\\/\\/"+XA+Tc)+"|"+Hf+"|"+$P+"|"+Jf),Sz=s(xz+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),Oue=s(Pz+"|"+Sz),Mue=s(fr+"\\:"+tR+s("\\?"+Zf)+"?"),Bue="^("+fr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",Nue="^(){0}"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+$P+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",Uue="^("+fr+")\\:"+s(s("\\/\\/("+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?$",Lue="^"+s("\\#("+am+")")+"?$",Kue="^"+s("("+Ns+")@")+"?("+sm+")"+s("\\:("+im+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",mr,Yt),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",mr,Yt),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",mr,Yt),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",mr,Yt),"g"),NOT_QUERY:new RegExp(n("[^\\%]",mr,Yt,"[\\:\\@\\/\\?]",nn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",mr,Yt,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",mr,Yt),"g"),UNRESERVED:new RegExp(mr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",mr,fn),"g"),PCT_ENCODED:new RegExp(Kr,"g"),IPV4ADDRESS:new RegExp("^("+Zo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Yu+")"+s(s("\\%25|\\%(?!"+Ue+"{2})")+"("+Wf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function Q(ie,oe){var ye=[],we=!0,Ue=!1,St=void 0;try{for(var ar=ie[Symbol.iterator](),Kr;!(we=(Kr=ar.next()).done)&&(ye.push(Kr.value),!(oe&&ye.length===oe));we=!0);}catch(zr){Ue=!0,St=zr}finally{try{!we&&ar.return&&ar.return()}finally{if(Ue)throw St}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return Q(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(Q){if(Array.isArray(Q)){for(var ie=0,oe=Array(Q.length);ie<Q.length;ie++)oe[ie]=Q[ie];return oe}else return Array.from(Q)},p=2147483647,m=36,y=1,S=26,w=38,E=700,_=72,I=128,D="-",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,H=Math.floor,X=String.fromCharCode;function R(Q){throw new RangeError(z[Q])}function j(Q,ie){for(var oe=[],ye=Q.length;ye--;)oe[ye]=ie(Q[ye]);return oe}function x(Q,ie){var oe=Q.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",Q=oe[1]),Q=Q.replace(F,".");var we=Q.split("."),Ue=j(we,ie).join(".");return ye+Ue}function P(Q){for(var ie=[],oe=0,ye=Q.length;oe<ye;){var we=Q.charCodeAt(oe++);if(we>=55296&&we<=56319&&oe<ye){var Ue=Q.charCodeAt(oe++);(Ue&64512)==56320?ie.push(((we&1023)<<10)+(Ue&1023)+65536):(ie.push(we),oe--)}else ie.push(we)}return ie}var b=function(Q){return String.fromCodePoint.apply(String,h(Q))},k=function(Q){return Q-48<10?Q-22:Q-65<26?Q-65:Q-97<26?Q-97:m},A=function(Q,ie){return Q+22+75*(Q<26)-((ie!=0)<<5)},O=function(Q,ie,oe){var ye=0;for(Q=oe?H(Q/E):Q>>1,Q+=H(Q/ie);Q>B*S>>1;ye+=m)Q=H(Q/B);return H(ye+(B+1)*Q/(Q+w))},K=function(Q){var ie=[],oe=Q.length,ye=0,we=I,Ue=_,St=Q.lastIndexOf(D);St<0&&(St=0);for(var ar=0;ar<St;++ar)Q.charCodeAt(ar)>=128&&R("not-basic"),ie.push(Q.charCodeAt(ar));for(var Kr=St>0?St+1:0;Kr<oe;){for(var zr=ye,Yt=1,fn=m;;fn+=m){Kr>=oe&&R("invalid-input");var $n=k(Q.charCodeAt(Kr++));($n>=m||$n>H((p-ye)/Yt))&&R("overflow"),ye+=$n*Yt;var nn=fn<=Ue?y:fn>=Ue+S?S:fn-Ue;if($n<nn)break;var mr=m-nn;Yt>H(p/mr)&&R("overflow"),Yt*=mr}var fr=ie.length+1;Ue=O(ye-zr,fr,zr==0),H(ye/fr)>p-we&&R("overflow"),we+=H(ye/fr),ye%=fr,ie.splice(ye++,0,we)}return String.fromCodePoint.apply(String,ie)},G=function(Q){var ie=[];Q=P(Q);var oe=Q.length,ye=I,we=0,Ue=_,St=!0,ar=!1,Kr=void 0;try{for(var zr=Q[Symbol.iterator](),Yt;!(St=(Yt=zr.next()).done);St=!0){var fn=Yt.value;fn<128&&ie.push(X(fn))}}catch(Vf){ar=!0,Kr=Vf}finally{try{!St&&zr.return&&zr.return()}finally{if(ar)throw Kr}}var $n=ie.length,nn=$n;for($n&&ie.push(D);nn<oe;){var mr=p,fr=!0,Ns=!1,nm=void 0;try{for(var _i=Q[Symbol.iterator](),Zo;!(fr=(Zo=_i.next()).done);fr=!0){var yr=Zo.value;yr>=ye&&yr<mr&&(mr=yr)}}catch(Vf){Ns=!0,nm=Vf}finally{try{!fr&&_i.return&&_i.return()}finally{if(Ns)throw nm}}var qi=nn+1;mr-ye>H((p-we)/qi)&&R("overflow"),we+=(mr-ye)*qi,ye=mr;var vo=!0,_c=!1,Zu=void 0;try{for(var Ca=Q[Symbol.iterator](),Ww;!(vo=(Ww=Ca.next()).done);vo=!0){var Vw=Ww.value;if(Vw<ye&&++we>p&&R("overflow"),Vw==ye){for(var qf=we,Ff=m;;Ff+=m){var Gf=Ff<=Ue?y:Ff>=Ue+S?S:Ff-Ue;if(qf<Gf)break;var Yu=qf-Gf,Wf=m-Gf;ie.push(X(A(Gf+Yu%Wf,0))),qf=H(Yu/Wf)}ie.push(X(A(qf,0))),Ue=O(we,qi,nn==$n),we=0,++nn}}}catch(Vf){_c=!0,Zu=Vf}finally{try{!vo&&Ca.return&&Ca.return()}finally{if(_c)throw Zu}}++we,++ye}return ie.join("")},V=function(Q){return x(Q,function(ie){return N.test(ie)?K(ie.slice(4).toLowerCase()):ie})},W=function(Q){return x(Q,function(ie){return $.test(ie)?"xn--"+G(ie):ie})},J={version:"2.1.0",ucs2:{decode:P,encode:b},decode:K,encode:G,toASCII:W,toUnicode:V},q={};function Y(Q){var ie=Q.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 ne(Q){for(var ie="",oe=0,ye=Q.length;oe<ye;){var we=parseInt(Q.substr(oe+1,2),16);if(we<128)ie+=String.fromCharCode(we),oe+=3;else if(we>=194&&we<224){if(ye-oe>=6){var Ue=parseInt(Q.substr(oe+4,2),16);ie+=String.fromCharCode((we&31)<<6|Ue&63)}else ie+=Q.substr(oe,6);oe+=6}else if(we>=224){if(ye-oe>=9){var St=parseInt(Q.substr(oe+4,2),16),ar=parseInt(Q.substr(oe+7,2),16);ie+=String.fromCharCode((we&15)<<12|(St&63)<<6|ar&63)}else ie+=Q.substr(oe,9);oe+=9}else ie+=Q.substr(oe,3),oe+=3}return ie}function se(Q,ie){function oe(ye){var we=ne(ye);return we.match(ie.UNRESERVED)?we:ye}return Q.scheme&&(Q.scheme=String(Q.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),Q.userinfo!==void 0&&(Q.userinfo=String(Q.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Y).replace(ie.PCT_ENCODED,o)),Q.host!==void 0&&(Q.host=String(Q.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Y).replace(ie.PCT_ENCODED,o)),Q.path!==void 0&&(Q.path=String(Q.path).replace(ie.PCT_ENCODED,oe).replace(Q.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Y).replace(ie.PCT_ENCODED,o)),Q.query!==void 0&&(Q.query=String(Q.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Y).replace(ie.PCT_ENCODED,o)),Q.fragment!==void 0&&(Q.fragment=String(Q.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Y).replace(ie.PCT_ENCODED,o)),Q}function Z(Q){return Q.replace(/^0*(.*)/,"$1")||"0"}function ce(Q,ie){var oe=Q.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),we=ye[1];return we?we.split(".").map(Z).join("."):Q}function fe(Q,ie){var oe=Q.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),we=ye[1],Ue=ye[2];if(we){for(var St=we.toLowerCase().split("::").reverse(),ar=f(St,2),Kr=ar[0],zr=ar[1],Yt=zr?zr.split(":").map(Z):[],fn=Kr.split(":").map(Z),$n=ie.IPV4ADDRESS.test(fn[fn.length-1]),nn=$n?7:8,mr=fn.length-nn,fr=Array(nn),Ns=0;Ns<nn;++Ns)fr[Ns]=Yt[Ns]||fn[mr+Ns]||"";$n&&(fr[nn-1]=ce(fr[nn-1],ie));var nm=fr.reduce(function(vo,_c,Zu){if(!_c||_c==="0"){var Ca=vo[vo.length-1];Ca&&Ca.index+Ca.length===Zu?Ca.length++:vo.push({index:Zu,length:1})}return vo},[]),_i=nm.sort(function(vo,_c){return _c.length-vo.length})[0],Zo=void 0;if(_i&&_i.length>1){var yr=fr.slice(0,_i.index),qi=fr.slice(_i.index+_i.length);Zo=yr.join(":")+"::"+qi.join(":")}else Zo=fr.join(":");return Ue&&(Zo+="%"+Ue),Zo}else return Q}var ue=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Pe="".match(/(){0}/)[1]===void 0;function pe(Q){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(Q=(ie.scheme?ie.scheme+":":"")+"//"+Q);var we=Q.match(ue);if(we){Pe?(oe.scheme=we[1],oe.userinfo=we[3],oe.host=we[4],oe.port=parseInt(we[5],10),oe.path=we[6]||"",oe.query=we[7],oe.fragment=we[8],isNaN(oe.port)&&(oe.port=we[5])):(oe.scheme=we[1]||void 0,oe.userinfo=Q.indexOf("@")!==-1?we[3]:void 0,oe.host=Q.indexOf("//")!==-1?we[4]:void 0,oe.port=parseInt(we[5],10),oe.path=we[6]||"",oe.query=Q.indexOf("?")!==-1?we[7]:void 0,oe.fragment=Q.indexOf("#")!==-1?we[8]:void 0,isNaN(oe.port)&&(oe.port=Q.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?we[4]:void 0)),oe.host&&(oe.host=fe(ce(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 Ue=q[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!Ue||!Ue.unicodeSupport)){if(oe.host&&(ie.domainHost||Ue&&Ue.domainHost))try{oe.host=J.toASCII(oe.host.replace(ye.PCT_ENCODED,ne).toLowerCase())}catch(St){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+St}se(oe,d)}else se(oe,ye);Ue&&Ue.parse&&Ue.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function Ee(Q,ie){var oe=ie.iri!==!1?l:d,ye=[];return Q.userinfo!==void 0&&(ye.push(Q.userinfo),ye.push("@")),Q.host!==void 0&&ye.push(fe(ce(String(Q.host),oe),oe).replace(oe.IPV6ADDRESS,function(we,Ue,St){return"["+Ue+(St?"%25"+St:"")+"]"})),(typeof Q.port=="number"||typeof Q.port=="string")&&(ye.push(":"),ye.push(String(Q.port))),ye.length?ye.join(""):void 0}var bt=/^\.\.?\//,Un=/^\/\.(\/|$)/,Tr=/^\/\.\.(\/|$)/,ki=/^\/?(?:.|\n)*?(?=\/|$)/;function ze(Q){for(var ie=[];Q.length;)if(Q.match(bt))Q=Q.replace(bt,"");else if(Q.match(Un))Q=Q.replace(Un,"/");else if(Q.match(Tr))Q=Q.replace(Tr,"/"),ie.pop();else if(Q==="."||Q==="..")Q="";else{var oe=Q.match(ki);if(oe){var ye=oe[0];Q=Q.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function Ft(Q){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],we=q[(ie.scheme||Q.scheme||"").toLowerCase()];if(we&&we.serialize&&we.serialize(Q,ie),Q.host&&!oe.IPV6ADDRESS.test(Q.host)&&(ie.domainHost||we&&we.domainHost))try{Q.host=ie.iri?J.toUnicode(Q.host):J.toASCII(Q.host.replace(oe.PCT_ENCODED,ne).toLowerCase())}catch(ar){Q.error=Q.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+ar}se(Q,oe),ie.reference!=="suffix"&&Q.scheme&&(ye.push(Q.scheme),ye.push(":"));var Ue=Ee(Q,ie);if(Ue!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(Ue),Q.path&&Q.path.charAt(0)!=="/"&&ye.push("/")),Q.path!==void 0){var St=Q.path;!ie.absolutePath&&(!we||!we.absolutePath)&&(St=ze(St)),Ue===void 0&&(St=St.replace(/^\/\//,"/%2F")),ye.push(St)}return Q.query!==void 0&&(ye.push("?"),ye.push(Q.query)),Q.fragment!==void 0&&(ye.push("#"),ye.push(Q.fragment)),ye.join("")}function Ir(Q,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],we={};return ye||(Q=pe(Ft(Q,oe),oe),ie=pe(Ft(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(we.scheme=ie.scheme,we.userinfo=ie.userinfo,we.host=ie.host,we.port=ie.port,we.path=ze(ie.path||""),we.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(we.userinfo=ie.userinfo,we.host=ie.host,we.port=ie.port,we.path=ze(ie.path||""),we.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?we.path=ze(ie.path):((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path?we.path="/"+ie.path:Q.path?we.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+ie.path:we.path=ie.path,we.path=ze(we.path)),we.query=ie.query):(we.path=Q.path,ie.query!==void 0?we.query=ie.query:we.query=Q.query),we.userinfo=Q.userinfo,we.host=Q.host,we.port=Q.port),we.scheme=Q.scheme),we.fragment=ie.fragment,we}function tr(Q,ie,oe){var ye=c({scheme:"null"},oe);return Ft(Ir(pe(Q,ye),pe(ie,ye),ye,!0),ye)}function At(Q,ie){return typeof Q=="string"?Q=Ft(pe(Q,ie),ie):a(Q)==="object"&&(Q=pe(Ft(Q,ie),ie)),Q}function T(Q,ie,oe){return typeof Q=="string"?Q=Ft(pe(Q,oe),oe):a(Q)==="object"&&(Q=Ft(Q,oe)),typeof ie=="string"?ie=Ft(pe(ie,oe),oe):a(ie)==="object"&&(ie=Ft(ie,oe)),Q===ie}function M(Q,ie){return Q&&Q.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Y)}function L(Q,ie){return Q&&Q.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,ne)}var te={scheme:"http",domainHost:!0,parse:function(Q,ie){return Q.host||(Q.error=Q.error||"HTTP URIs must have a host."),Q},serialize:function(Q,ie){var oe=String(Q.scheme).toLowerCase()==="https";return(Q.port===(oe?443:80)||Q.port==="")&&(Q.port=void 0),Q.path||(Q.path="/"),Q}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(Q){return typeof Q.secure=="boolean"?Q.secure:String(Q.scheme).toLowerCase()==="wss"}var be={scheme:"ws",domainHost:!0,parse:function(Q,ie){var oe=Q;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(Q,ie){if((Q.port===(he(Q)?443:80)||Q.port==="")&&(Q.port=void 0),typeof Q.secure=="boolean"&&(Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0),Q.resourceName){var oe=Q.resourceName.split("?"),ye=f(oe,2),we=ye[0],Ue=ye[1];Q.path=we&&we!=="/"?we:void 0,Q.query=Ue,Q.resourceName=void 0}return Q.fragment=void 0,Q}},Rt={scheme:"wss",domainHost:be.domainHost,parse:be.parse,serialize:be.serialize},Ln={},Or=!0,lr="[A-Za-z0-9\\-\\.\\_\\~"+(Or?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",rr="[0-9A-Fa-f]",oz=s(s("%[EFef]"+rr+"%"+rr+rr+"%"+rr+rr)+"|"+s("%[89A-Fa-f]"+rr+"%"+rr+rr)+"|"+s("%"+rr+rr)),az="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",cz="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",dz=n(cz,'[\\"\\\\]'),uz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",lz=new RegExp(lr,"g"),zf=new RegExp(oz,"g"),fz=new RegExp(n("[^]",az,"[\\.]",'[\\"]',dz),"g"),HA=new RegExp(n("[^]",lr,uz),"g"),pz=HA;function jP(Q){var ie=ne(Q);return ie.match(lz)?ie:Q}var JA={scheme:"mailto",parse:function(Q,ie){var oe=Q,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var we=!1,Ue={},St=oe.query.split("&"),ar=0,Kr=St.length;ar<Kr;++ar){var zr=St[ar].split("=");switch(zr[0]){case"to":for(var Yt=zr[1].split(","),fn=0,$n=Yt.length;fn<$n;++fn)ye.push(Yt[fn]);break;case"subject":oe.subject=L(zr[1],ie);break;case"body":oe.body=L(zr[1],ie);break;default:we=!0,Ue[L(zr[0],ie)]=L(zr[1],ie);break}}we&&(oe.headers=Ue)}oe.query=void 0;for(var nn=0,mr=ye.length;nn<mr;++nn){var fr=ye[nn].split("@");if(fr[0]=L(fr[0]),ie.unicodeSupport)fr[1]=L(fr[1],ie).toLowerCase();else try{fr[1]=J.toASCII(L(fr[1],ie).toLowerCase())}catch(Ns){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ns}ye[nn]=fr.join("@")}return oe},serialize:function(Q,ie){var oe=Q,ye=i(Q.to);if(ye){for(var we=0,Ue=ye.length;we<Ue;++we){var St=String(ye[we]),ar=St.lastIndexOf("@"),Kr=St.slice(0,ar).replace(zf,jP).replace(zf,o).replace(fz,Y),zr=St.slice(ar+1);try{zr=ie.iri?J.toUnicode(zr):J.toASCII(L(zr,ie).toLowerCase())}catch(nn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+nn}ye[we]=Kr+"@"+zr}oe.path=ye.join(",")}var Yt=Q.headers=Q.headers||{};Q.subject&&(Yt.subject=Q.subject),Q.body&&(Yt.body=Q.body);var fn=[];for(var $n in Yt)Yt[$n]!==Ln[$n]&&fn.push($n.replace(zf,jP).replace(zf,o).replace(HA,Y)+"="+Yt[$n].replace(zf,jP).replace(zf,o).replace(pz,Y));return fn.length&&(oe.query=fn.join("&")),oe}},hz=/^([^\:]+)\:(.*)/,ZA={scheme:"urn",parse:function(Q,ie){var oe=Q.path&&Q.path.match(hz),ye=Q;if(oe){var we=ie.scheme||ye.scheme||"urn",Ue=oe[1].toLowerCase(),St=oe[2],ar=we+":"+(ie.nid||Ue),Kr=q[ar];ye.nid=Ue,ye.nss=St,ye.path=void 0,Kr&&(ye=Kr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(Q,ie){var oe=ie.scheme||Q.scheme||"urn",ye=Q.nid,we=oe+":"+(ie.nid||ye),Ue=q[we];Ue&&(Q=Ue.serialize(Q,ie));var St=Q,ar=Q.nss;return St.path=(ye||ie.nid)+":"+ar,St}},mz=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,YA={scheme:"urn:uuid",parse:function(Q,ie){var oe=Q;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(mz))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(Q,ie){var oe=Q;return oe.nss=(Q.uuid||"").toLowerCase(),oe}};q[te.scheme]=te,q[ae.scheme]=ae,q[be.scheme]=be,q[Rt.scheme]=Rt,q[JA.scheme]=JA,q[ZA.scheme]=ZA,q[YA.scheme]=YA,r.SCHEMES=q,r.pctEncChar=Y,r.pctDecChars=ne,r.parse=pe,r.removeDotSegments=ze,r.serialize=Ft,r.resolveComponents=Ir,r.resolve=tr,r.normalize=At,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),One=Bt((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])}`},"")}}`}}),YU=Bt((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":"")}}),rP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(rP||{}),Bs={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Ds=class QU{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=QU.DID_URI_PATTERN.exec(e);if(!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}};Ds.METHOD_PATTERN="([a-z0-9]+)",Ds.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Ds.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Ds.PCT_ENCODED_PATTERN})`,Ds.METHOD_ID_PATTERN=`((?:${Ds.ID_CHAR_PATTERN}*:)*(${Ds.ID_CHAR_PATTERN}+))`,Ds.PATH_PATTERN="(/[^#?]*)?",Ds.QUERY_PATTERN="([?][^#]*)?",Ds.FRAGMENT_PATTERN="(#.*)?",Ds.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Ds.METHOD_PATTERN+"):(?<id>"+Ds.METHOD_ID_PATTERN+")(?<path>"+Ds.PATH_PATTERN+")(?<query>"+Ds.QUERY_PATTERN+")(?<fragment>"+Ds.FRAGMENT_PATTERN+")$");var ls=Ds,We=class XU 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,XU)}},Mne=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidGatewayUri="invalidGatewayUri",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))(Mne||{}),Wo=class eL extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,eL)}},Li;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Li||(Li={}));var Bne=Rf(mne(),1);function Nne(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,w=p.length;S!==w&&p[S]===0;)S++,m++;for(var E=(w-S)*d+1>>>0,_=new Uint8Array(E);S!==w;){for(var I=p[S],D=0,N=E-1;(I!==0||D<y)&&N!==-1;N--,D++)I+=256*_[N]>>>0,_[N]=I%i>>>0,I=I/i>>>0;if(I!==0)throw new Error("Non-zero carry");y=D,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 w=(p.length-m)*u+1>>>0,E=new Uint8Array(w);p[m];){var _=r[p.charCodeAt(m)];if(_===255)return;for(var I=0,D=w-1;(_!==0||I<S)&&D!==-1;D--,I++)_+=i*E[D]>>>0,E[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");S=I,m++}if(p[m]!==" "){for(var N=w-S;N!==w&&E[N]===0;)N++;for(var $=new Uint8Array(y+(w-N)),F=y;N!==w;)$[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 Une=Nne,Lne=Une,Kne=Lne,u$e=new Uint8Array(0),zne=(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")},qne=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")}},Fne=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 tL(this,t)}},Gne=class{constructor(t){this.decoders=t}or(t){return tL(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`)}},tL=(t,e)=>new Gne({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Wne=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new qne(t,e,r),this.decoder=new Fne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},rL=({name:t,prefix:e,encode:r,decode:n})=>new Wne(t,e,r,n),nL=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=Kne(r,e);return rL({prefix:t,name:e,encode:n,decode:a=>KI(s(a))})},Vne=(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},Hne=(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},yo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>rL({prefix:e,name:t,encode(s){return Hne(s,n,r)},decode(s){return Vne(s,n,r,t)}}),x1=yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),l$e=yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),f$e=yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),p$e=yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),h$e=yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),m$e=yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),y$e=yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),g$e=yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kN=yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Fo=nL({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),w$e=nL({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),v$e=yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),b$e=yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hd=yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),P$e=yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Jne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Zne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function gI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Vg=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())})},_N=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,yf=new TextDecoder,Je=class Ni{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ni(e,"ArrayBuffer")}static asyncIterable(e){if(!Zne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ni(e,"AsyncIterable")}static base32Z(e){return new Ni(e,"Base32Z")}static base58Btc(e){return new Ni(e,"Base58Btc")}static base64Url(e){return new Ni(e,"Base64Url")}static bufferSource(e){return new Ni(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 Ni(e,"Hex")}static multibase(e){return new Ni(e,"Multibase")}static object(e){return new Ni(e,"Object")}static string(e){return new Ni(e,"String")}static uint8Array(e){return new Ni(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Fo.baseDecode(this.data).buffer;case"Base64Url":return hd.baseDecode(this.data).buffer;case"BufferSource":{if(gI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Jne(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 Vg(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 kN.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 Fo.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Fo.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 hd.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return hd.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=h1.encode(e);return hd.baseEncode(r)}case"String":{let e=h1.encode(this.data);return hd.baseEncode(e)}case"Uint8Array":return hd.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=_N(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 Ni.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ni.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=hd.baseDecode(this.data),r=yf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=yf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Vg(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 yf.decode(this.data);case"Base64Url":{let e=hd.baseDecode(this.data);return yf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return yf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=_N(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+=yf.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+=yf.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 kN.baseDecode(this.data);case"Base58Btc":return Fo.baseDecode(this.data);case"Base64Url":return hd.baseDecode(this.data);case"BufferSource":{let e=gI(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 Vg(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.`)}})}},mw;(function(t){t.Debug="debug",t.Silent="silent"})(mw||(mw={}));var Yne=class{constructor(){this.logLevel=mw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==mw.Silent&&console.info(t)}error(t){this.logLevel!==mw.Silent&&console.error(t)}},Qne=new Yne;typeof window<"u"&&(window.enboxLogger=Qne);var ew={};NI(ew,{decode:()=>F1,encodeTo:()=>gw,encodingLength:()=>ww});var Xne=sL,TN=128,ese=127,tse=~ese,rse=Math.pow(2,31);function sL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=rse;)e[r++]=t&255|TN,t/=128;for(;t&tse;)e[r++]=t&255|TN,t>>>=7;return e[r]=t|0,sL.bytes=r-n+1,e}var nse=wI,sse=128,IN=127;function wI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw wI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&IN)<<s:(o&IN)*Math.pow(2,s),s+=7}while(o>=sse);return wI.bytes=a-n,r}var ise=Math.pow(2,7),ose=Math.pow(2,14),ase=Math.pow(2,21),cse=Math.pow(2,28),dse=Math.pow(2,35),use=Math.pow(2,42),lse=Math.pow(2,49),fse=Math.pow(2,56),pse=Math.pow(2,63),hse=function(t){return t<ise?1:t<ose?2:t<ase?3:t<cse?4:t<dse?5:t<use?6:t<lse?7:t<fse?8:t<pse?9:10},mse={encode:Xne,decode:nse,encodingLength:hse},yse=mse,q1=yse,F1=(t,e=0)=>[q1.decode(t,e),q1.decode.bytes],gw=(t,e,r=0)=>(q1.encode(t,e,r),e),ww=t=>q1.encodingLength(t),gse=(t,e)=>{let r=e.byteLength,n=ww(t),s=n+ww(r),a=new Uint8Array(s+r);return gw(t,a,0),gw(r,a,n),a.set(e,s),new zI(t,r,e,a)},wse=t=>{let e=KI(t),[r,n]=F1(e),[s,a]=F1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new zI(r,s,o,e)},vse=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&zne(t.bytes,r.bytes)}},zI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},AN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Pse(r,vI(t),e||Fo.encoder);default:return xse(r,vI(t),e||x1.encoder)}},RN=new WeakMap,vI=t=>{let e=RN.get(t);if(e==null){let r=new Map;return RN.set(t,r),r}return e},x$e=class Ys{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!==Hg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Sse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ys.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=gse(e,r);return Ys.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 Ys.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&vse(e.multihash,n.multihash)}toString(e){return AN(this,e)}toJSON(){return{"/":AN(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 Ys)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Ys(n,s,a,o||DN(n,s,a.bytes))}else if(r[Ese]===!0){let{version:n,multihash:s,code:a}=r,o=wse(s);return Ys.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!==Hg)throw new Error(`Version 0 CID must use dag-pb (code: ${Hg}) block encoding`);return new Ys(e,r,n,n.bytes)}case 1:{let s=DN(e,r,n.bytes);return new Ys(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Ys.create(0,Hg,e)}static createV1(e,r){return Ys.create(1,e,r)}static decode(e){let[r,n]=Ys.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Ys.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?Ys.createV0(o):Ys.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=F1(e.subarray(r));return r+=f,l},s=n(),a=Hg;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]=bse(e,r),a=Ys.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vI(a).set(n,e),a}},bse=(t,e)=>{switch(t[0]){case"Q":{let r=e||Fo;return[Fo.prefix,r.decode(`${Fo.prefix}${t}`)]}case Fo.prefix:{let r=e||Fo;return[Fo.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)]}}},Pse=(t,e,r)=>{let{prefix:n}=r;if(n!==Fo.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},xse=(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},Hg=112,Sse=18,DN=(t,e,r)=>{let n=ww(t),s=n+ww(e),a=new Uint8Array(s+r.byteLength);return gw(t,a,0),gw(e,a,n),a.set(r,s),a},Ese=Symbol.for("@ipld/js-cid/CID"),Ho=class Uu{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=Uu.codeToName.has(n)?n:Uu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=ew.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),ew.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=ew.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Uu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Uu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Uu.codeToName.set(e.code,e.name),Uu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=ew.decode(r),a=Uu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Ho.codeToName=new Map;Ho.nameToCode=new Map;Ho.registerCodec({code:237,name:"ed25519-pub"});Ho.registerCodec({code:4864,name:"ed25519-priv"});Ho.registerCodec({code:236,name:"x25519-pub"});Ho.registerCodec({code:4866,name:"x25519-priv"});Ho.registerCodec({code:231,name:"secp256k1-pub"});Ho.registerCodec({code:4865,name:"secp256k1-priv"});function iL(t){Object.keys(t).forEach(e=>{let r=t[e];r===void 0?delete t[e]:r!==null&&typeof r=="object"&&iL(r)})}var S$e=Rf(ZU(),1),Au=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())})},kse=class{constructor(){this.store=new Map}clear(){return Au(this,void 0,void 0,function*(){this.store.clear()})}open(){return Au(this,void 0,void 0,function*(){})}close(){return Au(this,void 0,void 0,function*(){})}delete(t){return Au(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Au(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Au(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Au(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Au(this,void 0,void 0,function*(){this.store.set(t,e)})}},_se=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())})};function Tse(t){let e=t.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let r=e.indexOf("%");if(r!==-1&&(e=e.slice(0,r)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=aL(e);return n!==void 0?cL(n):e.includes(":")?Dse(e):!1}var Ise=["http:","https:"],S1=class extends Error{constructor(t){super(t),this.name="PublicUrlValidationError"}};function CN(t,e="URL",r){var n;let s=typeof t=="string"?new URL(t):new URL(t.toString()),a=(n=r?.allowedProtocols)!==null&&n!==void 0?n:Ise;if(!a.includes(s.protocol))throw new S1(`${e} must use one of the allowed schemes (${a.join(", ")}): ${s.protocol}`);if(s.hostname==="")throw new S1(`${e} must specify a hostname.`);if(Tse(s.hostname))throw new S1(`${e} must not target a private, loopback, or link-local host: ${s.hostname}`);return s}var Ase=5,Rse=new Set([301,302,303,307,308]);function oL(t,e,r){return _se(this,void 0,void 0,function*(){var n,s;let a=(n=r?.description)!==null&&n!==void 0?n:"URL",o=(s=r?.maxRedirects)!==null&&s!==void 0?s:Ase,i=CN(t,a,{allowedProtocols:r?.allowedProtocols}).href;for(let c=0;c<=o;c++){let u=yield fetch(i,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!Rse.has(u.status))return u;let d=u.headers.get("location");if(d===null)return u;i=CN(new URL(d,i),a,{allowedProtocols:r?.allowedProtocols}).href}throw new Error(`${a} exceeded the maximum number of redirects (${o}).`)})}function aL(t){let e=t.split(".");if(e.length!==4)return;let r=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(r.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return r}function cL([t,e]){return t===0||t===10||t===100&&e>=64&&e<=127||t===127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224}function Dse(t){let e=Cse(t);if(e===void 0)return!1;let[r,n,s,a,o,i,c,u]=e,d=r===0&&n===0&&s===0&&a===0&&o===0&&i===0;return e.every(l=>l===0)||d&&c===0&&u===1||(r&65024)===64512||(r&65472)===65152||(r&65280)===65280?!0:r===100&&n===65435&&s===0&&a===0&&o===0&&i===0||r===0&&n===0&&s===0&&a===0&&o===0&&i===65535?cL($se(c,u)):!!d}function Cse(t){let[e,r,n]=t.split("::");if(n!==void 0)return;let s=e===""?[]:e.split(":"),a=r===void 0||r===""?[]:r.split(":"),o=jse([...s,...a]);if(o===void 0||o.length>8||r===void 0&&o.length!==8||r!==void 0&&o.length>=8)return;let i=o.map(u=>/^[0-9a-f]{1,4}$/.test(u)?Number.parseInt(u,16):Number.NaN);if(!i.every(u=>Number.isInteger(u)&&u>=0&&u<=65535))return;if(r===void 0)return i;let c=new Array(8-i.length).fill(0);return[...i.slice(0,s.length),...c,...i.slice(s.length)]}function jse(t){let e=t.at(-1);if(!e?.includes("."))return t;let r=aL(e);if(r===void 0)return;let[n,s,a,o]=r;return[...t.slice(0,-1),((n<<8|s)&65535).toString(16),((a<<8|o)&65535).toString(16)]}function $se(t,e){return[t>>8&255,t&255,e>>8&255,e&255]}var nP=class{},dL={};NI(dL,{bitGet:()=>Kse,bitLen:()=>Lse,bitMask:()=>FI,bitSet:()=>zse,bytesToHex:()=>Tf,bytesToNumberBE:()=>Ef,bytesToNumberLE:()=>Fu,concatBytes:()=>If,createHmacDrbg:()=>fL,ensureBytes:()=>Cn,equalBytes:()=>Nse,hexToBytes:()=>qh,hexToNumber:()=>qI,isBytes:()=>xc,numberToBytesBE:()=>Sc,numberToBytesLE:()=>Fh,numberToHexUnpadded:()=>lL,numberToVarBytesBE:()=>Bse,utf8ToBytes:()=>Use,validateObject:()=>Df});var uL=BigInt(0),sP=BigInt(1),Ose=BigInt(2);function xc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Mse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Tf(t){if(!xc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Mse[t[r]];return e}function lL(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 md={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function jN(t){if(t>=md._0&&t<=md._9)return t-md._0;if(t>=md._A&&t<=md._F)return t-(md._A-10);if(t>=md._a&&t<=md._f)return t-(md._a-10)}function qh(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=jN(t.charCodeAt(a)),i=jN(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 Ef(t){return qI(Tf(t))}function Fu(t){if(!xc(t))throw new Error("Uint8Array expected");return qI(Tf(Uint8Array.from(t).reverse()))}function Sc(t,e){return qh(t.toString(16).padStart(e*2,"0"))}function Fh(t,e){return Sc(t,e).reverse()}function Bse(t){return qh(lL(t))}function Cn(t,e,r){let n;if(typeof e=="string")try{n=qh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(xc(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 If(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!xc(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 Nse(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 Use(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Lse(t){let e;for(e=0;t>uL;t>>=sP,e+=1);return e}function Kse(t,e){return t>>BigInt(e)&sP}var zse=(t,e,r)=>t|(r?sP:uL)<<BigInt(e),FI=t=>(Ose<<BigInt(t-1))-sP,aI=t=>new Uint8Array(t),$N=t=>Uint8Array.from(t);function fL(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=aI(t),s=aI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=aI())=>{s=i($N([0]),d),n=i(),d.length!==0&&(s=i($N([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 If(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var qse={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"||xc(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 Df(t,e,r={}){let n=(s,a,o)=>{let i=qse[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 ON(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Fse(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function pL(t,...e){if(!Fse(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 Gse(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ON(t.outputLen),ON(t.blockLen)}function G1(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 Wse(t,e){pL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var cI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function hL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var dI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),hc=(t,e)=>t<<32-e|t>>>e,Vse=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Vse)throw new Error("Non little-endian hardware is not supported");function mL(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=mL(t)),!hL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function yL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!hL(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 gL=class{clone(){return this._cloneInto()}},E$e={}.toString;function wL(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(cI&&typeof cI.getRandomValues=="function")return cI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Hse(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 vL=class extends gL{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=dI(this.buffer)}update(t){G1(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=dI(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){G1(this),Wse(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;Hse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=dI(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,Zse=(t,e,r)=>t&e^t&r^e&r,Yse=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]),Ru=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Du=new Uint32Array(64),Qse=class extends vL{constructor(){super(64,32,8,!1),this.A=Ru[0]|0,this.B=Ru[1]|0,this.C=Ru[2]|0,this.D=Ru[3]|0,this.E=Ru[4]|0,this.F=Ru[5]|0,this.G=Ru[6]|0,this.H=Ru[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)Du[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Du[d-15],f=Du[d-2],h=hc(l,7)^hc(l,18)^l>>>3,p=hc(f,17)^hc(f,19)^f>>>10;Du[d]=p+Du[d-7]+h+Du[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=hc(o,6)^hc(o,11)^hc(o,25),f=u+l+Jse(o,i,c)+Yse[d]+Du[d]|0,h=(hc(r,2)^hc(r,13)^hc(r,22))+Zse(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(){Du.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},bL=wL(()=>new Qse),Qn=BigInt(0),rn=BigInt(1),vf=BigInt(2),Xse=BigInt(3),bI=BigInt(4),MN=BigInt(5),BN=BigInt(8),k$e=BigInt(9),eie=BigInt(16);function Lr(t,e){let r=t%e;return r>=Qn?r:e+r}function PL(t,e,r){if(r<=Qn||e<Qn)throw new Error("Expected power/modulo > 0");if(r===rn)return Qn;let n=rn;for(;e>Qn;)e&rn&&(n=n*t%r),t=t*t%r,e>>=rn;return n}function dn(t,e,r){let n=t;for(;e-- >Qn;)n*=n,n%=r;return n}function PI(t,e){if(t===Qn||e<=Qn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Lr(t,e),n=e,s=Qn,a=rn,o=rn,i=Qn;for(;r!==Qn;){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!==rn)throw new Error("invert: does not exist");return Lr(s,e)}function tie(t){let e=(t-rn)/vf,r,n,s;for(r=t-rn,n=0;r%vf===Qn;r/=vf,n++);for(s=vf;s<t&&PL(s,e,t)!==t-rn;s++);if(n===1){let o=(t+rn)/bI;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+rn)/vf;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,rn<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function rie(t){if(t%bI===Xse){let e=(t+rn)/bI;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%BN===MN){let e=(t-MN)/BN;return function(r,n){let s=r.mul(n,vf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,vf),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%eie,tie(t)}var nie=(t,e)=>(Lr(t,e)&rn)===rn,sie=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iie(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=sie.reduce((n,s)=>(n[s]="function",n),e);return Df(t,r)}function oie(t,e,r){if(r<Qn)throw new Error("Expected power > 0");if(r===Qn)return t.ONE;if(r===rn)return e;let n=t.ONE,s=e;for(;r>Qn;)r&rn&&(n=t.mul(n,s)),s=t.sqr(s),r>>=rn;return n}function aie(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 xL(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<=Qn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=xL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=rie(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:FI(s),ZERO:Qn,ONE:rn,create:c=>Lr(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Qn<=c&&c<t},is0:c=>c===Qn,isOdd:c=>(c&rn)===rn,neg:c=>Lr(-c,t),eql:(c,u)=>c===u,sqr:c=>Lr(c*c,t),add:(c,u)=>Lr(c+u,t),sub:(c,u)=>Lr(c-u,t),mul:(c,u)=>Lr(c*u,t),pow:(c,u)=>oie(i,c,u),div:(c,u)=>Lr(c*PI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>PI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>aie(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Fh(c,a):Sc(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Fu(c):Ef(c)}});return Object.freeze(i)}function cie(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 SL(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 EL(t){let e=SL(t);return e+Math.ceil(e/2)}function die(t,e,r=!1){let n=t.length,s=SL(e),a=EL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?Ef(t):Fu(t),i=Lr(o,e-rn)+rn;return r?Fh(i,s):Sc(i,s)}var uie=BigInt(0),uI=BigInt(1);function kL(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>uie;)a&uI&&(o=o.add(i)),i=i.double(),a>>=uI;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+=uI);let S=m,w=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[w]))}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 iie(t.Fp),Df(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...xL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function lie(t){let e=HI(t);Df(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:fie,hexToBytes:pie}=dL,xf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=xf;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:fie(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=xf,r=typeof t=="string"?pie(t):t;if(!xc(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}=xf._parseInt(r.subarray(2)),{d:o,l:i}=xf._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}`}},Pd=BigInt(0),qo=BigInt(1),_$e=BigInt(2),NN=BigInt(3),T$e=BigInt(4);function hie(t){let e=lie(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return If(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),w=r.mul(S,p);return r.add(r.add(w,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"&&Pd<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:w}=e;if(m&&typeof p!="bigint"){if(xc(p)&&(p=Tf(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:Ef(Cn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Lr(E,w)),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 w=E=>r.eql(E,r.ZERO);return w(y)&&w(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,w)=>S.toAffine(y[w])).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),w=a(m);if(!r.eql(S,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:S,pz:w}=this,{px:E,py:_,pz:I}=m,D=r.eql(r.mul(y,I),r.mul(E,w)),N=r.eql(r.mul(S,I),r.mul(_,w));return D&&N}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,NN),{px:w,py:E,pz:_}=this,I=r.ZERO,D=r.ZERO,N=r.ZERO,$=r.mul(w,w),F=r.mul(E,E),z=r.mul(_,_),B=r.mul(w,E);return B=r.add(B,B),N=r.mul(w,_),N=r.add(N,N),I=r.mul(m,N),D=r.mul(S,z),D=r.add(I,D),I=r.sub(F,D),D=r.add(F,D),D=r.mul(I,D),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),D=r.add(D,$),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,D,N)}add(m){d(m);let{px:y,py:S,pz:w}=this,{px:E,py:_,pz:I}=m,D=r.ZERO,N=r.ZERO,$=r.ZERO,F=e.a,z=r.mul(e.b,NN),B=r.mul(y,E),H=r.mul(S,_),X=r.mul(w,I),R=r.add(y,S),j=r.add(E,_);R=r.mul(R,j),j=r.add(B,H),R=r.sub(R,j),j=r.add(y,w);let x=r.add(E,I);return j=r.mul(j,x),x=r.add(B,X),j=r.sub(j,x),x=r.add(S,w),D=r.add(_,I),x=r.mul(x,D),D=r.add(H,X),x=r.sub(x,D),$=r.mul(F,j),D=r.mul(z,X),$=r.add(D,$),D=r.sub(H,$),$=r.add(H,$),N=r.mul(D,$),H=r.add(B,B),H=r.add(H,B),X=r.mul(F,X),j=r.mul(z,j),H=r.add(H,X),X=r.sub(B,X),X=r.mul(F,X),j=r.add(j,X),B=r.mul(H,j),N=r.add(N,B),B=r.mul(x,j),D=r.mul(R,D),D=r.sub(D,B),B=r.mul(R,H),$=r.mul(x,$),$=r.add($,B),new l(D,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(w=>w.pz));return y.map((w,E)=>w.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Pd)return y;if(i(m),m===qo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:w,k1:E,k2neg:_,k2:I}=S.splitScalar(m),D=y,N=y,$=this;for(;E>Pd||I>Pd;)E&qo&&(D=D.add($)),I&qo&&(N=N.add($)),$=$.double(),E>>=qo,I>>=qo;return w&&(D=D.negate()),_&&(N=N.negate()),N=new l(r.mul(N.px,S.beta),N.py,N.pz),D.add(N)}multiply(m){i(m);let y=m,S,w,{endo:E}=e;if(E){let{k1neg:_,k1:I,k2neg:D,k2:N}=E.splitScalar(y),{p:$,f:F}=this.wNAF(I),{p:z,f:B}=this.wNAF(N);$=h.constTimeNegate(_,$),z=h.constTimeNegate(D,z),z=new l(r.mul(z.px,E.beta),z.py,z.pz),S=$.add(z),w=F.add(B)}else{let{p:_,f:I}=this.wNAF(y);S=_,w=I}return l.normalizeZ([S,w])[0]}multiplyAndAddUnsafe(m,y,S){let w=l.BASE,E=(I,D)=>D===Pd||D===qo||!I.equals(w)?I.multiplyUnsafe(D):I.multiply(D),_=E(this,y).add(E(m,S));return _.is0()?void 0:_}toAffine(m){let{px:y,py:S,pz:w}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(w));let _=r.mul(y,m),I=r.mul(S,m),D=r.mul(w,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===qo)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===qo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Tf(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=kL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function mie(t){let e=HI(t);return Df(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function yie(t){let e=mie(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o(j){return Pd<j&&j<r.ORDER}function i(j){return Lr(j,n)}function c(j){return PI(j,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=hie({...e,toBytes(j,x,P){let b=x.toAffine(),k=r.toBytes(b.x),A=If;return P?A(Uint8Array.from([x.hasEvenY()?2:3]),k):A(Uint8Array.from([4]),k,r.toBytes(b.y))},fromBytes(j){let x=j.length,P=j[0],b=j.subarray(1);if(x===s&&(P===2||P===3)){let k=Ef(b);if(!o(k))throw new Error("Point is not on curve");let A=l(k),O=r.sqrt(A),K=(O&qo)===qo;return(P&1)===1!==K&&(O=r.neg(O)),{x:k,y:O}}else if(x===a&&P===4){let k=r.fromBytes(b.subarray(0,r.BYTES)),A=r.fromBytes(b.subarray(r.BYTES,2*r.BYTES));return{x:k,y:A}}else throw new Error(`Point of length ${x} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=j=>Tf(Sc(j,e.nByteLength));function p(j){let x=n>>qo;return j>x}function m(j){return p(j)?i(-j):j}let y=(j,x,P)=>Ef(j.slice(x,P));class S{constructor(x,P,b){this.r=x,this.s=P,this.recovery=b,this.assertValidity()}static fromCompact(x){let P=e.nByteLength;return x=Cn("compactSignature",x,P*2),new S(y(x,0,P),y(x,P,2*P))}static fromDER(x){let{r:P,s:b}=xf.toSig(Cn("DER",x));return new S(P,b)}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(x){return new S(this.r,this.s,x)}recoverPublicKey(x){let{r:P,s:b,recovery:k}=this,A=N(Cn("msgHash",x));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let O=k===2||k===3?P+e.n:P;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let K=k&1?"03":"02",G=u.fromHex(K+h(O)),V=c(O),W=i(-A*V),J=i(b*V),q=u.BASE.multiplyAndAddUnsafe(G,W,J);if(!q)throw new Error("point at infinify");return q.assertValidity(),q}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qh(this.toDERHex())}toDERHex(){return xf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(j){try{return d(j),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let j=EL(e.n);return die(e.randomBytes(j),e.n)},precompute(j=8,x=u.BASE){return x._setWindowSize(j),x.multiply(BigInt(3)),x}};function E(j,x=!0){return u.fromPrivateKey(j).toRawBytes(x)}function _(j){let x=xc(j),P=typeof j=="string",b=(x||P)&&j.length;return x?b===s||b===a:P?b===2*s||b===2*a:j instanceof u}function I(j,x,P=!0){if(_(j))throw new Error("first arg must be private key");if(!_(x))throw new Error("second arg must be public key");return u.fromHex(x).multiply(d(j)).toRawBytes(P)}let D=e.bits2int||function(j){let x=Ef(j),P=j.length*8-e.nBitLength;return P>0?x>>BigInt(P):x},N=e.bits2int_modN||function(j){return i(D(j))},$=FI(e.nBitLength);function F(j){if(typeof j!="bigint")throw new Error("bigint expected");if(!(Pd<=j&&j<$))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Sc(j,e.nByteLength)}function z(j,x,P=B){if(["recovered","canonical"].some(ne=>ne in P))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:k}=e,{lowS:A,prehash:O,extraEntropy:K}=P;A==null&&(A=!0),j=Cn("msgHash",j),O&&(j=Cn("prehashed msgHash",b(j)));let G=N(j),V=d(x),W=[F(V),F(G)];if(K!=null){let ne=K===!0?k(r.BYTES):K;W.push(Cn("extraEntropy",ne))}let J=If(...W),q=G;function Y(ne){let se=D(ne);if(!f(se))return;let Z=c(se),ce=u.BASE.multiply(se).toAffine(),fe=i(ce.x);if(fe===Pd)return;let ue=i(Z*i(q+fe*V));if(ue===Pd)return;let Pe=(ce.x===fe?0:2)|Number(ce.y&qo),pe=ue;return A&&p(ue)&&(pe=m(ue),Pe^=1),new S(fe,pe,Pe)}return{seed:J,k2sig:Y}}let B={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function X(j,x,P=B){let{seed:b,k2sig:k}=z(j,x,P),A=e;return fL(A.hash.outputLen,A.nByteLength,A.hmac)(b,k)}u.BASE._setWindowSize(8);function R(j,x,P,b=H){let k=j;if(x=Cn("msgHash",x),P=Cn("publicKey",P),"strict"in b)throw new Error("options.strict was renamed to lowS");let{lowS:A,prehash:O}=b,K,G;try{if(typeof k=="string"||xc(k))try{K=S.fromDER(k)}catch(Z){if(!(Z instanceof xf.Err))throw Z;K=S.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Z,s:ce}=k;K=new S(Z,ce)}else throw new Error("PARSE");G=u.fromHex(P)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(A&&K.hasHighS())return!1;O&&(x=e.hash(x));let{r:V,s:W}=K,J=N(x),q=c(W),Y=i(J*q),ne=i(V*q),se=u.BASE.multiplyAndAddUnsafe(G,Y,ne)?.toAffine();return se?i(se.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:I,sign:X,verify:R,ProjectivePoint:u,Signature:S,utils:w}}var _L=class extends gL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Gse(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 G1(this),this.iHash.update(t),this}digestInto(t){G1(this),pL(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()}},TL=(t,e,r)=>new _L(t,e).update(r).digest();TL.create=(t,e)=>new _L(t,e);function gie(t){return{hash:t,hmac:(e,...r)=>TL(t,e,yL(...r)),randomBytes:WI}}function IL(t,e){let r=n=>yie({...t,...gie(n)});return Object.freeze({...r(e),create:r})}var AL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),UN=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),wie=BigInt(1),xI=BigInt(2),LN=(t,e)=>(t+e/xI)/e;function vie(t){let e=AL,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=dn(d,r,e)*d%e,f=dn(l,r,e)*d%e,h=dn(f,xI,e)*u%e,p=dn(h,s,e)*h%e,m=dn(p,a,e)*p%e,y=dn(m,i,e)*m%e,S=dn(y,c,e)*y%e,w=dn(S,i,e)*m%e,E=dn(w,r,e)*d%e,_=dn(E,o,e)*p%e,I=dn(_,n,e)*u%e,D=dn(I,xI,e);if(!SI.eql(SI.sqr(D),t))throw new Error("Cannot find square root");return D}var SI=VI(AL,void 0,void 0,{sqrt:vie}),fo=IL({a:BigInt(0),b:BigInt(7),Fp:SI,n:UN,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=UN,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-wie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=LN(a*t,e),c=LN(-n*t,e),u=Lr(t-i*r-c*s,e),d=Lr(-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}}}},bL),I$e=BigInt(0),A$e=fo.ProjectivePoint;function bie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function RL(t,...e){if(!bie(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 KN(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 Pie(t,e){RL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var E1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,lI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,R$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function DL(t){return typeof t=="string"&&(t=xie(t)),RL(t),t}var Sie=class{clone(){return this._cloneInto()}},D$e={}.toString;function Eie(t){let e=n=>t().update(DL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function kie(t=32){if(E1&&typeof E1.getRandomValues=="function")return E1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function _ie(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 Tie=(t,e,r)=>t&e^~t&r,Iie=(t,e,r)=>t&e^t&r^e&r,Aie=class extends Sie{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=lI(this.buffer)}update(t){KN(this);let{view:e,buffer:r,blockLen:n}=this;t=DL(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=lI(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){KN(this),Pie(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;_ie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=lI(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}},Rie=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]),Cu=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ju=new Uint32Array(64),Die=class extends Aie{constructor(){super(64,32,8,!1),this.A=Cu[0]|0,this.B=Cu[1]|0,this.C=Cu[2]|0,this.D=Cu[3]|0,this.E=Cu[4]|0,this.F=Cu[5]|0,this.G=Cu[6]|0,this.H=Cu[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)ju[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=ju[d-15],f=ju[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;ju[d]=p+ju[d-7]+h+ju[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+Tie(o,i,c)+Rie[d]+ju[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+Iie(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(){ju.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},vw=Eie(()=>new Die);function Cie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort((o,i)=>o.localeCompare(i)),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var jie=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())})},CL=class{static digest(t){return jie(this,arguments,void 0,function*({data:e}){return vw(e)})}},$ie=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())})},zN="urn:jwk:";function ur(t){return $ie(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}`);iL(n);let s=Cie(n),a=Je.string(s).toUint8Array(),o=yield CL.digest({data:a});return Je.uint8Array(o).toBase64Url()})}function kf(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 Ed(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 Oie(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 As=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())})},Mie=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},js=class gc{static adjustSignatureToLowS(e){return As(this,arguments,void 0,function*({signature:r}){let n=fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static compressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return As(this,arguments,void 0,function*({key:r}){let n=yield gc.privateKeyToBytes({privateKey:r}),s=yield gc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Je.uint8Array(s.x).toBase64Url(),y:Je.uint8Array(s.y).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertDerToCompactSignature(e){return As(this,arguments,void 0,function*({derSignature:r}){return fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return As(this,void 0,void 0,function*(){let e=fo.utils.randomPrivateKey(),r=yield gc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return As(this,arguments,void 0,function*({key:r}){var n;if(!(kf(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=Mie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return As(this,arguments,void 0,function*({privateKey:r}){if(!kf(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return As(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=Je.base64Url(r.x).toUint8Array(),a=Je.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return As(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 gc.privateKeyToBytes({privateKey:r}),a=yield gc.publicKeyToBytes({publicKey:n});return fo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return As(this,arguments,void 0,function*({data:r,key:n}){let s=yield gc.privateKeyToBytes({privateKey:n}),a=vw(r);return fo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){return fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){try{fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return As(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield gc.publicKeyToBytes({publicKey:r}),o=vw(s);return fo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return As(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=fo.getPublicKey(r));let n=fo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},jL=VI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Bie=jL.create(BigInt("-3")),Nie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Uie=IL({a:Bie,b:Nie,Fp:jL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},bL),No=Uie,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())})},Lie=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},Qs=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=No.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:"P-256",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({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:"P-256",x:Je.uint8Array(n.x).toBase64Url(),y:Je.uint8Array(n.y).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return No.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:"P-256",x:Je.uint8Array(s.x).toBase64Url(),y:Je.uint8Array(s.y).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return No.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return No.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=No.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(kf(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=Lie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!kf(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(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=Je.base64Url(r.x).toUint8Array(),a=Je.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("Secp256r1: 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 No.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=vw(r);return No.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return No.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{No.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=vw(s);return No.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=No.getPublicKey(r));let n=No.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},yd=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())})},qN=class extends nP{bytesToPrivateKey(t){return yd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Qs.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return yd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Qs.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Qs.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return yd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield js.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield Qs.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Qs.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return yd(this,arguments,void 0,function*({key:e,data:r}){if(!kf(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield js.sign({key:e,data:r});case"P-256":return yield Qs.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return yd(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 js.verify({key:e,signature:r,data:n});case"P-256":return yield Qs.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return yd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield js.privateKeyToBytes({privateKey:e});case"P-256":return yield Qs.privateKeyToBytes({privateKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return yd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield js.publicKeyToBytes({publicKey:e});case"P-256":return yield Qs.publicKeyToBytes({publicKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},m1=BigInt(4294967295),EI=BigInt(32);function $L(t,e=!1){return e?{h:Number(t&m1),l:Number(t>>EI&m1)}:{h:Number(t>>EI&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}=$L(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var zie=(t,e)=>BigInt(t>>>0)<<EI|BigInt(e>>>0),qie=(t,e,r)=>t>>>r,Fie=(t,e,r)=>t<<32-r|e>>>r,Gie=(t,e,r)=>t>>>r|e<<32-r,Wie=(t,e,r)=>t<<32-r|e>>>r,Vie=(t,e,r)=>t<<64-r|e>>>r-32,Hie=(t,e,r)=>t>>>r-32|e<<64-r,Jie=(t,e)=>e,Zie=(t,e)=>t,Yie=(t,e,r)=>t<<r|e>>>32-r,Qie=(t,e,r)=>e<<r|t>>>32-r,Xie=(t,e,r)=>e<<r-32|t>>>64-r,eoe=(t,e,r)=>t<<r-32|e>>>64-r;function toe(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var roe=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),noe=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,soe=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),ioe=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,ooe=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),aoe=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,coe={fromBig:$L,split:Kie,toBig:zie,shrSH:qie,shrSL:Fie,rotrSH:Gie,rotrSL:Wie,rotrBH:Vie,rotrBL:Hie,rotr32H:Jie,rotr32L:Zie,rotlSH:Yie,rotlSL:Qie,rotlBH:Xie,rotlBL:eoe,add:toe,add3L:roe,add3H:noe,add4L:soe,add4H:ioe,add5H:aoe,add5L:ooe},Et=coe,[doe,uoe]=Et.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))),$u=new Uint32Array(80),Ou=new Uint32Array(80),loe=class extends vL{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 w=0;w<16;w++,e+=4)$u[w]=t.getUint32(e),Ou[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let E=$u[w-15]|0,_=Ou[w-15]|0,I=Et.rotrSH(E,_,1)^Et.rotrSH(E,_,8)^Et.shrSH(E,_,7),D=Et.rotrSL(E,_,1)^Et.rotrSL(E,_,8)^Et.shrSL(E,_,7),N=$u[w-2]|0,$=Ou[w-2]|0,F=Et.rotrSH(N,$,19)^Et.rotrBH(N,$,61)^Et.shrSH(N,$,6),z=Et.rotrSL(N,$,19)^Et.rotrBL(N,$,61)^Et.shrSL(N,$,6),B=Et.add4L(D,z,Ou[w-7],Ou[w-16]),H=Et.add4H(B,I,F,$u[w-7],$u[w-16]);$u[w]=H|0,Ou[w]=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 w=0;w<80;w++){let E=Et.rotrSH(d,l,14)^Et.rotrSH(d,l,18)^Et.rotrBH(d,l,41),_=Et.rotrSL(d,l,14)^Et.rotrSL(d,l,18)^Et.rotrBL(d,l,41),I=d&f^~d&p,D=l&h^~l&m,N=Et.add5L(S,_,D,uoe[w],Ou[w]),$=Et.add5H(N,y,E,I,doe[w],$u[w]),F=N|0,z=Et.rotrSH(r,n,28)^Et.rotrBH(r,n,34)^Et.rotrBH(r,n,39),B=Et.rotrSL(r,n,28)^Et.rotrBL(r,n,34)^Et.rotrBL(r,n,39),H=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}=Et.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 R=Et.add3L(F,B,X);r=Et.add3H(R,$,z,H),n=R|0}({h:r,l:n}=Et.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Et.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Et.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Et.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Et.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Et.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Et.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Et.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(){$u.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)}},OL=wL(()=>new loe),_a=BigInt(0),uo=BigInt(1),y1=BigInt(2),foe=BigInt(8),poe={zip215:!0};function hoe(t){let e=HI(t);return Df(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=hoe(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=y1<<BigInt(i*8)-uo,d=r.create,l=e.uvRatio||((P,b)=>{try{return{isValid:!0,value:r.sqrt(P*r.inv(b))}}catch{return{isValid:!1,value:_a}}}),f=e.adjustScalarBytes||(P=>P),h=e.domain||((P,b,k)=>{if(b.length||k)throw new Error("Contexts/pre-hash are not supported");return P}),p=P=>typeof P=="bigint"&&_a<P,m=(P,b)=>p(P)&&p(b)&&P<b,y=P=>P===_a||m(P,u);function S(P,b){if(m(P,b))return P;throw new Error(`Expected valid scalar < ${b}, got ${typeof P} ${P}`)}function w(P){return P===_a?P:S(P,n)}let E=new Map;function _(P){if(!(P instanceof I))throw new Error("ExtendedPoint expected")}class I{constructor(b,k,A,O){if(this.ex=b,this.ey=k,this.ez=A,this.et=O,!y(b))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(b){if(b instanceof I)throw new Error("extended point not allowed");let{x:k,y:A}=b||{};if(!y(k)||!y(A))throw new Error("invalid affine point");return new I(k,A,uo,d(k*A))}static normalizeZ(b){let k=r.invertBatch(b.map(A=>A.ez));return b.map((A,O)=>A.toAffine(k[O])).map(I.fromAffine)}_setWindowSize(b){this._WINDOW_SIZE=b,E.delete(this)}assertValidity(){let{a:b,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:A,ey:O,ez:K,et:G}=this,V=d(A*A),W=d(O*O),J=d(K*K),q=d(J*J),Y=d(V*b),ne=d(J*d(Y+W)),se=d(q+d(k*d(V*W)));if(ne!==se)throw new Error("bad point: equation left != right (1)");let Z=d(A*O),ce=d(K*G);if(Z!==ce)throw new Error("bad point: equation left != right (2)")}equals(b){_(b);let{ex:k,ey:A,ez:O}=this,{ex:K,ey:G,ez:V}=b,W=d(k*V),J=d(K*O),q=d(A*V),Y=d(G*O);return W===J&&q===Y}is0(){return this.equals(I.ZERO)}negate(){return new I(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:b}=e,{ex:k,ey:A,ez:O}=this,K=d(k*k),G=d(A*A),V=d(y1*d(O*O)),W=d(b*K),J=k+A,q=d(d(J*J)-K-G),Y=W+G,ne=Y-V,se=W-G,Z=d(q*ne),ce=d(Y*se),fe=d(q*se),ue=d(ne*Y);return new I(Z,ce,ue,fe)}add(b){_(b);let{a:k,d:A}=e,{ex:O,ey:K,ez:G,et:V}=this,{ex:W,ey:J,ez:q,et:Y}=b;if(k===BigInt(-1)){let ki=d((K-O)*(J+W)),ze=d((K+O)*(J-W)),Ft=d(ze-ki);if(Ft===_a)return this.double();let Ir=d(G*y1*Y),tr=d(V*y1*q),At=tr+Ir,T=ze+ki,M=tr-Ir,L=d(At*Ft),te=d(T*M),ae=d(At*M),he=d(Ft*T);return new I(L,te,he,ae)}let ne=d(O*W),se=d(K*J),Z=d(V*A*Y),ce=d(G*q),fe=d((O+K)*(W+J)-ne-se),ue=ce-Z,Pe=ce+Z,pe=d(se-k*ne),Ee=d(fe*ue),bt=d(Pe*pe),Un=d(fe*pe),Tr=d(ue*Pe);return new I(Ee,bt,Tr,Un)}subtract(b){return this.add(b.negate())}wNAF(b){return $.wNAFCached(this,E,b,I.normalizeZ)}multiply(b){let{p:k,f:A}=this.wNAF(S(b,n));return I.normalizeZ([k,A])[0]}multiplyUnsafe(b){let k=w(b);return k===_a?N:this.equals(N)||k===uo?this:this.equals(D)?this.wNAF(k).p:$.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return $.unsafeLadder(this,n).is0()}toAffine(b){let{ex:k,ey:A,ez:O}=this,K=this.is0();b==null&&(b=K?foe:r.inv(O));let G=d(k*b),V=d(A*b),W=d(O*b);if(K)return{x:_a,y:uo};if(W!==uo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:b}=e;return b===uo?this:this.multiplyUnsafe(b)}static fromHex(b,k=!1){let{d:A,a:O}=e,K=r.BYTES;b=Cn("pointHex",b,K);let G=b.slice(),V=b[K-1];G[K-1]=V&-129;let W=Fu(G);W===_a||(k?S(W,u):S(W,r.ORDER));let J=d(W*W),q=d(J-uo),Y=d(A*J-O),{isValid:ne,value:se}=l(q,Y);if(!ne)throw new Error("Point.fromHex: invalid y coordinate");let Z=(se&uo)===uo,ce=(V&128)!==0;if(!k&&se===_a&&ce)throw new Error("Point.fromHex: x=0 and x_0=1");return ce!==Z&&(se=d(-se)),I.fromAffine({x:se,y:W})}static fromPrivateKey(b){return B(b).point}toRawBytes(){let{x:b,y:k}=this.toAffine(),A=Fh(k,r.BYTES);return A[A.length-1]|=b&uo?128:0,A}toHex(){return Tf(this.toRawBytes())}}I.BASE=new I(e.Gx,e.Gy,uo,d(e.Gx*e.Gy)),I.ZERO=new I(_a,uo,uo,_a);let{BASE:D,ZERO:N}=I,$=kL(I,i*8);function F(P){return Lr(P,n)}function z(P){return F(Fu(P))}function B(P){let b=i;P=Cn("private key",P,b);let k=Cn("hashed private key",a(P),2*b),A=f(k.slice(0,b)),O=k.slice(b,2*b),K=z(A),G=D.multiply(K),V=G.toRawBytes();return{head:A,prefix:O,scalar:K,point:G,pointBytes:V}}function H(P){return B(P).pointBytes}function X(P=new Uint8Array,...b){let k=If(...b);return z(a(h(k,Cn("context",P),!!s)))}function R(P,b,k={}){P=Cn("message",P),s&&(P=s(P));let{prefix:A,scalar:O,pointBytes:K}=B(b),G=X(k.context,A,P),V=D.multiply(G).toRawBytes(),W=X(k.context,V,K,P),J=F(G+W*O);w(J);let q=If(V,Fh(J,r.BYTES));return Cn("result",q,i*2)}let j=poe;function x(P,b,k,A=j){let{context:O,zip215:K}=A,G=r.BYTES;P=Cn("signature",P,2*G),b=Cn("message",b),s&&(b=s(b));let V=Fu(P.slice(G,2*G)),W,J,q;try{W=I.fromHex(k,K),J=I.fromHex(P.slice(0,G),K),q=D.multiplyUnsafe(V)}catch{return!1}if(!K&&W.isSmallOrder())return!1;let Y=X(O,J.toRawBytes(),W.toRawBytes(),b);return J.add(W.multiplyUnsafe(Y)).subtract(q).clearCofactor().equals(I.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:R,verify:x,ExtendedPoint:I,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>o(r.BYTES),precompute(P=8,b=I.BASE){return b._setWindowSize(P),b.multiply(BigInt(3)),b}}}}var Jg=BigInt(0),fI=BigInt(1);function moe(t){return Df(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function yoe(t){let e=moe(t),{P:r}=e,n=E=>Lr(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>PL(E,r-BigInt(2),r));function u(E,_,I){let D=n(E*(_-I));return _=n(_-D),I=n(I+D),[_,I]}function d(E){if(typeof E=="bigint"&&Jg<=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),D=d(_),N=I,$=fI,F=Jg,z=I,B=fI,H=Jg,X;for(let j=BigInt(s-1);j>=Jg;j--){let x=D>>j&fI;H^=x,X=u(H,$,z),$=X[0],z=X[1],X=u(H,F,B),F=X[0],B=X[1],H=x;let P=$+F,b=n(P*P),k=$-F,A=n(k*k),O=b-A,K=z+B,G=z-B,V=n(G*P),W=n(K*k),J=V+W,q=V-W;z=n(J*J),B=n(N*n(q*q)),$=n(b*A),F=n(O*(b+n(l*O)))}X=u(H,$,z),$=X[0],z=X[1],X=u(H,F,B),F=X[0],B=X[1];let R=c(F);return n($*R)}function h(E){return Fh(n(E),a)}function p(E){let _=Cn("u coordinate",E,a);return o===32&&(_[31]&=127),Fu(_)}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 Fu(i(_))}function y(E,_){let I=p(_),D=m(E),N=f(I,D);if(N===Jg)throw new Error("Invalid private or public key received");return h(N)}let S=h(e.Gu);function w(E){return y(E,S)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>w(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var bw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),C$e=BigInt(0),goe=BigInt(1),kI=BigInt(2),woe=BigInt(5),GN=BigInt(10),voe=BigInt(20),boe=BigInt(40),WN=BigInt(80);function ML(t){let e=bw,r=t*t%e*t%e,n=dn(r,kI,e)*r%e,s=dn(n,goe,e)*t%e,a=dn(s,woe,e)*s%e,o=dn(a,GN,e)*a%e,i=dn(o,voe,e)*o%e,c=dn(i,boe,e)*i%e,u=dn(c,WN,e)*c%e,d=dn(u,WN,e)*c%e,l=dn(d,GN,e)*a%e;return{pow_p_5_8:dn(l,kI,e)*t%e,b2:r}}function BL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Poe(t,e){let r=bw,n=Lr(e*e*e,r),s=Lr(n*n*e,r),a=ML(t*s).pow_p_5_8,o=Lr(t*n*a,r),i=Lr(e*o*o,r),c=o,u=Lr(o*FN,r),d=i===t,l=i===Lr(-t,r),f=i===Lr(-t*FN,r);return d&&(o=c),(l||f)&&(o=u),nie(o,r)&&(o=Lr(-o,r)),{isValid:d||l,value:o}}var Vo=VI(bw,void 0,!0),Pw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Vo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:OL,randomBytes:WI,adjustScalarBytes:BL,uvRatio:Poe},gf=YI(Pw);function NL(t,e,r){if(e.length>255)throw new Error("Context is too big");return yL(mL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var j$e=YI({...Pw,domain:NL}),$$e=YI({...Pw,domain:NL,prehash:OL}),tw=yoe({P:bw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=bw,{pow_p_5_8:r,b2:n}=ML(t);return Lr(dn(r,BigInt(3),e)*n,e)},adjustScalarBytes:BL,randomBytes:WI});function xoe(t){let{y:e}=gf.ExtendedPoint.fromHex(t),r=BigInt(1);return Vo.toBytes(Vo.create((r+e)*Vo.inv(r-e)))}function Soe(t){let e=Pw.hash(t.subarray(0,32));return Pw.adjustScalarBytes(e).subarray(0,32)}var Eoe=(Vo.ORDER+BigInt(3))/BigInt(8),O$e=Vo.pow(kI,Eoe),M$e=Vo.sqrt(Vo.neg(Vo.ONE)),B$e=(Vo.ORDER-BigInt(5))/BigInt(8),N$e=BigInt(486662),U$e=cie(Vo,Vo.neg(BigInt(486664))),L$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),K$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),z$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),q$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),F$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Uo=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())})},koe=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 Lu{static bytesToPrivateKey(e){return Uo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=gf.getPublicKey(r),s={crv:"Ed25519",d:Je.uint8Array(r).toBase64Url(),kty:"OKP",x:Je.uint8Array(n).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return Uo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Je.uint8Array(r).toBase64Url()};return n.kid=yield ur({jwk:n}),n})}static computePublicKey(e){return Uo(this,arguments,void 0,function*({key:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=gf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Uo(this,arguments,void 0,function*({privateKey:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=Soe(n),a=tw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Je.uint8Array(s).toBase64Url(),x:Je.uint8Array(a).toBase64Url()};return o.kid=yield ur({jwk:o}),o})}static convertPublicKeyToX25519(e){return Uo(this,arguments,void 0,function*({publicKey:r}){let n=yield Lu.publicKeyToBytes({publicKey:r});if(!(yield Lu.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=xoe(n),a={kty:"OKP",crv:"X25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static generateKey(){return Uo(this,void 0,void 0,function*(){let e=gf.utils.randomPrivateKey(),r=yield Lu.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Uo(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=koe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Uo(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Uo(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 Je.base64Url(r.x).toUint8Array()})}static sign(e){return Uo(this,arguments,void 0,function*({key:r,data:n}){let s=yield Lu.privateKeyToBytes({privateKey:r});return gf.sign(n,s)})}static validatePublicKey(e){return Uo(this,arguments,void 0,function*({publicKeyBytes:r}){try{gf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Uo(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Lu.publicKeyToBytes({publicKey:r});return gf.verify(n,s,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())})},_oe=class extends nP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield $s.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield $s.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(!ZI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield $s.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"Ed25519":return yield $s.privateKeyToBytes({privateKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield $s.publicKeyToBytes({publicKey:e});default:throw new Wo(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},Toe=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())})},Ioe=class extends nP{digest(t){return Toe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield CL.digest({data:r})}})}},Mu=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())})},Aoe=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},Ch=class rw{static bytesToPrivateKey(e){return Mu(this,arguments,void 0,function*({privateKeyBytes:r}){let n=tw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Je.uint8Array(r).toBase64Url(),x:Je.uint8Array(n).toBase64Url()};return s.kid=yield ur({jwk:s}),s})}static bytesToPublicKey(e){return Mu(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Je.uint8Array(r).toBase64Url()};return n.kid=yield ur({jwk:n}),n})}static computePublicKey(e){return Mu(this,arguments,void 0,function*({key:r}){let n=yield rw.privateKeyToBytes({privateKey:r}),s=tw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Je.uint8Array(s).toBase64Url()};return a.kid=yield ur({jwk:a}),a})}static generateKey(){return Mu(this,void 0,void 0,function*(){let e=tw.utils.randomPrivateKey(),r=yield rw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ur({jwk:r}),r})}static getPublicKey(e){return Mu(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=Aoe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield ur({jwk:a})),a})}static privateKeyToBytes(e){return Mu(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Je.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Mu(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 Je.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Mu(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 rw.privateKeyToBytes({privateKey:r}),a=yield rw.publicKeyToBytes({publicKey:n});return tw.getSharedSecret(s,a)})}},Zg=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())})},Roe=class extends nP{bytesToPrivateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Ch.bytesToPrivateKey({privateKeyBytes:r});default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.computePublicKey({key:e});default:throw new Wo(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ch.generateKey();default:throw new Wo(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.getPublicKey({key:e});default:throw new Wo(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Zg(this,arguments,void 0,function*({privateKey:e}){return Ch.privateKeyToBytes({privateKey:e})})}},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())})},pI={Ed25519:{implementation:_oe,names:["Ed25519"]},secp256k1:{implementation:qN,names:["ES256K","secp256k1"]},secp256r1:{implementation:qN,names:["ES256","secp256r1"]},"SHA-256":{implementation:Ioe,names:["SHA-256"]},X25519:{implementation:Roe,names:["X25519"]}},Aa=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new kse}digest(t){return wd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return wd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return wd(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=`${zN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return wd(this,arguments,void 0,function*({key:e}){let r=yield ur({jwk:e});return`${zN}${r}`})}getPublicKey(t){return wd(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 wd(this,arguments,void 0,function*({key:e}){var r;if(!Oie(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 ur({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return wd(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 wd(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=pI[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 pI){let s=pI[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 wd(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})}},Doe=class UL{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 kie(e)}static randomUuid(){return E1.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),n=Math.ceil(Math.log2(r)/8),s=Math.pow(2,n*8),a=s-s%r,o;do{o=0;let i=UL.randomBytes(n);for(let c of i)o=o*256+c}while(o>=a);return(o%r).toString().padStart(e,"0")}},Coe=["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 joe(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":$oe(t)||"Object"}function $oe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(Coe.includes(e))return e}var ve=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}};ve.uint=new ve(0,"uint",!0);ve.negint=new ve(1,"negint",!0);ve.bytes=new ve(2,"bytes",!0);ve.string=new ve(3,"string",!0);ve.array=new ve(4,"array",!1);ve.map=new ve(5,"map",!1);ve.tag=new ve(6,"tag",!1);ve.float=new ve(7,"float",!0);ve.false=new ve(7,"false",!0);ve.true=new ve(7,"true",!0);ve.null=new ve(7,"null",!0);ve.undefined=new ve(7,"undefined",!0);ve.break=new ve(7,"break",!0);var Ve=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}`}},Tw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Ooe=new TextEncoder;function W1(t){return Tw&&globalThis.Buffer.isBuffer(t)}function LL(t){return t instanceof Uint8Array?W1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var Moe=24,Boe=200,Noe=Tw?t=>t.length>=Moe?globalThis.Buffer.from(t):VN(t):t=>t.length>=Boe?Ooe.encode(t):VN(t),vd=t=>Uint8Array.from(t),Uoe=Tw?(t,e,r)=>W1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Loe=Tw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),LL(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=Tw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function KL(t,e){if(W1(t)&&W1(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 VN(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 zoe=256,zL=class{constructor(t=zoe){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=Uoe(r,0,this.cursor)}else e=Loe(this.chunks,this.cursor);return t&&this.reset(),e}},qoe=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}},un="CBOR decode error:",qL="CBOR encode error:",Iw=[];Iw[23]=1;Iw[24]=2;Iw[25]=3;Iw[26]=5;Iw[27]=9;function Jh(t,e,r){if(t.length-e<r)throw new Error(`${un} not enough data for type`)}var Os=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Cf(t,e,r){Jh(t,e,1);let n=t[e];if(r.strict===!0&&n<Os[0])throw new Error(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function jf(t,e,r){Jh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Os[1])throw new Error(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Jh(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(`${un} integer encoded in more bytes than necessary (strict decode)`);return n}function Of(t,e,r){Jh(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(`${un} 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(`${un} integers outside of the safe integer range are not supported`)}function Foe(t,e,r,n){return new Ve(ve.uint,Cf(t,e+1,n),2)}function Goe(t,e,r,n){return new Ve(ve.uint,jf(t,e+1,n),3)}function Woe(t,e,r,n){return new Ve(ve.uint,$f(t,e+1,n),5)}function Voe(t,e,r,n){return new Ve(ve.uint,Of(t,e+1,n),9)}function Mf(t,e){return Jo(t,0,e.value)}function Jo(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(`${un} encountered BigInt larger than allowable range`)}}Mf.encodedSize=function(t){return Jo.encodedSize(t.value)};Jo.encodedSize=function(t){return t<Os[0]?1:t<Os[1]?2:t<Os[2]?3:t<Os[3]?5:9};Mf.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Hoe(t,e,r,n){return new Ve(ve.negint,-1-Cf(t,e+1,n),2)}function Joe(t,e,r,n){return new Ve(ve.negint,-1-jf(t,e+1,n),3)}function Zoe(t,e,r,n){return new Ve(ve.negint,-1-$f(t,e+1,n),5)}var QI=BigInt(-1),FL=BigInt(1);function Yoe(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 Ve(ve.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${un} integers outside of the safe integer range are not supported`);return new Ve(ve.negint,QI-BigInt(s),9)}function XI(t,e){let r=e.value,n=typeof r=="bigint"?r*QI-FL:r*-1-1;Jo(t,e.type.majorEncoded,n)}XI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*QI-FL: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 Aw(t,e,r,n){Jh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Ve(ve.bytes,s,r+n)}function Qoe(t,e,r,n){return Aw(t,e,1,r)}function Xoe(t,e,r,n){return Aw(t,e,2,Cf(t,e+1,n))}function eae(t,e,r,n){return Aw(t,e,3,jf(t,e+1,n))}function tae(t,e,r,n){return Aw(t,e,5,$f(t,e+1,n))}function rae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer bytes lengths not supported`);return Aw(t,e,9,s)}function V1(t){return t.encodedBytes===void 0&&(t.encodedBytes=ve.equals(t.type,ve.string)?Noe(t.value):t.value),t.encodedBytes}function iP(t,e){let r=V1(e);Jo(t,e.type.majorEncoded,r.length),t.push(r)}iP.encodedSize=function(t){let e=V1(t);return Jo.encodedSize(e.length)+e.length};iP.compareTokens=function(t,e){return nae(V1(t),V1(e))};function nae(t,e){return t.length<e.length?-1:t.length>e.length?1:KL(t,e)}var HN=new TextDecoder,sae=32;function iae(t,e,r){if(r-e<sae){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return HN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return HN.decode(t.subarray(e,r))}function Rw(t,e,r,n,s){let a=r+n;Jh(t,e,a);let o=new Ve(ve.string,iae(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function oae(t,e,r,n){return Rw(t,e,1,r,n)}function aae(t,e,r,n){return Rw(t,e,2,Cf(t,e+1,n),n)}function cae(t,e,r,n){return Rw(t,e,3,jf(t,e+1,n),n)}function dae(t,e,r,n){return Rw(t,e,5,$f(t,e+1,n),n)}function uae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer string lengths not supported`);return Rw(t,e,9,s,n)}var lae=iP;function Zh(t,e,r,n){return new Ve(ve.array,n,r)}function fae(t,e,r,n){return Zh(t,e,1,r)}function pae(t,e,r,n){return Zh(t,e,2,Cf(t,e+1,n))}function hae(t,e,r,n){return Zh(t,e,3,jf(t,e+1,n))}function mae(t,e,r,n){return Zh(t,e,5,$f(t,e+1,n))}function yae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer array lengths not supported`);return Zh(t,e,9,s)}function gae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return Zh(t,e,1,1/0)}function eA(t,e){Jo(t,ve.array.majorEncoded,e.value)}eA.compareTokens=Mf.compareTokens;eA.encodedSize=function(t){return Jo.encodedSize(t.value)};function Yh(t,e,r,n){return new Ve(ve.map,n,r)}function wae(t,e,r,n){return Yh(t,e,1,r)}function vae(t,e,r,n){return Yh(t,e,2,Cf(t,e+1,n))}function bae(t,e,r,n){return Yh(t,e,3,jf(t,e+1,n))}function Pae(t,e,r,n){return Yh(t,e,5,$f(t,e+1,n))}function xae(t,e,r,n){let s=Of(t,e+1,n);if(typeof s=="bigint")throw new Error(`${un} 64-bit integer map lengths not supported`);return Yh(t,e,9,s)}function Sae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function tA(t,e){Jo(t,ve.map.majorEncoded,e.value)}tA.compareTokens=Mf.compareTokens;tA.encodedSize=function(t){return Jo.encodedSize(t.value)};function Eae(t,e,r,n){return new Ve(ve.tag,r,1)}function kae(t,e,r,n){return new Ve(ve.tag,Cf(t,e+1,n),2)}function _ae(t,e,r,n){return new Ve(ve.tag,jf(t,e+1,n),3)}function Tae(t,e,r,n){return new Ve(ve.tag,$f(t,e+1,n),5)}function Iae(t,e,r,n){return new Ve(ve.tag,Of(t,e+1,n),9)}function rA(t,e){Jo(t,ve.tag.majorEncoded,e.value)}rA.compareTokens=Mf.compareTokens;rA.encodedSize=function(t){return Jo.encodedSize(t.value)};var GL=20,WL=21,VL=22,HL=23;function Aae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${un} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Ve(ve.null,null,1):new Ve(ve.undefined,void 0,1)}function Rae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${un} indefinite length items not allowed`);return new Ve(ve.break,void 0,1)}function nA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${un} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${un} Infinity values are not supported`)}return new Ve(ve.float,t,e)}function Dae(t,e,r,n){return nA(iA(t,e+1),3,n)}function Cae(t,e,r,n){return nA(oA(t,e+1),5,n)}function jae(t,e,r,n){return nA(QL(t,e+1),9,n)}function sA(t,e,r){let n=e.value;if(n===!1)t.push([ve.float.majorEncoded|GL]);else if(n===!0)t.push([ve.float.majorEncoded|WL]);else if(n===null)t.push([ve.float.majorEncoded|VL]);else if(n===void 0)t.push([ve.float.majorEncoded|HL]);else{let s,a=!1;(!r||r.float64!==!0)&&(ZL(n),s=iA(Ta,1),n===s||Number.isNaN(n)?(Ta[0]=249,t.push(Ta.slice(0,3)),a=!0):(YL(n),s=oA(Ta,1),n===s&&(Ta[0]=250,t.push(Ta.slice(0,5)),a=!0))),a||($ae(n),s=QL(Ta,1),Ta[0]=251,t.push(Ta.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){ZL(r);let n=iA(Ta,1);if(r===n||Number.isNaN(r))return 3;if(YL(r),n=oA(Ta,1),r===n)return 5}return 9};var JL=new ArrayBuffer(9),Ko=new DataView(JL,1),Ta=new Uint8Array(JL,0);function ZL(t){if(t===1/0)Ko.setUint16(0,31744,!1);else if(t===-1/0)Ko.setUint16(0,64512,!1);else if(Number.isNaN(t))Ko.setUint16(0,32256,!1);else{Ko.setFloat32(0,t);let e=Ko.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Ko.setUint16(0,31744,!1);else if(r===0)Ko.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?Ko.setUint16(0,0):s<-14?Ko.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Ko.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function iA(t,e){if(t.length-e<2)throw new Error(`${un} 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 YL(t){Ko.setFloat32(0,t,!1)}function oA(t,e){if(t.length-e<4)throw new Error(`${un} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function $ae(t){Ko.setFloat64(0,t,!1)}function QL(t,e){if(t.length-e<8)throw new Error(`${un} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}sA.compareTokens=Mf.compareTokens;function er(t,e,r){throw new Error(`${un} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function oP(t){return()=>{throw new Error(`${un} ${t}`)}}var De=[];for(let t=0;t<=23;t++)De[t]=er;De[24]=Foe;De[25]=Goe;De[26]=Woe;De[27]=Voe;De[28]=er;De[29]=er;De[30]=er;De[31]=er;for(let t=32;t<=55;t++)De[t]=er;De[56]=Hoe;De[57]=Joe;De[58]=Zoe;De[59]=Yoe;De[60]=er;De[61]=er;De[62]=er;De[63]=er;for(let t=64;t<=87;t++)De[t]=Qoe;De[88]=Xoe;De[89]=eae;De[90]=tae;De[91]=rae;De[92]=er;De[93]=er;De[94]=er;De[95]=oP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)De[t]=oae;De[120]=aae;De[121]=cae;De[122]=dae;De[123]=uae;De[124]=er;De[125]=er;De[126]=er;De[127]=oP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)De[t]=fae;De[152]=pae;De[153]=hae;De[154]=mae;De[155]=yae;De[156]=er;De[157]=er;De[158]=er;De[159]=gae;for(let t=160;t<=183;t++)De[t]=wae;De[184]=vae;De[185]=bae;De[186]=Pae;De[187]=xae;De[188]=er;De[189]=er;De[190]=er;De[191]=Sae;for(let t=192;t<=215;t++)De[t]=Eae;De[216]=kae;De[217]=_ae;De[218]=Tae;De[219]=Iae;De[220]=er;De[221]=er;De[222]=er;De[223]=er;for(let t=224;t<=243;t++)De[t]=oP("simple values are not supported");De[244]=er;De[245]=er;De[246]=er;De[247]=Aae;De[248]=oP("simple values are not supported");De[249]=Dae;De[250]=Cae;De[251]=jae;De[252]=er;De[253]=er;De[254]=er;De[255]=Rae;var _d=[];for(let t=0;t<24;t++)_d[t]=new Ve(ve.uint,t,1);for(let t=-1;t>=-24;t--)_d[31-t]=new Ve(ve.negint,t,1);_d[64]=new Ve(ve.bytes,new Uint8Array(0),1);_d[96]=new Ve(ve.string,"",1);_d[128]=new Ve(ve.array,0,1);_d[160]=new Ve(ve.map,0,1);_d[244]=new Ve(ve.false,!1,1);_d[245]=new Ve(ve.true,!0,1);_d[246]=new Ve(ve.null,null,1);function Oae(t){switch(t.type){case ve.false:return vd([244]);case ve.true:return vd([245]);case ve.null:return vd([246]);case ve.bytes:return t.value.length?void 0:vd([64]);case ve.string:return t.value===""?vd([96]):void 0;case ve.array:return t.value===0?vd([128]):void 0;case ve.map:return t.value===0?vd([160]):void 0;case ve.uint:return t.value<24?vd([Number(t.value)]):void 0;case ve.negint:if(t.value>=-24)return vd([31-Number(t.value)])}}var Mae=Object.freeze({float64:!0,mapSorter:Kae,quickEncodeToken:Oae});function Bae(){let t=[];return t[ve.uint.major]=Mf,t[ve.negint.major]=XI,t[ve.bytes.major]=iP,t[ve.string.major]=lae,t[ve.array.major]=eA,t[ve.map.major]=tA,t[ve.tag.major]=rA,t[ve.float.major]=sA,t}var Nae=Bae(),Uae=new zL,JN=class XL{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(`${qL} object contains circular references`);return new XL(r,e)}},Bu={null:new Ve(ve.null,null),undefined:new Ve(ve.undefined,void 0),true:new Ve(ve.true,!0),false:new Ve(ve.false,!1),emptyArray:new Ve(ve.array,0),emptyMap:new Ve(ve.map,0)},Wu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Ve(ve.float,t):t>=0?new Ve(ve.uint,t):new Ve(ve.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Ve(ve.uint,t):new Ve(ve.negint,t)},Uint8Array(t,e,r,n){return new Ve(ve.bytes,t)},string(t,e,r,n){return new Ve(ve.string,t)},boolean(t,e,r,n){return t?Bu.true:Bu.false},null(t,e,r,n){return Bu.null},undefined(t,e,r,n){return Bu.undefined},ArrayBuffer(t,e,r,n){return new Ve(ve.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Ve(ve.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Bu.emptyArray,new Ve(ve.break)]:Bu.emptyArray;n=JN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=k1(o,r,n);return r.addBreakTokens?[new Ve(ve.array,t.length),s,new Ve(ve.break)]:[new Ve(ve.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=JN.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++]=[k1(d,r,n),k1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(Lae(i,r),r.addBreakTokens?[new Ve(ve.map,i.length),i,new Ve(ve.break)]:[new Ve(ve.map,i.length),i]):r.addBreakTokens===!0?[Bu.emptyMap,new Ve(ve.break)]:Bu.emptyMap}};Wu.Map=Wu.Object;Wu.Buffer=Wu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Wu[`${t}Array`]=Wu.DataView;function k1(t,e={},r){let n=joe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Wu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Wu[n];if(!a)throw new Error(`${qL} unsupported type: ${n}`);return a(t,n,e,r)}function Lae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Kae(t,e){if(t[0]instanceof Ve&&e[0]instanceof Ve){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=ZN(r.value)),n._keyBytes||(n._keyBytes=ZN(n.value)),KL(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function ZN(t){return zae(t,Nae,Mae)}function eK(t,e,r,n){if(Array.isArray(e))for(let s of e)eK(t,s,r,n);else r[e.type.major](t,e,n)}var G$e=ve.uint.majorEncoded,W$e=ve.negint.majorEncoded,V$e=ve.bytes.majorEncoded,H$e=ve.string.majorEncoded,J$e=ve.array.majorEncoded,Z$e=ve.float.majorEncoded|GL,Y$e=ve.float.majorEncoded|WL,Q$e=ve.float.majorEncoded|VL,X$e=ve.float.majorEncoded|HL,e3e=BigInt(-1),t3e=BigInt(1);function zae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new qoe(n):Uae,o=k1(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 zL(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():LL(a.chunks[0])}}return a.reset(),eK(a,o,e,r),a.toBytes(!0)}var r3e=Symbol.for("DONE"),n3e=Symbol.for("BREAK"),YN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(YN||(YN={}));var Xs;(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"})(Xs||(Xs={}));var Go;(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"})(Go||(Go={}));var QN;(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"})(QN||(QN={}));var XN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(XN||(XN={}));var s3e={"P-256":Xs.P256,"P-384":Xs.P384,"P-521":Xs.P521,X25519:Xs.X25519,Ed25519:Xs.Ed25519,Ed448:Xs.Ed448,secp256k1:Xs.Secp256k1},i3e={[Xs.P256]:"P-256",[Xs.P384]:"P-384",[Xs.P521]:"P-521",[Xs.X25519]:"X25519",[Xs.Ed25519]:"Ed25519",[Xs.Ed448]:"Ed448",[Xs.Secp256k1]:"secp256k1"},o3e={EdDSA:Go.EdDSA,ES256:Go.ES256,ES384:Go.ES384,ES512:Go.ES512,ES256K:Go.ES256K},a3e={[Go.EdDSA]:"EdDSA",[Go.ES256]:"ES256",[Go.ES384]:"ES384",[Go.ES512]:"ES512",[Go.ES256K]:"ES256K"},eU;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(eU||(eU={}));var tU;(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"})(tU||(tU={}));var rU;(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"})(rU||(rU={}));var nU;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(nU||(nU={}));var qae={};NI(qae,{extractDidFragment:()=>Si,getServices:()=>Fae,getVerificationMethodByKey:()=>Gae,getVerificationMethodTypes:()=>tK,getVerificationMethods:()=>aP,getVerificationRelationshipsById:()=>rK,isDidService:()=>nK,isDidVerificationMethod:()=>H1,isDwnDidService:()=>Wae,isPortableDid:()=>Vae,keyBytesToMultibaseId:()=>sK,multibaseIdToKeyBytes:()=>iK});function Si(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Fae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Gae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=aP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await ur({jwk:e})===await ur({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function aP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(H1)??[]),Object.keys(rP).forEach(r=>{e.push(...t[r]?.filter(H1)??[])}),e}function tK({didDocument:t}){let e=aP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function rK({didDocument:t,methodId:e}){let r=[];return Object.keys(rP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=Si(e);s.some(o=>{let i=Si(o)===a,c=H1(o)&&Si(o.id)===a;return i||c})&&r.push(n)}}),r}function nK(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Wae(t){return!(!nK(t)||t.type!=="DecentralizedWebNode")}function H1(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 Vae(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 sK({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Ho.addPrefix({code:e,data:t,name:r}),s=Je.uint8Array(n).toBase58Btc();return Je.base58Btc(s).toMultibase()}function iK({multibaseKeyId:t}){try{let e=Je.multibase(t).toBase58Btc(),r=Je.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Ho.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new We("invalidDid",`Invalid multibase identifier: ${t}`)}}var Ec=class oK{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=>Si(o.id)===(Si(e?.methodId)??Si(this.document.assertionMethod?.[0])));if(!r?.publicKeyJwk)throw new We("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:Doe.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 Aa}){let n=aP({didDocument:e.document});if(n.length===0)throw new We("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 oK({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Dw=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()")}},aK=(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))(aK||{}),aA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(aA||{}),cK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(cK||{}),sU="0123456789abcdef",dK=[],iU=[];for(let t=0;t<256;t++)dK[t]=sU[t>>4&15]+sU[t&15],t<16&&(t<10?iU[48+t]=t:iU[87+t]=t);var Hae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=dK[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},oU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Yg=0;Yg<oU.length;Yg++)Zae[oU.charCodeAt(Yg)]=Yg;var Yg,Yae=new TextDecoder,uK=(t,e)=>e?new TextDecoder(e).decode(t):Yae.decode(t),Qae=new TextEncoder,kd=t=>Qae.encode(t),aU=typeof window<"u"?window:self,cU=aU.crypto||aU.msCrypto||{},c3e=cU.subtle||cU.webkitSubtle;function Cw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function lK(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 or(t,e,r){let n=[],s=null;return or._encode(n,t),s=Jae(n),or.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}or.bytes=-1;or._floatConversionDetected=!1;or._encode=function(t,e){if(e!=null)switch(lK(e)){case"object":or.dict(t,e);break;case"map":or.dictMap(t,e);break;case"array":or.list(t,e);break;case"set":or.listSet(t,e);break;case"string":or.string(t,e);break;case"number":or.number(t,e);break;case"boolean":or.number(t,e);break;case"arraybufferview":or.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":or.buffer(t,new Uint8Array(e));break}};var cP=new Uint8Array([101]),fK=new Uint8Array([100]),pK=new Uint8Array([108]);or.buffer=function(t,e){t.push(kd(e.length+":"),e)};or.string=function(t,e){t.push(kd(kd(e).byteLength+":"+e))};or.number=function(t,e){if(Number.isInteger(e))return t.push(kd("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(kd("i"+a+"e")),a!==e&&!or._floatConversionDetected&&(or._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())};or.dict=function(t,e){t.push(fK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(or.string(t,n),or._encode(t,e[n]));t.push(cP)};or.dictMap=function(t,e){t.push(fK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?or._encode(t,n):or.string(t,String(n)),or._encode(t,e.get(n)));t.push(cP)};or.list=function(t,e){let r=0,n=e.length;for(t.push(pK);r<n;r++)e[r]!=null&&or._encode(t,e[r]);t.push(cP)};or.listSet=function(t,e){t.push(pK);for(let r of e)r!=null&&or._encode(t,r);t.push(cP)};var Xae=or,ece=105,tce=58,rce=100,nce=108,cA=101;function hK(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 at(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),at.position=0,at.encoding=n||null,at.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):kd(t),at.bytes=at.data.length,at.next())}at.bytes=0;at.position=0;at.data=null;at.encoding=null;at.next=function(){switch(at.data[at.position]){case rce:return at.dictionary();case nce:return at.list();case ece:return at.integer();default:return at.buffer()}};at.find=function(t){let e=at.position,r=at.data.length,n=at.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)+"]")};at.dictionary=function(){at.position++;let t={};for(;at.data[at.position]!==cA;){let e=at.buffer(),r=uK(e);r.includes("\uFFFD")&&(r=Hae(e)),t[r]=at.next()}return at.position++,t};at.list=function(){at.position++;let t=[];for(;at.data[at.position]!==cA;)t.push(at.next());return at.position++,t};at.integer=function(){let t=at.find(cA),e=hK(at.data,at.position+1,t);return at.position+=t+1-at.position,e};at.buffer=function(){let t=at.find(tce),e=hK(at.data,at.position,t),r=++t+e;return at.position=r,at.encoding?uK(at.data.slice(t,r)):at.data.slice(t,r)};var sce=at;function ice(t){let e=2;for(let r of t)e+=dP(r);return e}function oce(t){let e=2;for(let[r,n]of t){let s=kd(r).byteLength;e+=Cw(s)+1+s,e+=dP(n)}return e}function ace(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=kd(r[n]).byteLength;e+=Cw(s)+1+s,e+=dP(t[r[n]])}return e}function cce(t){let e=kd(t).byteLength;return Cw(e)+1+e}function dce(t){let e=t.byteLength-t.byteOffset;return Cw(e)+1+e}function dP(t){if(t==null)return 0;let e=lK(t);switch(e){case"arraybufferview":return dce(t);case"string":return cce(t);case"array":case"set":return ice(t);case"number":return 1+Cw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return ace(t);case"map":return oce(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var mK=dP,uce=mK,yK={encode:Xae,decode:sce,byteLength:mK,encodingLength:uce},lce=/^(\d{1,3}\.){3,3}\d{1,3}$/,fce=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Pc={name:"v4",size:4,isFormat:t=>lce.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]}`}},Gu={name:"v6",size:16,isFormat:t=>t.length>0&&fce.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 gK(t){if(Pc.isFormat(t))return Pc.size;if(Gu.isFormat(t))return Gu.size;throw Error(`Invalid ip address: ${t}`)}function pce(t){return gK(t)===Pc.size?1:2}function hce(t,e,r){r=~~r;let n=gK(t);return typeof e=="function"&&(e=e(r+n)),n===Pc.size?Pc.encode(t,e,r):Gu.encode(t,e,r)}function mce(t,e,r){if(e=~~e,r=r||t.length-e,r===Pc.size)return Pc.decode(t,e,r);if(r===Gu.size)return Gu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Pc.size} for v4 or ${Gu.size} for v6.`)}function uP(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 xw(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 yce(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 gce(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 wK(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 vK(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 wce(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 dU(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 bK(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 Sw(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(bK(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 Sw.bytes=s-r,e}Sw.bytes=0;function jw(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 jw.bytes=r-e,n}jw.bytes=0;var Af=t=>t instanceof Uint8Array;function Vu(t){return typeof t=="string"?bK(t):t.byteLength}function dA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Sw(t)}function uA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Sw(e,t,r),Sw.bytes}var nw={},PK=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}`;PK[o]=i,nw[i]=o,nw[`${r}${s}`]=o,nw[`${e}${a}`]=o,nw[`${r}${a}`]=o}}function vce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=PK[a]}return n}function uU(t){return t.length>>>1}function bce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=nw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var Pce=Math.pow(2,24),xce=Math.pow(2,16),Sce=Math.pow(2,8),xd=(t,e)=>t[e]*Pce+t[e+1]*xce+t[e+2]*Sce+t[e+3],kt=(t,e)=>t[e]<<8|t[e+1],Sd=(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),Ze=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mo(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:Ece(t,e,r,n,s)}function Ece(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 kce=0,lU=32768,_I=32768,_ce=~_I,xK=32768,Tce=~xK;function $r({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Le=$r({encode(t,e,r){e||(e=new Uint8Array(Le.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,Le.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=kt(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(jw(t,e,e+i)),e+=i,a+=o?0:i}}return Le.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Vu(t.replace(/^\.|\.$/gm,""))+2}}),Yn=$r({encode(t,e,r){e||(e=new Uint8Array(Yn.encodingLength(t))),r||(r=0);let n=uA(e,t,r+1);return e[r]=n,Yn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=jw(t,e+1,e+1+r);return Yn.decode.bytes=r+1,n},encodingLength(t){return Vu(t)+1}}),jh=$r({bytes:12,encode(t,e,r){e||(e=new Uint8Array(jh.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?lU:kce;return Ze(e,t.id||0,r),Ze(e,n|s,r+2),Ze(e,t.questions.length,r+4),Ze(e,t.answers.length,r+6),Ze(e,t.authorities.length,r+8),Ze(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=kt(t,e+2);return{id:kt(t,e),type:r&lU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:gce(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:yce(r&15),questions:new Array(kt(t,e+4)),answers:new Array(kt(t,e+6)),authorities:new Array(kt(t,e+8)),additionals:new Array(kt(t,e+10))}},encodingLength(){return 12}}),_1=$r({encode(t,e,r){e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0);let n=t.length;return Ze(e,n,r),mo(t,e,r+2,0,n),_1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n=t.slice(e+2,e+2+r);return _1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),T1=$r({encode(t,e,r){return e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),Ze(e,Le.encode.bytes,r),T1.encode.bytes=Le.encode.bytes+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n=Le.decode(t,e+2);return T1.decode.bytes=r+2,n},encodingLength(t){return Le.encodingLength(t)+2}}),I1=$r({encode(t,e,r){e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mname,e,r),r+=Le.encode.bytes,Le.encode(t.rname,e,r),r+=Le.encode.bytes,Sd(e,t.serial||0,r),r+=4,Sd(e,t.refresh||0,r),r+=4,Sd(e,t.retry||0,r),r+=4,Sd(e,t.expire||0,r),r+=4,Sd(e,t.minimum||0,r),r+=4,Ze(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Le.decode(t,e),e+=Le.decode.bytes,n.rname=Le.decode(t,e),e+=Le.decode.bytes,n.serial=xd(t,e),e+=4,n.refresh=xd(t,e),e+=4,n.retry=xd(t,e),e+=4,n.expire=xd(t,e),e+=4,n.minimum=xd(t,e),e+=4,I1.decode.bytes=e-r,n},encodingLength(t){return 22+Le.encodingLength(t.mname)+Le.encodingLength(t.rname)}}),A1=$r({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])),!Af(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,mo(s,e,r,0,s.length),r+=s.length}),Ze(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=kt(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 A1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Vu(r)+1:e+=r.length+1}),e}}),R1=$r({encode(t,e,r){e||(e=new Uint8Array(R1.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 mo(t,e,r,0,s),r+=s,Ze(e,r-n-2,n),R1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=kt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,R1.decode.bytes=e-r,s},encodingLength(t){return t?(Af(t)?t.length:Vu(t))+2:2}}),D1=$r({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Yn.encode(t.cpu,e,r),r+=Yn.encode.bytes,Yn.encode(t.os,e,r),r+=Yn.encode.bytes,Ze(e,r-n-2,n),D1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Yn.decode(t,e),e+=Yn.decode.bytes,n.os=Yn.decode(t,e),e+=Yn.decode.bytes,D1.decode.bytes=e-r,n},encodingLength(t){return Yn.encodingLength(t.cpu)+Yn.encodingLength(t.os)+2}}),Lh=$r({encode(t,e,r){return e||(e=new Uint8Array(Lh.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),Ze(e,Le.encode.bytes,r),Lh.encode.bytes=Le.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Le.decode(t,e+2);return Lh.decode.bytes=Le.decode.bytes+2,r},encodingLength(t){return Le.encodingLength(t)+2}}),C1=$r({encode(t,e,r){e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0),Ze(e,t.priority||0,r+2),Ze(e,t.weight||0,r+4),Ze(e,t.port||0,r+6),Le.encode(t.target,e,r+8);let n=Le.encode.bytes+6;return Ze(e,n,r),C1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=kt(t,e),n={};return n.priority=kt(t,e+2),n.weight=kt(t,e+4),n.port=kt(t,e+6),n.target=Le.decode(t,e+8),C1.decode.bytes=r+2,n},encodingLength(t){return 8+Le.encodingLength(t.target)}}),zu=$r({encode(t,e,r){let n=zu.encodingLength(t);return e||(e=new Uint8Array(zu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=zu.ISSUER_CRITICAL),Ze(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Yn.encode(t.tag,e,r),r+=Yn.encode.bytes,uA(e,t.value,r),r+=Vu(t.value),zu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=kt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Yn.decode(t,e),e+=Yn.decode.bytes,s.value=jw(t,e,n+r),s.issuerCritical=!!(s.flags&zu.ISSUER_CRITICAL),zu.decode.bytes=r+2,s},encodingLength(t){return Yn.encodingLength(t.tag)+Yn.encodingLength(t.value)+2}});zu.ISSUER_CRITICAL=128;var j1=$r({encode(t,e,r){e||(e=new Uint8Array(j1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze(e,t.preference||0,r),r+=2,Le.encode(t.exchange,e,r),r+=Le.encode.bytes,Ze(e,r-n-2,n),j1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=kt(t,e),e+=2,n.exchange=Le.decode(t,e),e+=Le.decode.bytes,j1.decode.bytes=e-r,n},encodingLength(t){return 4+Le.encodingLength(t.exchange)}}),SK=$r({encode(t,e,r){return e||(e=new Uint8Array(SK.encodingLength(t))),r||(r=0),Ze(e,4,r),r+=2,Pc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Pc.decode(t,e)},bytes:6}),$1=$r({encode(t,e,r){return e||(e=new Uint8Array($1.encodingLength(t))),r||(r=0),Ze(e,16,r),r+=2,Gu.encode(t,e,r),$1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Gu.decode(t,e);return $1.decode.bytes=18,r},bytes:18}),fU=t=>new Uint8Array(t),bd=$r({encode(t,e,r){e||(e=new Uint8Array(bd.encodingLength(t))),r||(r=0);let n=r,s=dU(t.code);if(Ze(e,s,r),r+=2,t.data)Ze(e,t.data.length,r),r+=2,mo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||pce(t.ip,fU),i=hce(t.ip,fU),c=Math.ceil(a/8);Ze(e,c+4,r),r+=2,Ze(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,mo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Ze(e,2,r),r+=2,Ze(e,t.timeout,r),r+=2):(Ze(e,0,r),r+=2);break;case 12:{let a=t.length||0;Ze(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Ze(e,a,r),r+=2;for(let o of t.tags)Ze(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return bd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=kt(t,e),r.type=wce(r.code),e+=2;let n=kt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=kt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);mo(t,s,0,e,e+n-4),r.ip=mce(s)}break;case 11:n>0&&(r.timeout=kt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(kt(t,e)),e+=2}return bd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(dU(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}`)}}),qu=$r({encode(t,e,r){e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0);let n=r,s=Nh(t,bd);return Ze(e,s,r),r=dw(t,bd,e,r+2),qu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=kt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=bd.decode(t,e),e+=bd.decode.bytes,s-=bd.decode.bytes;return qu.decode.bytes=e-r,n},encodingLength(t){return 2+Nh(t||[],bd)}}),bc=$r({encode(t,e,r){e||(e=new Uint8Array(bc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Af(s))throw new Error("Key must be a Buffer");return r+=2,Ze(e,t.flags,r),r+=2,e[r]=bc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mo(s,e,r,0,s.length),r+=s.length,bc.encode.bytes=r-n,Ze(e,bc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);if(e+=2,n.flags=kt(t,e),e+=2,t[e]!==bc.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,bc.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.key)}});bc.PROTOCOL_DNSSEC=3;bc.ZONE_KEY=128;bc.SECURE_ENTRYPOINT=32768;var sw=$r({encode(t,e,r){e||(e=new Uint8Array(sw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Af(s))throw new Error("Signature must be a Buffer");return r+=2,Ze(e,xw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Sd(e,t.originalTTL,r),r+=4,Sd(e,t.expiration,r),r+=4,Sd(e,t.inception,r),r+=4,Ze(e,t.keyTag,r),r+=2,Le.encode(t.signersName,e,r),r+=Le.encode.bytes,mo(s,e,r,0,s.length),r+=s.length,sw.encode.bytes=r-n,Ze(e,sw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.typeCovered=uP(kt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=xd(t,e),e+=4,n.expiration=xd(t,e),e+=4,n.inception=xd(t,e),e+=4,n.keyTag=kt(t,e),e+=2,n.signersName=Le.decode(t,e),e+=Le.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,sw.decode.bytes=e-r,n},encodingLength(t){return 20+Le.encodingLength(t.signersName)+Vu(t.signature)}}),iw=$r({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mbox||".",e,r),r+=Le.encode.bytes,Le.encode(t.txt||".",e,r),r+=Le.encode.bytes,iw.encode.bytes=r-n,Ze(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Le.decode(t,e)||".",e+=Le.decode.bytes,n.txt=Le.decode(t,e)||".",e+=Le.decode.bytes,iw.decode.bytes=e-r,n},encodingLength(t){return 2+Le.encodingLength(t.mbox||".")+Le.encodingLength(t.txt||".")}}),ho=$r({encode(t,e,r){e||(e=new Uint8Array(ho.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=xw(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,mo(o,e,r,0,o.length),r+=o.length}return ho.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=uP(a<<8|i<<3|u);s.push(d)}}e+=o}return ho.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=xw(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}}),ow=$r({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.nextDomain,e,r),r+=Le.encode.bytes,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,ow.encode.bytes=r-n,Ze(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.nextDomain=Le.decode(t,e),e+=Le.decode.bytes,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Le.encodingLength(t.nextDomain)+ho.encodingLength(t.rrtypes)}}),aw=$r({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Af(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Af(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Ze(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,mo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,mo(a,e,r,0,a.length),r+=a.length,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,aw.encode.bytes=r-n,Ze(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=kt(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=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+ho.encodingLength(t.rrtypes)}}),cw=$r({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Af(s))throw new Error("Digest must be a Buffer");return r+=2,Ze(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mo(s,e,r,0,s.length),r+=s.length,cw.encode.bytes=r-n,Ze(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=kt(t,e);return e+=2,n.keyTag=kt(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,cw.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.digest)}}),Bh=$r({encode(t,e,r){e||(e=new Uint8Array(Bh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=uU(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 bce(e,t.fingerprint,r,r+=s),Bh.encode.bytes=r-n,Ze(e,Bh.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=vce(t,e,e+s),e+=s,Bh.decode.bytes=e-r,n},encodingLength(t){return 4+uU(t.fingerprint)}});function TI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Bh.getFingerprintLengthForHashType=TI;function hI(t){switch(t.toUpperCase()){case"A":return SK;case"PTR":return Lh;case"CNAME":return Lh;case"DNAME":return Lh;case"TXT":return A1;case"NULL":return R1;case"AAAA":return $1;case"SRV":return C1;case"HINFO":return D1;case"CAA":return zu;case"NS":return T1;case"SOA":return I1;case"MX":return j1;case"OPT":return qu;case"DNSKEY":return bc;case"RRSIG":return sw;case"RP":return iw;case"NSEC":return ow;case"NSEC3":return aw;case"SSHFP":return Bh;case"DS":return cw}return _1}var zo=$r({encode(t,e,r){e||(e=new Uint8Array(zo.encodingLength(t))),r||(r=0);let n=r;if(Le.encode(t.name,e,r),r+=Le.encode.bytes,Ze(e,xw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Ze(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Ze(e,t.flags||0,r+6),r+=8,qu.encode(t.options||[],e,r),r+=qu.encode.bytes}else{let s=vK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Ze(e,s,r+2),Sd(e,t.ttl||0,r+4),r+=8;let a=hI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return zo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Le.decode(t,e),e+=Le.decode.bytes,r.type=uP(kt(t,e)),r.type==="OPT")r.udpPayloadSize=kt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=kt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=qu.decode(t,e+8),e+=8+qu.decode.bytes;else{let s=kt(t,e+2);r.ttl=xd(t,e+4),r.class=wK(s&_ce),r.flush=!!(s&_I);let a=hI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return zo.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Le.encodingLength(t.name)+8+hI(t.type).encodingLength(e)}}),Kh=$r({encode(t,e,r){e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0);let n=r;return Le.encode(t.name,e,r),r+=Le.encode.bytes,Ze(e,xw(t.type),r),r+=2,Ze(e,vK(t.class===void 0?"IN":t.class),r),r+=2,Kh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Le.decode(t,e),e+=Le.decode.bytes,n.type=uP(kt(t,e)),e+=2,n.class=wK(kt(t,e)),e+=2,n.class&xK&&(n.class&=Tce),Kh.decode.bytes=e-r,n},encodingLength(t){return Le.encodingLength(t.name)+4}}),Ice=1024,Ms={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(Ace(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),jh.encode(t,e,r),r+=jh.encode.bytes,r=dw(t.questions,Kh,e,r),r=dw(t.answers,zo,e,r),r=dw(t.authorities,zo,e,r),r=dw(t.additionals,zo,e,r),Ms.encode.bytes=r-s,n&&Q1.bytes!==e.length?e.slice(0,Q1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=jh.decode(t,e);return e+=jh.decode.bytes,e=g1(n.questions,Kh,t,e),e=g1(n.answers,zo,t,e),e=g1(n.authorities,zo,t,e),e=g1(n.additionals,zo,t,e),Ms.decode.bytes=e-r,n},encodingLength:function(t){return jh.encodingLength(t)+Nh(t.questions||[],Kh)+Nh(t.answers||[],zo)+Nh(t.authorities||[],zo)+Nh(t.additionals||[],zo)}};Ms.encode.bytes=0;Ms.decode.bytes=0;function J1(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 Z1={encode:function(t,e,r){return e=Ms.encode(J1(t,"query"),e,r),Z1.encode.bytes=Ms.encode.bytes,e},decode:function(t,e){let r=Ms.decode(t,e);return Z1.decode.bytes=Ms.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Ms.encodingLength(J1(t,"query"))}};Z1.encode.bytes=0;Z1.decode.bytes=0;var Y1={encode:function(t,e,r){return e=Ms.encode(J1(t,"response"),e,r),Y1.encode.bytes=Ms.encode.bytes,e},decode:function(t,e){let r=Ms.decode(t,e);return Y1.decode.bytes=Ms.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Ms.encodingLength(J1(t,"response"))}};Y1.encode.bytes=0;Y1.decode.bytes=0;var Q1=Ms.encode,II=Ms.decode,Ace=Ms.encodingLength;function EK(t){let e=Q1(t),r=new Uint8Array(2+e.byteLength);return Ze(r,e.byteLength),mo(e,r,2,0,e.length),EK.bytes=r.byteLength,r}EK.bytes=0;function kK(t){let e=kt(t,0);if(t.byteLength<e+2)return null;let r=II(t.slice(2));return kK.bytes=II.bytes,r}kK.bytes=0;function Nh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function dw(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 _K(t,e){let r=Je.uint8Array(t).toBase32Z();return new URL(r,e).href}async function TK(t,e,r){if(r)return fetch(t,e);try{return await oL(t,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof S1?new We("invalidGatewayUri",n.message):n}}async function Rce({gatewayUri:t,publicKeyBytes:e,allowPrivateGatewayUri:r=!1}){let n=Je.uint8Array(e).toBase32Z(),s=_K(e,t),a;try{if(a=await TK(s,{method:"GET",signal:AbortSignal.timeout(3e4)},r),!a.ok)throw new We("notFound",`Pkarr record not found for: ${n}`)}catch(i){throw i instanceof We?i:new We("internalError",`Failed to fetch Pkarr record: ${i.message}`)}let o=await a.arrayBuffer();if(!o)throw new We("notFound",`Pkarr record not found for: ${n}`);if(o.byteLength<72)throw new We("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${o.byteLength}`);if(o.byteLength>1072)throw new We("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${o.byteLength}`);return{k:e,seq:Number(new DataView(o).getBigUint64(64)),sig:new Uint8Array(o,0,64),v:new Uint8Array(o,72)}}async function Dce({gatewayUri:t,bep44Message:e,allowPrivateGatewayUri:r=!1}){let n=Je.uint8Array(e.k).toBase32Z(),s=_K(e.k,t),a=new Uint8Array(e.v.length+72);a.set(e.sig,0),new DataView(a.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),a.set(e.v,e.sig.length+8);let o;try{o=await TK(s,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:a,signal:AbortSignal.timeout(3e4)},r)}catch(i){throw i instanceof We?i:new We("internalError",`Failed to put Pkarr record for identifier ${n}: ${i.message}`)}return o.ok}async function Cce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Q1(t),a=yK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new We("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 jce({bep44Message:t}){let e=await $s.bytesToPublicKey({publicKeyBytes:t.k}),r=yK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await $s.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new We("invalidSignature","Invalid signature for DHT BEP44 message");return II(t.v)}var IK="dht";async function AK({didUri:t}){let e=lA({didUri:t});return await $s.bytesToPublicKey({publicKeyBytes:e})}function lA({didUri:t}){let e=ls.parse(t);if(!e)throw new We("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==IK)throw new We("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Je.base32Z(e.id).toUint8Array()}catch{throw new We("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new We("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function $ce({identityKey:t}){let e=await $s.publicKeyToBytes({publicKey:t}),r=Je.uint8Array(e).toBase32Z();return`did:${IK}:${r}`}function fA(t){let e={Ed25519:$s,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await Qs.publicKeyToBytes({publicKey:r});return await Qs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Qs.bytesToPublicKey,privateKeyToBytes:Qs.privateKeyToBytes,bytesToPrivateKey:Qs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await js.publicKeyToBytes({publicKey:r});return await js.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:js.bytesToPublicKey,privateKeyToBytes:js.privateKeyToBytes,bytesToPrivateKey:js.bytesToPrivateKey},X25519:Ch}[t];if(!e)throw new We("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function RK({newDid:t,previousDidProof:e}){let r=await AK({didUri:e.previousDid}),n=lA({didUri:t}),s=Je.base64Url(e.signature).toUint8Array();if(!await $s.verify({key:r,data:n,signature:s}))throw new We("invalidPreviousDidProof","The previous DID proof is invalid.")}var Oce=0,Nu=7200,O1=";",xi=",",DK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},CK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function Ew(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Je.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Ew(e)).join("");throw new We("internalError","Pkarr returned DNS TXT record with invalid data type")}function uw(t){return Ew(t).split(O1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function jK(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 Mce({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=Ew(a.data);r.alsoKnownAs=i.split(xi);break}case o.startsWith("cnt"):{let i=Ew(a.data);r.controller=i.includes(xi)?i.split(xi):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=uw(a.data),f=Je.base64Url(u).toUint8Array(),h=aA[Number(c)],p=await fA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||CK[Number(c)];let m=o==="k0"?"0":i===void 0?await ur({jwk:p}):i;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}=uw(a.data),l=u.includes(xi)?u.split(xi):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(xi)?p.split(xi):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=uw(a.data);n.types=i.split(xi).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(xi).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=uw(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 Bce({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 RK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Nu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Nu,data:t.alsoKnownAs.join(xi)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(xi):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Nu,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 DK))throw new We("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=Je.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${S}`];h!=="0"&&await ur({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==CK[m]&&w.push(`a=${p.alg}`),l.controller!==t.id&&w.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:w.join(O1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=Si(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,_])=>`${E}=${_}`).join(O1),w=jK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:w})});let u=[`v=${Oce}`];if(c.length&&u.push(`vm=${c.join(xi)}`),Object.keys(rP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=cK[d];u.push(`${f}=${l.join(xi)}`)}}),i.length&&u.push(`svc=${i.join(xi)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?aK[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Nu,data:`id=${d.join(xi)}`})}s.push({type:"TXT",name:"_did."+pU(t.id)+".",ttl:Nu,data:u.join(O1)});for(let d of r||[])a.push({type:"NS",name:"_did."+pU(t.id)+".",ttl:Nu,data:d+"."});return{id:0,type:"response",flags:Ice,answers:[...s,...a]}}function pU(t){return t.split(":")[2]}var Nce="https://enbox-did-dht.fly.dev";function Uce(){return U.DID_DHT_GATEWAY_URI||Nce}function Lce(){return U.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function hU(t,e){return{gatewayUri:t??Uce(),allowPrivateGatewayUri:e??Lce()}}var $K=class AI extends Dw{static async create({keyManager:e=new Aa,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in DK)))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 Uh.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?.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await ur({jwk:f});h=`${o}#${Si(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 Ec({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,allowPrivateGatewayUri:r.allowPrivateGatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Aa}){if(ls.parse(e.uri)?.method!==AI.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new We("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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>Si(a.id)===(Si(r)??Si(e.assertionMethod?.[0])));if(!s?.publicKeyJwk)throw new We("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r,allowPrivateGatewayUri:n}){let s=hU(r,n);return mU.put({did:e,...s})}static async resolve(e,r={}){let{gatewayUri:n,allowPrivateGatewayUri:s}=hU(r.gatewayUri,r.allowPrivateGatewayUri);try{await Uh.identifierToIdentityKey({didUri:e});let{didDocument:a,didDocumentMetadata:o}=await mU.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:s});return{...Bs,didDocument:a,didDocumentMetadata:o}}catch(a){if(!(a instanceof We))throw new Error(a);return{...Bs,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};$K.methodName="dht";var OK=$K,mU=class lw{static async get({didUri:e,gatewayUri:r,allowPrivateGatewayUri:n=!1}){let s=Uh.identifierToIdentityKeyBytes({didUri:e}),a=await lw.pkarrGet({gatewayUri:r,publicKeyBytes:s,allowPrivateGatewayUri:n}),o=await Uh.parseBep44GetMessage({bep44Message:a}),i=await lw.fromDnsPacket({didUri:e,dnsPacket:o});return i.didDocumentMetadata.versionId=a.seq.toString(),i}static async put({did:e,gatewayUri:r,allowPrivateGatewayUri:n=!1}){let s=await lw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),a=await Uh.createBep44PutMessage({dnsPacket:s,publicKeyBytes:Uh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),o=await lw.pkarrPut({gatewayUri:r,bep44Message:a,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o,versionId:a.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return Rce(e)}static async pkarrPut(e){return Dce(e)}static async fromDnsPacket(e){return Mce(e)}static async toDnsPacket(e){return Bce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Uh=class{static async createBep44PutMessage(t){return Cce(t)}static async identifierToIdentityKey(t){return AK(t)}static identifierToIdentityKeyBytes(t){return lA(t)}static async identityKeyToIdentifier(t){return $ce(t)}static keyConverter(t){return fA(t)}static async parseBep44GetMessage(t){return jce(t)}static parseTxtDataToObject(t){return uw(t)}static parseTxtDataToString(t){return Ew(t)}static async validatePreviousDidProof(t){return RK(t)}static chunkDataIfNeeded(t){return jK(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)}},d3e=new Uint8Array(0),Kce=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")},zce=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")}},qce=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 MK(this,t)}},Fce=class{constructor(t){this.decoders=t}or(t){return MK(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`)}},MK=(t,e)=>new Fce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Gce=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new zce(t,e,r),this.decoder=new qce(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},Wce=({name:t,prefix:e,encode:r,decode:n})=>new Gce(t,e,r,n),Vce=(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},Hce=(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},lP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Wce({prefix:e,name:t,encode(s){return Hce(s,n,r)},decode(s){return Vce(s,n,r,t)}}),u3e=lP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),l3e=lP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yU=lP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),f3e=lP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Gh=class M1{static encode(e){return yU.baseEncode(e)}static decodeAsBytes(e,r){if(!M1.isBase64UrlString(e))throw new Dn(Rn.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return yU.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)}},Jce=Rf($ne(),1),RI;(function(t){t.Public="public",t.Private="private"})(RI||(RI={}));var vc=RI,lo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===vc.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===vc.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(!Gh.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 Ia=pA,Zce=Rf(One(),1),kw=class DI{static canonicalizeAsBytes(e){let r=DI.removeAllUndefinedProperties(e),n=Zce.default(r);return Gh.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}},Yce=BK,gU=128,Qce=127,Xce=~Qce,ede=Math.pow(2,31);function BK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=ede;)e[r++]=t&255|gU,t/=128;for(;t&Xce;)e[r++]=t&255|gU,t>>>=7;return e[r]=t|0,BK.bytes=r-n+1,e}var tde=CI,rde=128,wU=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&wU)<<s:(o&wU)*Math.pow(2,s),s+=7}while(o>=rde);return CI.bytes=a-n,r}var nde=Math.pow(2,7),sde=Math.pow(2,14),ide=Math.pow(2,21),ode=Math.pow(2,28),ade=Math.pow(2,35),cde=Math.pow(2,42),dde=Math.pow(2,49),ude=Math.pow(2,56),lde=Math.pow(2,63),fde=function(t){return t<nde?1:t<sde?2:t<ide?3:t<ode?4:t<ade?5:t<cde?6:t<dde?7:t<ude?8:t<lde?9:10},pde={encode:Yce,decode:tde,encodingLength:fde},hde=pde,X1=hde,vU=(t,e=0)=>[X1.decode(t,e),X1.decode.bytes],bU=(t,e,r=0)=>(X1.encode(t,e,r),e),PU=t=>X1.encodingLength(t),xU=(t,e)=>{let r=e.byteLength,n=PU(t),s=n+PU(r),a=new Uint8Array(s+r);return bU(t,a,0),bU(r,a,n),a.set(e,s),new NK(t,r,e,a)},mde=t=>{let e=Kce(t),[r,n]=vU(e),[s,a]=vU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new NK(r,s,o,e)},NK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},UK=({name:t,code:e,encode:r})=>new yde(t,e,r),yde=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?xU(this.code,e):e.then(r=>xU(this.code,r))}else throw Error("Unknown type, must be binary type")}},LK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),SU=UK({name:"sha2-256",code:18,encode:LK("SHA-256")}),p3e=UK({name:"sha2-512",code:19,encode:LK("SHA-512")}),Qg=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())})},po=class fw{static hash(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield SU.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 Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield SU.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 Qg(this,void 0,void 0,function*(){let n=kw.canonicalizeAsBytes(e);return yield fw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=kw.canonicalizeAsBytes(e),s=yield fw.hashAsNonMultihashBytes(n,r);return yield fw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=yield fw.hash(e,r);return Gh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Gh.decodeAsBytes(e,r);try{n=mde(s)}catch{throw new Dn(Rn.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Ia.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 Dh=$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())})},KK=class Lo{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;lo.validateEs256kOperationKey(r,vc.Public),lo.validateEs256kOperationKey(n,vc.Public),Lo.validateDidDocumentKeys(s),Lo.validateServices(a);let o=Ia.hashAlgorithmInMultihashCode,i=[{action:Dh.Replace,document:e.document}],c={updateCommitment:yield po.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Lo.validateDeltaSize(c);let u={deltaHash:yield po.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:w1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return v1(this,void 0,void 0,function*(){Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public);let r=Ia.hashAlgorithmInMultihashCode,n=yield po.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*(){Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextRecoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Lo.validateDidDocumentKeys(e.document.publicKeys),Lo.validateServices(e.document.services);let r=Ia.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Dh.Replace,document:e.document}],a=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield po.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield po.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(Lo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.updatePublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Lo.validateServices(e.servicesToAdd),Lo.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)lo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)lo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Dh.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Dh.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Dh.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Dh.RemovePublicKeys,ids:o};r.push(p)}let i=Ia.hashAlgorithmInMultihashCode,c=yield po.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield po.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){po.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(lo.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),lo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Lo.validateService(n),r.has(n.id))throw new Dn(Rn.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){lo.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"&&Jce.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=kw.canonicalizeAsBytes(e);if(r.length>Ia.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Ia.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Dn(Rn.DeltaExceedsMaximumSize,n)}}},EU=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())})},gde=class zK{static createLongFormDid(e){return EU(this,void 0,void 0,function*(){let r=yield KK.createCreateRequest(e),n=yield zK.computeDidUniqueSuffix(r.suffixData),s;Ia.network===void 0||Ia.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Ia.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=kw.canonicalizeAsBytes(a),i=Gh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return EU(this,void 0,void 0,function*(){let r=kw.canonicalizeAsBytes(e),n=yield po.hash(r,Ia.hashAlgorithmInMultihashCode);return Gh.encode(n)})}},Cs=2n**255n-19n,B1=2n**252n+27742317777372353535851937790883648493n,OI=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,MI=0x6666666666666666666666666666666666666666666666666666666666666658n,b1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Cs,n:B1,h:8,Gx:OI,Gy:MI},Ui=(t="")=>{throw new Error(t)},qK=t=>typeof t=="string",hA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Ui("Uint8Array expected"):t,Wh=t=>new Uint8Array(t),wde=(t,e)=>hA(qK(t)?yA(t):Wh(t),e),Xe=(t,e=Cs)=>{let r=t%e;return r>=0n?r:e+r},kU=t=>t instanceof Vh?t:Ui("Point expected"),_U,Vh=class $h{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new $h(e.x,e.y,1n,Xe(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=b1;e=wde(e,32);let s=e.slice();s[31]=e[31]&-129;let a=bde(s);a===0n||(r&&!(0n<a&&a<Cs)&&Ui("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Ui("bad y coord 2"));let o=Xe(a*a),i=Xe(o-1n),c=Xe(n*o+1n),{isValid:u,value:d}=xde(i,c);u||Ui("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=Xe(-d)),new $h(d,a,1n,Xe(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}=kU(e),c=Xe(r*i),u=Xe(a*s),d=Xe(n*i),l=Xe(o*s);return c===u&&d===l}is0(){return this.equals(N1)}negate(){return new $h(Xe(-this.ex),this.ey,this.ez,Xe(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=b1,a=Xe(e*e),o=Xe(r*r),i=Xe(2n*Xe(n*n)),c=Xe(s*a),u=e+r,d=Xe(Xe(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=Xe(d*f),m=Xe(l*h),y=Xe(d*h),S=Xe(f*l);return new $h(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=kU(e),{a:d,d:l}=b1,f=Xe(r*o),h=Xe(n*i),p=Xe(a*l*u),m=Xe(s*c),y=Xe((r+n)*(o+i)-f-h),S=Xe(m-p),w=Xe(m+p),E=Xe(h-d*f),_=Xe(y*S),I=Xe(w*E),D=Xe(y*E),N=Xe(S*w);return new $h(_,I,N,D)}mul(e,r=!0){if(e===0n)return r===!0?Ui("cannot multiply by 0"):N1;if(typeof e=="bigint"&&0n<e&&e<B1||Ui("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(eP))return kde(e).p;let n=N1,s=eP;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(B1/2n,!1).double();return B1%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=GK(n);return Xe(n*s)!==1n&&Ui("invalid inverse"),{x:Xe(e*s),y:Xe(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=vde(r);return n[31]|=e&1n?128:0,n}toHex(){return mA(this.toRawBytes())}};Vh.BASE=new Vh(OI,MI,1n,Xe(OI*MI));Vh.ZERO=new Vh(0n,1n,1n,0n);var{BASE:eP,ZERO:N1}=Vh,FK=(t,e)=>t.toString(16).padStart(e,"0"),mA=t=>Array.from(t).map(e=>FK(e,2)).join(""),yA=t=>{let e=t.length;(!qK(t)||e%2)&&Ui("hex invalid 1");let r=Wh(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)&&Ui("hex invalid 2"),r[n]=o}return r},vde=t=>yA(FK(t,32*2)).reverse(),bde=t=>BigInt("0x"+mA(Wh(hA(t)).reverse())),TU=(...t)=>{let e=Wh(t.reduce((n,s)=>n+hA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},GK=(t,e=Cs)=>{(t===0n||e<=0n)&&Ui("no inverse n="+t+" mod="+e);let r=Xe(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?Xe(s,e):Ui("no inverse")},yc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Cs;return r},Pde=t=>{let e=t*t%Cs*t%Cs,r=yc(e,2n)*e%Cs,n=yc(r,1n)*t%Cs,s=yc(n,5n)*n%Cs,a=yc(s,10n)*s%Cs,o=yc(a,20n)*a%Cs,i=yc(o,40n)*o%Cs,c=yc(i,80n)*i%Cs,u=yc(c,80n)*i%Cs,d=yc(u,10n)*s%Cs;return{pow_p_5_8:yc(d,2n)*t%Cs,b2:e}},IU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,xde=(t,e)=>{let r=Xe(e*e*e),n=Xe(r*r*e),s=Pde(t*n).pow_p_5_8,a=Xe(t*r*s),o=Xe(e*a*a),i=a,c=Xe(a*IU),u=o===t,d=o===Xe(-t),l=o===Xe(-t*IU);return u&&(a=i),(d||l)&&(a=c),(Xe(a)&1n)===1n&&(a=Xe(-a)),{isValid:u||d,value:a}},mI,AU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Sde={bytesToHex:mA,hexToBytes:yA,concatBytes:TU,mod:Xe,invert:GK,randomBytes:t=>{let e=AU();return e||Ui("crypto.getRandomValues must be defined"),e.getRandomValues(Wh(t))},sha512Async:async(...t)=>{let e=AU();e||Ui("crypto.subtle or etc.sha512Async must be defined");let r=TU(...t);return Wh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(Sde,{sha512Sync:{configurable:!1,get(){return mI},set(t){mI||(mI=t)}}});var bf=8,Ede=()=>{let t=[],e=256/bf+1,r=eP,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(bf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},kde=t=>{let e=_U||(_U=Ede()),r=(d,l)=>{let f=l.negate();return d?f:l},n=N1,s=eP,a=1+256/bf,o=2**(bf-1),i=BigInt(2**bf-1),c=2**bf,u=BigInt(bf);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,_f=gA-0x1000003d1n,wA=gA-0x14551231950b75fc4402da1732fc9bebfn,WK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,VK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,HK={p:_f,n:wA,a:0n,b:7n,Gx:WK,Gy:VK},zh=32,RU=t=>Ge(Ge(t*t)*t+HK.b),us=(t="")=>{throw new Error(t)},fP=t=>typeof t=="bigint",JK=t=>typeof t=="string",yI=t=>fP(t)&&0n<t&&t<_f,ZK=t=>fP(t)&&0n<t&&t<wA,YK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?us("Uint8Array expected"):t,_w=t=>new Uint8Array(t),vA=(t,e)=>YK(JK(t)?pP(t):_w(t),e),Ge=(t,e=_f)=>{let r=t%e;return r>=0n?r:e+r},DU=t=>t instanceof Hh?t:us("Point expected"),CU,Hh=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=jU(s,0,zh),o=e.length;if(o===33&&[2,3].includes(n)){yI(a)||us("Point hex invalid: x not FE");let i=_de(RU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=Ge(-i)),r=new Oh(a,i,1n)}return o===65&&n===4&&(r=new Oh(a,jU(s,zh,2*zh),1n)),r?r.ok():us("Point is not on curve")}static fromPrivateKey(e){return yw.mul(Tde(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}=DU(e),c=Ge(r*i),u=Ge(a*s),d=Ge(n*i),l=Ge(o*s);return c===u&&d===l}negate(){return new Oh(this.px,Ge(-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}=DU(e),{a:c,b:u}=HK,d=0n,l=0n,f=0n,h=Ge(u*3n),p=Ge(r*a),m=Ge(n*o),y=Ge(s*i),S=Ge(r+n),w=Ge(a+o);S=Ge(S*w),w=Ge(p+m),S=Ge(S-w),w=Ge(r+s);let E=Ge(a+i);return w=Ge(w*E),E=Ge(p+y),w=Ge(w-E),E=Ge(n+s),d=Ge(o+i),E=Ge(E*d),d=Ge(m+y),E=Ge(E-d),f=Ge(c*w),d=Ge(h*y),f=Ge(d+f),d=Ge(m-f),f=Ge(m+f),l=Ge(d*f),m=Ge(p+p),m=Ge(m+p),y=Ge(c*y),w=Ge(h*w),m=Ge(m+y),y=Ge(p-y),y=Ge(c*y),w=Ge(w+y),p=Ge(m*w),l=Ge(l+p),p=Ge(E*w),d=Ge(S*d),d=Ge(d-p),p=Ge(S*m),f=Ge(E*f),f=Ge(f+p),new Oh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return U1;if(ZK(e)||us("invalid scalar"),this.equals(yw))return Dde(e).p;let n=U1,s=yw;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(U1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=XK(n);return Ge(n*s)!==1n&&us("invalid inverse"),{x:Ge(e*s),y:Ge(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!yI(e)||!yI(r))&&us("Point invalid: x or y"),Ge(r*r)===RU(e)?this:us("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")+$U(r)+(e?"":$U(n))}toRawBytes(e=!0){return pP(this.toHex(e))}};Hh.BASE=new Hh(WK,VK,1n);Hh.ZERO=new Hh(0n,1n,0n);var{BASE:yw,ZERO:U1}=Hh,QK=(t,e)=>t.toString(16).padStart(e,"0"),bA=t=>Array.from(t).map(e=>QK(e,2)).join(""),pP=t=>{let e=t.length;(!JK(t)||e%2)&&us("hex invalid 1");let r=_w(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)&&us("hex invalid 2"),r[n]=o}return r},hP=t=>BigInt("0x"+(bA(t)||"0")),jU=(t,e,r)=>hP(t.slice(e,r)),PA=t=>fP(t)&&t>=0n&&t<gA?pP(QK(t,2*zh)):us("bigint expected"),$U=t=>bA(PA(t)),OU=(...t)=>{let e=_w(t.reduce((n,s)=>n+YK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},XK=(t,e=_f)=>{(t===0n||e<=0n)&&us("no inverse n="+t+" mod="+e);let r=Ge(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?Ge(s,e):us("no inverse")},_de=t=>{let e=1n;for(let r=t,n=(_f+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%_f),r=r*r%_f;return Ge(e*e)===t?e:us("sqrt invalid")},Tde=t=>(fP(t)||(t=hP(vA(t,zh))),ZK(t)?t:us("private key out of range")),MU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,L1;function Ide(t){t=vA(t);let e=zh+8;(t.length<e||t.length>1024)&&us("expected proper params");let r=Ge(hP(t),wA-1n)+1n;return PA(r)}var Ade={hexToBytes:pP,bytesToHex:bA,concatBytes:OU,bytesToNumberBE:hP,numberToBytesBE:PA,mod:Ge,invert:XK,hmacSha256Async:async(t,...e)=>{let r=MU();if(!r)return us("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return _w(await n.sign("HMAC",s,OU(...e)))},hmacSha256Sync:L1,hashToPrivateKey:Ide,randomBytes:t=>{let e=MU();return e||us("crypto.getRandomValues must be defined"),e.getRandomValues(_w(t))}};Object.defineProperties(Ade,{hmacSha256Sync:{configurable:!1,get(){return L1},set(t){L1||(L1=t)}}});var Pf=8,Rde=()=>{let t=[],e=256/Pf+1,r=yw,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},Dde=t=>{let e=CU||(CU=Rde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=U1,s=yw,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}},BU;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(BU||(BU={}));var NU;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(NU||(NU={}));var Xg=class wf{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 wf.createIonDocument({services:n,verificationMethods:s}),o=wf.normalizeJwk(e),i=wf.normalizeJwk(r);return await gde.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await KK.createCreateRequest({document:e,recoveryKey:wf.normalizeJwk(r),updateKey:wf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await ur({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:wf.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}},Cde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(Cde||{}),jde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},UU="https://ion.tbd.engineering",$de=class pw extends Dw{static async create({keyManager:e=new Aa,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in jde)))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 Xg.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await pw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ec({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 pw.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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!s?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==pw.methodName)throw new We("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=UU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:rK({didDocument:e.document,methodId:o.id})}))??[],s=await Xg.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await Xg.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=Xg.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{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==pw.methodName)return{...Bs,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??UU;try{let a=Xg.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new We("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...Bs,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof We))throw new Error(a);return{...Bs,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};$de.methodName="ion";var e9=class hw extends Dw{static async create({keyManager:e=new Aa,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=Je.object(a).toBase64Url(),i=`did:${hw.methodName}:${o}`,c=(await hw.resolve(i)).didDocument;return new Ec({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 We("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==hw.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new We("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?Je.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...Bs,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{...Bs,didDocument:a}}};e9.methodName="jwk";var t9=e9,Ode={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},K1=class Mh{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=Mh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ho.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":Qs.compressPublicKey,secp256k1:js.compressPublicKey}[e];if(!r)throw new We("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:$s,"P-256":Qs,secp256k1:js}[e];if(!r)throw new We("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?Ho.getNameFromCode({code:e}):r;let n=r,s=Mh.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 Ode))throw new We("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Mh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Mh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Mh.jwkToMulticodec({jwk:e});return sK({keyBytes:r,multicodecName:n})}};K1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},K1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},K1.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=K1,Mde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(Mde||{}),LU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},r9=class Ku extends Dw{static async create({keyManager:e=new Aa,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:${Ku.methodName}:${o}`,c=(await Ku.resolve(i,r)).didDocument;return new Ec({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 We("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!s?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==Ku.methodName)throw new We("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new We("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await Ku.createDocument({didUri:e,options:r});return{...Bs,didDocument:n}}catch(n){if(!(n instanceof We))throw new Error(n);return{...Bs,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 We("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==Ku.methodName)throw new We("methodNotSupported",`Method not supported: ${i.method}`);if(!Ku.validateIdentifier(i))throw new We("invalidDid",`Invalid DID URI: ${e}`);let u=await Ku.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 tK({didDocument:o}).forEach(l=>{let f=LU[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}=iK({multibaseKeyId:r}),d=i.byteLength,l=P1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new We("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await js.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new We("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new We("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in LU))throw new We("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new We("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&&gI(n)==="String"&&n.startsWith("z")}};r9.methodName="key";var $w=r9,Bde=3e4,n9=class z1 extends Dw{static async create({keyManager:e=new Aa,options:r}){if(!r.domain)throw new We("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:${z1.methodName}:${n}`;if(!ls.parse(s))throw new We("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 Ec({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 We("methodNotSupported",`Method not supported: ${n.method}`);let s=Si(r)??Si(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>Si(o.id)===s):e.verificationMethod?.[0];if(!a?.publicKeyJwk)throw new We("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 Aa}){if(ls.parse(e.uri)?.method!==z1.methodName)throw new We("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=ls.parse(e);if(!n)return{...Bs,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==z1.methodName)return{...Bs,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=await oL(a,{signal:AbortSignal.timeout(Bde)},{description:"did:web document URL"});if(!o.ok)throw new Error("HTTP error status code returned");let i=await o.json();return{...Bs,didDocument:i}}catch{return{...Bs,didResolutionMetadata:{error:"notFound"}}}}};n9.methodName="web";var s9=n9,h3e=Rf(ZU(),1),m3e=Rf(YU(),1);var Nde=Rf(YU(),1),i9=class{constructor({ttl:t="15m"}={}){this.cache=new Bne.default({ttl:(0,Nde.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(){}},Ude={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()}},o9=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=t||Ude;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{...Bs,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...Bs,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};if(e!==void 0)return n.resolve(r.uri,e);let s=await this.cache.get(r.uri);if(s)return s;let a=this._inFlight.get(r.uri);if(a)return a;let o=(async()=>{let i=await n.resolve(r.uri,e);if(!i.didResolutionMetadata.error)try{await this.cache.set(r.uri,i)}catch{}return i})();this._inFlight.set(r.uri,o);try{return await o}finally{this._inFlight.delete(r.uri)}}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:{}}}};Jt();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 Rh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new c1(e.resumableTaskStore,this.storageController),this._coreProtocols=new ag,this._coreProtocols.register(new kr);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 o9({didResolvers:[OK,t9,$w,s9],cache:new i9}),e.ownsResolver=!0),e.tenantGate??=new cg;let r=new t(e);return await r.open(),r}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,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{ge.validateJsonSchema(e)}catch(s){return ot(s,400)}}};ut();Jt();pn();Dy();wi();v();function Lde(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,Lde(e)]):t}Ba();sr();fa();_0();Mn();c0();r2();Za();gi();FE();Al();v();Xm();v();import{Level as Kde}from"level";async function Ki(t,e){return new Kde(t,{...e,keyEncoding:"utf8"})}var Ra=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...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 Bf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...e},this.db=r??new Ra({...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),Nt.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:Nt.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()}};v();Vd();v();var IP=Kn(_o(),1);v();function zde(t){return t[Symbol.asyncIterator]!=null}function qde(t){if(zde(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 a9=qde;Fc();v();Tp();To();var q9=Kn(_o(),1);fy();v();Qu();rp();var c9=0,Fde="identity",d9=Yo,Gde=t=>sl(c9,d9(t)),u9={code:c9,name:Fde,encode:d9,digest:Gde};v();Tp();var l9=Kn(_o(),1);Fc();var Wde=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=G2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=Nt.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,l9.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}}}},f9=Wde;v();var p9=Kn(_o(),1);rp();Wc();v();function Vde(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 Nf=Vde;v();var Ow=Kn(_o(),1),Hde=(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}},Qh=Hde;var Jde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new yn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Zde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,p9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=a0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Jde(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},h9=Zde;v();var m9=Kn(_o(),1);Wc();var Yde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new yn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Qde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,m9.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:Yde(c),depth:a,size:BigInt(c.length),node:c}}},y9=Qde;v();To();var qw=Kn(_o(),1);Zd();v();To();GS();WS();var Xde=async function(t){return(await dv.encode(t)).slice(0,8).reverse()},eue=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 Ga({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},g9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),tue=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},w9=async(t,e,r,n,s)=>{if(n==null){let d=fv({hashFn:Xde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await eue(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=g9(a.pos),i=tue(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=g9(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=Gc(u),w9(t,e,r,n,s)},v9=w9;v();v();v();function rue(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 mP=rue;function nue(t){return t[Symbol.asyncIterator]!=null}function sue(t,e){let r=0;if(nue(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=mP(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 b9=sue;v();function iue(t){return t[Symbol.asyncIterator]!=null}function oue(t,e){let r=0;if(iue(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=mP(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 Xh=oue;v();v();function zi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var yP=globalThis.CustomEvent??Event;async function*Uf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=zi(),i=zi(),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=zi(),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 yP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new yP("task-complete"))})}c=!0,s.dispatchEvent(new yP("task-complete"))}catch(p){u=p,s.dispatchEvent(new yP("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=zi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}v();v();v();var gP=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}},em=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new gP(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 gP(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 wP(t={}){return aue(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 aue(t,e){e=e??{};let r=e.onEnd,n=new em,s,a,o,i=zi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=w=>{a=null,n.push(w);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=zi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new em,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 em,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 w,E;S!=null&&(w=new Promise((_,I)=>{E=()=>{I(new SA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,w])}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}v();v();v();function cue(t){return t.reason}async function P9(t,e,r){if(e==null)return t;let n=r?.translateError??cue;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=zi(),this.haveNext=zi()}[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=zi(),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=zi(),await P9(this.readNext.promise,r?.signal,r)}};function x9(){return new EA}function due(t){return t[Symbol.asyncIterator]!=null}async function uue(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*lue(t){let e=new AbortController,r=x9();uue(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*fue(t){for(let e of t)yield*e}function pue(...t){let e=[];for(let r of t)due(r)||e.push(r);return e.length===t.length?fue(e):lue(t)}var S9=pue;function tm(t,...e){if(t==null)throw new Error("Empty pipeline");if(kA(t)){let n=t;t=()=>n.source}else if(k9(t)||E9(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]=mue(r[n]));return hue(...r)}var hue=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},E9=t=>t?.[Symbol.asyncIterator]!=null,k9=t=>t?.[Symbol.iterator]!=null,kA=t=>t==null?!1:t.sink!=null&&t.source!=null,mue=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=wP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(E9(a))s=async function*(){yield*a,n.end()};else if(k9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return S9(n,s())}return t.source};Wc();var yue=(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 yn("unixfs:exporter:walk:directory",{cid:t})),yield*tm(l,f=>Xh(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Uf(f,{ordered:!0}),f=>b9(f,h=>h!=null))}return i},_9=yue;v();To();var Kf=Kn(_o(),1);Zd();fy();v();v();var TA=Kn(I9(),1);v();var Bw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},IA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},A9=t=>globalThis.DOMException===void 0?new IA(t):new DOMException(t),R9=t=>{let e=t.reason===void 0?A9("This operation was aborted."):t.reason;return e instanceof Error?e:A9(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(R9(c)),c.addEventListener("abort",()=>{i(R9(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 Bw(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}v();v();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 Lf=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)},Td,DA=class{constructor(){Td.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Lf(this,Td,"f")[this.size-1].priority>=r.priority){Lf(this,Td,"f").push(n);return}let s=RA(Lf(this,Td,"f"),n,(a,o)=>o.priority-a.priority);Lf(this,Td,"f").splice(s,0,n)}dequeue(){let e=Lf(this,Td,"f").shift();return e?.run}filter(e){return Lf(this,Td,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Lf(this,Td,"f").length}};Td=new WeakMap;var D9=DA;var ln=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},Ke=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,Uw,Lw,Ju,kP,Kw,bP,Da,Nw,go,PP,wo,zw,Hu,xP,C9,j9,M9,$9,O9,SP,CA,jA,_P,B9,EP,TP=class extends Error{},$A=class extends TA.default{constructor(e){var r,n,s,a;if(super(),jn.add(this),Uw.set(this,void 0),Lw.set(this,void 0),Ju.set(this,0),kP.set(this,void 0),Kw.set(this,void 0),bP.set(this,0),Da.set(this,void 0),Nw.set(this,void 0),go.set(this,void 0),PP.set(this,void 0),wo.set(this,0),zw.set(this,void 0),Hu.set(this,void 0),xP.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:D9,...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})`);ln(this,Uw,e.carryoverConcurrencyCount,"f"),ln(this,Lw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),ln(this,kP,e.intervalCap,"f"),ln(this,Kw,e.interval,"f"),ln(this,go,new e.queueClass,"f"),ln(this,PP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,ln(this,xP,e.throwOnTimeout===!0,"f"),ln(this,Hu,e.autoStart===!1,"f")}get concurrency(){return Ke(this,zw,"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})`);ln(this,zw,e,"f"),Ke(this,jn,"m",_P).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ke(this,xP,"f"),...r},new Promise((n,s)=>{Ke(this,go,"f").enqueue(async()=>{var a,o,i;ln(this,wo,(o=Ke(this,wo,"f"),o++,o),"f"),ln(this,Ju,(i=Ke(this,Ju,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new TP("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,Ke(this,jn,"m",B9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Bw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ke(this,jn,"m",M9).call(this)}},r),this.emit("add"),Ke(this,jn,"m",SP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ke(this,Hu,"f")?(ln(this,Hu,!1,"f"),Ke(this,jn,"m",_P).call(this),this):this}pause(){ln(this,Hu,!0,"f")}clear(){ln(this,go,new(Ke(this,PP,"f")),"f")}async onEmpty(){Ke(this,go,"f").size!==0&&await Ke(this,jn,"m",EP).call(this,"empty")}async onSizeLessThan(e){Ke(this,go,"f").size<e||await Ke(this,jn,"m",EP).call(this,"next",()=>Ke(this,go,"f").size<e)}async onIdle(){Ke(this,wo,"f")===0&&Ke(this,go,"f").size===0||await Ke(this,jn,"m",EP).call(this,"idle")}get size(){return Ke(this,go,"f").size}sizeBy(e){return Ke(this,go,"f").filter(e).length}get pending(){return Ke(this,wo,"f")}get isPaused(){return Ke(this,Hu,"f")}};Uw=new WeakMap,Lw=new WeakMap,Ju=new WeakMap,kP=new WeakMap,Kw=new WeakMap,bP=new WeakMap,Da=new WeakMap,Nw=new WeakMap,go=new WeakMap,PP=new WeakMap,wo=new WeakMap,zw=new WeakMap,Hu=new WeakMap,xP=new WeakMap,jn=new WeakSet,C9=function(){return Ke(this,Lw,"f")||Ke(this,Ju,"f")<Ke(this,kP,"f")},j9=function(){return Ke(this,wo,"f")<Ke(this,zw,"f")},M9=function(){var e;ln(this,wo,(e=Ke(this,wo,"f"),e--,e),"f"),Ke(this,jn,"m",SP).call(this),this.emit("next")},$9=function(){Ke(this,jn,"m",jA).call(this),Ke(this,jn,"m",CA).call(this),ln(this,Nw,void 0,"f")},O9=function(){let e=Date.now();if(Ke(this,Da,"f")===void 0){let r=Ke(this,bP,"f")-e;if(r<0)ln(this,Ju,Ke(this,Uw,"f")?Ke(this,wo,"f"):0,"f");else return Ke(this,Nw,"f")===void 0&&ln(this,Nw,setTimeout(()=>{Ke(this,jn,"m",$9).call(this)},r),"f"),!0}return!1},SP=function(){if(Ke(this,go,"f").size===0)return Ke(this,Da,"f")&&clearInterval(Ke(this,Da,"f")),ln(this,Da,void 0,"f"),this.emit("empty"),Ke(this,wo,"f")===0&&this.emit("idle"),!1;if(!Ke(this,Hu,"f")){let e=!Ke(this,jn,"a",O9);if(Ke(this,jn,"a",C9)&&Ke(this,jn,"a",j9)){let r=Ke(this,go,"f").dequeue();return r?(this.emit("active"),r(),e&&Ke(this,jn,"m",CA).call(this),!0):!1}}return!1},CA=function(){Ke(this,Lw,"f")||Ke(this,Da,"f")!==void 0||(ln(this,Da,setInterval(()=>{Ke(this,jn,"m",jA).call(this)},Ke(this,Kw,"f")),"f"),ln(this,bP,Date.now()+Ke(this,Kw,"f"),"f"))},jA=function(){Ke(this,Ju,"f")===0&&Ke(this,wo,"f")===0&&Ke(this,Da,"f")&&(clearInterval(Ke(this,Da,"f")),ln(this,Da,void 0,"f")),ln(this,Ju,Ke(this,Uw,"f")?Ke(this,wo,"f"):0,"f"),Ke(this,jn,"m",_P).call(this)},_P=function(){for(;Ke(this,jn,"m",SP).call(this););},B9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new TP("The task was aborted."))},{once:!0})})},EP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var N9=$A;Wc();async function U9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Nf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,Kf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=ss.unmarshal(e.Data)}catch(u){throw(0,Kf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Nf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,Kf.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 tm(c,u=>Xh(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Uf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case sy:h=Gc(l);break;case Yd:h=l;break;default:r.end((0,Kf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new N9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new yn("unixfs:exporter:walk:file",{cid:d.Hash})),await U9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var vue=(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}=Qh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=wP();c.onProgress?.(new yn("unixfs:exporter:walk:file",{cid:t})),U9(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,Kf.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 yn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,Kf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},OA=vue;v();To();Wc();var bue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new yn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),L9(e,n,s,a,o,c)}return i};async function*L9(t,e,r,n,s,a){let o=t.Links,i=tm(o,c=>Xh(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=Gc(l),a.onProgress?.(new yn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:L9(t,e,r,n,s,a)}}}),c=>Uf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var K9=bue;var Pue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,xue={raw:OA,file:OA,directory:_9,"hamt-sharded-directory":K9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},Sue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Gc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,qw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=ss.unmarshal(u.Data)}catch(h){throw(0,qw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await v9(u,n[0],o):h=Pue(u,n[0]),h==null)throw(0,qw.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=xue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,qw.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}},z9=Sue;var Eue={[sy]:z9,[Yd]:y9,[Wd]:f9,[u9.code]:h9},F9=async(t,e,r,n,s,a,o)=>{let i=Eue[t.code];if(i==null)throw(0,q9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,F9,s,a,o)},G9=F9;var kue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),_ue=t=>{if(t instanceof Uint8Array)return{cid:Nt.decode(t),toResolve:[]};let e=Nt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=kue(t);return{cid:Nt.parse(r[0]),toResolve:r.slice(1)}}throw(0,IP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*Tue(t,e,r={}){let{cid:n,toResolve:s}=_ue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await G9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,IP.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 W9(t,e,r={}){let n=await a9(Tue(t,e,r));if(n==null)throw(0,IP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}JS();var MA=new TextEncoder,AP=new TextDecoder,BA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ki,...e},this.blockstore=new Bf({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(AP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(AP.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=my([{content:ns.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,MA.encode(JSON.stringify({dataSize:d}))),await i.put(n,MA.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(AP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await W9(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(AP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,MA.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")}};v();Vt();YS();Za();v();ga();Za();var RP="";async function V9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function H9(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(RP),c=n(o);return i+RP+c+s+t}function J9(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(RP)+RP}function Z9(t,e,r,n,s,a){let o=H9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return Q9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function Y9(t,e,r,n,s,a,o){let i=H9(r,n,s,a,o);if(i!==void 0)return Q9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function Q9(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 X9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=J9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await V9(t,e,s),p={};if(d===void 0)u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);else{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)}let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let w=[];for await(let[E,_]of h.iterator(p,c)){if(l!==void 0&&w.length===l)break;let I=JSON.parse(_);S&&!Ut.matchFilter(I.indexes,y)||w.push(I)}return w}async function ez(t,e,r,n,s,a,o){let i=J9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await V9(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);Ut.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ut();ga();var tz="index",rm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ki,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Ra({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 re("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=Y9(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(tz,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(tz)}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 X9(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 ez(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;Ut.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 re("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new re("IndexInvalidCursorValueType",`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,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?0:this.findCursorStartingIndex(l,o,a,u);if(f<0)return[];let h=c===void 0?void 0:f+c;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)||!Ut.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new re("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(Ut.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Ut.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Ut.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?yy(i,c):yy(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}};v();v();Xm();Y2();function DP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Iue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=Nt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*UA(n,s))}else{let r=Nt.asCID(e);r?yield[t.join("/"),r]:yield*UA(e,t)}}function*UA(t,e){if(t==null||t instanceof Uint8Array)return;let r=Nt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*Iue(a,s)}}function*Aue(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!Nt.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"&&!Nt.asCID(n)&&(yield*Aue(s,n))}}function Rue(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=Nt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var CP=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:DP(),bytes:DP(),value:DP(),asBlock:DP()})}links(){return UA(this.value,[])}tree(){return LA(this.value,[])}get(e="/"){return Rue(this.value,e.split("/").filter(Boolean))}};async function rz({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=Nt.create(1,e.code,s);return new CP({value:t,bytes:n,cid:a})}async function nz({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=Nt.create(1,e.code,s);return new CP({value:n,bytes:t,cid:a})}Tp();Vc();Fc();sr();Rd();Za();var Cue=[{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:Ki,...e},this.blockstore=new Bf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new rm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??Cue})}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=Nt.parse(r),o=await s.get(a,n);return o?(await Nn(nz({bytes:o,codec:qc,hasher:xn}),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=rm.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=Nt.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(rz({value:r,codec:qc,hasher:xn}),s?.signal),i=Rr.parseCid(await ge.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()}};v();Vc();var zA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ki,...e},this.db=new Ra({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 Rr.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()}};v();v();function sz(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)})}}}ga();ut();var iz="events",qA=class t{emitter=sz();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){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}else s="epoch_mismatch";let a=await this.getReplayBounds(e),o={requested:r,oldestAvailable:a?.oldest??r,latestAvailable:a?.latest??r,reason:s},i=new re("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 re("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}_${iz}`;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?void 0:t.parsePosition(n.position),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&&!Ut.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 re("EventLogNotOpenError",`invalid cursor position: '${e}'`);return Number(r)}catch(r){throw r instanceof re?r:new re("EventLogNotOpenError",`invalid cursor position: '${e}'`)}}async subscribe(e,r,n,s){let a=`${e}_${iz}`,{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&&!Ut.matchAnyFilter(S.indexes,i)||(f?c(S).then(w=>{n({type:"event",cursor:w,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?d:t.parsePosition(p.cursor.position);for(let S of p.events){let w=await this.buildToken(e,S.seq,S.messageCid??"");n({type:"event",cursor:w,event:S.event})}f=!0;for(let S of l)if(S.seq>y){let w=await this.buildToken(e,S.seq,S.messageCid);n({type:"event",cursor:w,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&&!Ut.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)}};v();vu();v();vu();var Fw=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=Zn(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=Zn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Zn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return ef(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Zn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Zn(e.leftHash),rightHash:Zn(e.rightHash)}:{type:"leaf",keyHash:Zn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:ef(e.leftHash),rightHash:ef(e.rightHash)}:{type:"leaf",keyHash:ef(e.keyHash),valueCid:e.valueCid}}};v();vu();var Gw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await ph()}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 Xl(e),n=await ug(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 Xl(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 Xl(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await Xl(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(tn(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?.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(tn(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(tn(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>=vi||tn(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return tn(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=co(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 wu(u,d);if(!tn(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<vi&&co(e.keyHash,o)===co(n.keyHash,o);)o++;if(o>=vi)return s;let i=co(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await wu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=co(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await wu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=vi)return this.defaultHashes[vi];if(tn(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 tn(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=co(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),tn(i,this.defaultHashes[n+1])&&tn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=tn(i,this.defaultHashes[n+1]),d=tn(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let l=await wu(i,c);if(!tn(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>=vi||tn(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return tn(s.keyHash,r);let a=s;return co(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=vi)return{siblings:[],leafNode:void 0,depth:n};if(tn(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=co(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(co(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await ug(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(co(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=vi||tn(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(tn(e,r)||n>=vi)return;let c=tn(e,this.defaultHashes[n]),u=tn(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"){tn(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:Ki,...e}}async open(){this.db=new Ra({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await ph()}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 Fw(n),a=new Gw(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")}};v();vu();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(Zn(e))}async putNode(e,r){this.nodes.set(Zn(e),r)}async deleteNode(e){this.nodes.delete(Zn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};vu();v();Tp();Fc();Vd();QP();pn();Ba();_0();Mn();wi();Vt();c0();Rd();gi();Up();Dy();Jt();Kp();var jue={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 wn.generateKey();o={publicJwk:await wn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await fd.create({definition:jue,signer:pt.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=pt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await fd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=pt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Ot(s);let a=await hf.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=pt.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 kr.createGrant(c);return{dataStream:ns.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=pt.createSigner(r),s=pt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=ns.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 gt.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 ya.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:w}=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},D=await gt.getEntryId(n.did,y.descriptor),N=ke.constructKeyDerivationPathUsingProtocolContextScheme(D),$=await Ha.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 w.encryptSymmetricEncryptionKey(E),await w.sign({signer:pt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:w,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=ns.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:pt.createSigner(e.author)},u=await gt.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=pt.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};Ot(a);let i=(await Jl.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=pt.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};Ot(a);let i=(await mf.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=pt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};Ot(a);let i=(await Hl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await pd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:pt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=pt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Ot(s);let a=await Yl.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:pt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Zl.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 fm.generateKeyPair(),r=await fm.sign(t.randomBytes(32),e.privateJwk);return _e.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 xn.digest(e);return(await Nt.createV1(Wd,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 $w.create(),r=await $w.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await wn.generateKey(),c={publicJwk:await wn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};v();Vt();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 mv(r)}}};export{cg as AllowAllTenantGate,Bf as BlockstoreLevel,Rr as Cid,KE as ContentEncryptionAlgorithm,ag as CoreProtocolRegistry,BA as DataStoreLevel,ns as DataStream,$p as DateSort,xA as Dwn,Co as DwnConstant,re as DwnError,dt as DwnErrorCode,Ht as DwnInterfaceName,ir as DwnMethodName,_e as Encoder,ya as Encryption,qA as EventEmitterEventLog,Ha as HdKey,rm as IndexLevel,pt as Jws,v3 as KeyAgreementAlgorithm,Lp as KeyDerivationScheme,Ra as LevelWrapper,ge as Message,KA as MessageStoreLevel,Zl as MessagesRead,Yl as MessagesSubscribe,lg as MessagesSync,zE as PERMISSIONS_REVOCATION_PATH,P3 as PermissionConditionPublication,Qr as PermissionGrant,dg as PermissionRequest,kr as PermissionsProtocol,VA as Poller,Ud as PrivateKeySigner,cm as ProtocolRecordLimitStrategy,iI as Protocols,fd as ProtocolsConfigure,hf as ProtocolsQuery,ke as Records,Hl as RecordsCount,pd as RecordsDelete,Jl as RecordsQuery,Wg as RecordsRead,mf as RecordsSubscribe,gt as RecordsWrite,zA as ResumableTaskStoreLevel,Fw as SMTStoreLevel,GA as SMTStoreMemory,vi as SMT_DEPTH,Oa as Secp256k1,Nd as Secp256r1,Ja as SortDirection,Gw as SparseMerkleTree,FA as StateIndexLevel,WA as TestDataGenerator,yt as Time,i_ as ZERO_HASH,cn as authenticate,Ki as createLevelDatabase,Nn as executeUnlessAborted,co as getBit,vM as getDefaultHashes,ld as getRuleSetAtPath,wu as hashChildren,tn as hashEquals,Xl as hashKey,ug as hashLeaf,Zn as hashToHex,ef as hexToHash,ph as initDefaultHashes,pf as isCrossProtocolRef,Bi as parseCrossProtocolRef};
|
|
11
11
|
/*! Bundled license information:
|
|
12
12
|
|
|
13
13
|
ieee754/index.js:
|