web-dc-api 0.0.70 → 0.0.71

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/dc.min.js CHANGED
@@ -4,4 +4,4 @@
4
4
  || ${c} === "boolean" || ${o} === null`).assign(u,n._`[${o}]`)}}i.else(),d(e),i.endIf(),i.if(n._`${u} !== undefined`,(()=>{i.assign(o,u),function(e,t){let{gen:r,parentData:i,parentDataProperty:o}=e;r.if(n._`${i} !== undefined`,(()=>r.assign(n._`${i}[${o}]`,t)))}(e,u)}))}(e,r,u):d(e)}))}return h};const a=new Set(["string","number","integer","boolean","null"]);function c(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:o.Correct;const s=i===o.Correct?n.operators.EQ:n.operators.NEQ;let a;switch(e){case"null":return n._`${t} ${s} null`;case"array":a=n._`Array.isArray(${t})`;break;case"object":a=n._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":a=c(n._`!(${t} % 1) && !isNaN(${t})`);break;case"number":a=c();break;default:return n._`typeof ${t} ${s} ${e}`}return i===o.Correct?a:(0,n.not)(a);function c(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.nil;return(0,n.and)(n._`typeof ${t} == "number"`,e,r?n._`isFinite(${t})`:n.nil)}}function l(e,t,r,o){if(1===e.length)return c(e[0],t,r,o);let s;const a=(0,i.toHash)(e);if(a.array&&a.object){const e=n._`typeof ${t} != "object"`;s=a.null?e:n._`!${t} || ${e}`,delete a.null,delete a.array,delete a.object}else s=n.nil;a.number&&delete a.integer;for(const e in a)s=(0,n.and)(s,c(e,t,r,o));return s}dataType.checkDataType=c,dataType.checkDataTypes=l;const u={message:e=>{let{schema:t}=e;return`must be ${t}`},params:e=>{let{schema:t,schemaValue:r}=e;return"string"==typeof t?n._`{type: ${t}}`:n._`{type: ${r}}`}};function d(e){const t=function(e){const{gen:t,data:r,schema:n}=e,o=(0,i.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}(e);(0,r.reportError)(t,u)}return dataType.reportTypeError=d,dataType}var defaults={},hasRequiredDefaults;function requireDefaults(){if(hasRequiredDefaults)return defaults;hasRequiredDefaults=1,Object.defineProperty(defaults,"__esModule",{value:!0}),defaults.assignDefaults=void 0;const e=requireCodegen(),t=requireUtil$2();function r(r,n,i){const{gen:o,compositeRule:s,data:a,opts:c}=r;if(void 0===i)return;const l=e._`${a}${(0,e.getProperty)(n)}`;if(s)return void(0,t.checkStrictMode)(r,`default is ignored for: ${l}`);let u=e._`${l} === undefined`;"empty"===c.useDefaults&&(u=e._`${u} || ${l} === null || ${l} === ""`),o.if(u,e._`${l} = ${(0,e.stringify)(i)}`)}return defaults.assignDefaults=function(e,t){const{properties:n,items:i}=e.schema;if("object"===t&&n)for(const t in n)r(e,t,n[t].default);else"array"===t&&Array.isArray(i)&&i.forEach(((t,n)=>r(e,n,t.default)))},defaults}var keyword={},code={},hasRequiredCode,hasRequiredKeyword;function requireCode(){if(hasRequiredCode)return code;hasRequiredCode=1,Object.defineProperty(code,"__esModule",{value:!0}),code.validateUnion=code.validateArray=code.usePattern=code.callValidateCode=code.schemaProperties=code.allSchemaProperties=code.noPropertyInData=code.propertyInData=code.isOwnProperty=code.hasPropFunc=code.reportMissingProp=code.checkMissingProp=code.checkReportMissingProp=void 0;const e=requireCodegen(),t=requireUtil$2(),r=requireNames(),n=requireUtil$2();function i(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function o(t,r,n){return e._`${i(t)}.call(${r}, ${n})`}function s(t,r,n,i){const s=e._`${r}${(0,e.getProperty)(n)} === undefined`;return i?(0,e.or)(s,(0,e.not)(o(t,r,n))):s}function a(e){return e?Object.keys(e).filter((e=>"__proto__"!==e)):[]}code.checkReportMissingProp=function(t,r){const{gen:n,data:i,it:o}=t;n.if(s(n,i,r,o.opts.ownProperties),(()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()}))},code.checkMissingProp=function(t,r,n){let{gen:i,data:o,it:{opts:a}}=t;return(0,e.or)(...r.map((t=>(0,e.and)(s(i,o,t,a.ownProperties),e._`${n} = ${t}`))))},code.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},code.hasPropFunc=i,code.isOwnProperty=o,code.propertyInData=function(t,r,n,i){const s=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return i?e._`${s} && ${o(t,r,n)}`:s},code.noPropertyInData=s,code.allSchemaProperties=a,code.schemaProperties=function(e,r){return a(r).filter((n=>!(0,t.alwaysValidSchema)(e,r[n])))},code.callValidateCode=function(t,n,i,o){let{schemaCode:s,data:a,it:{gen:c,topSchemaRef:l,schemaPath:u,errorPath:d},it:h}=t;const p=o?e._`${s}, ${a}, ${l}${u}`:a,f=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,d)],[r.default.parentData,h.parentData],[r.default.parentDataProperty,h.parentDataProperty],[r.default.rootData,r.default.rootData]];h.opts.dynamicRef&&f.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const y=e._`${p}, ${c.object(...f)}`;return i!==e.nil?e._`${n}.call(${i}, ${y})`:e._`${n}(${y})`};const c=e._`new RegExp`;return code.usePattern=function(t,r){let{gen:i,it:{opts:o}}=t;const s=o.unicodeRegExp?"u":"",{regExp:a}=o.code,l=a(r,s);return i.scopeValue("pattern",{key:l.toString(),ref:l,code:e._`${"new RegExp"===a.code?c:(0,n.useFunc)(i,a)}(${r}, ${s})`})},code.validateArray=function(r){const{gen:n,data:i,keyword:o,it:s}=r,a=n.name("valid");if(s.allErrors){const e=n.let("valid",!0);return c((()=>n.assign(e,!1))),e}return n.var(a,!0),c((()=>n.break())),a;function c(s){const c=n.const("len",e._`${i}.length`);n.forRange("i",0,c,(i=>{r.subschema({keyword:o,dataProp:i,dataPropType:t.Type.Num},a),n.if((0,e.not)(a),s)}))}},code.validateUnion=function(r){const{gen:n,schema:i,keyword:o,it:s}=r;if(!Array.isArray(i))throw new Error("ajv implementation error");if(i.some((e=>(0,t.alwaysValidSchema)(s,e)))&&!s.opts.unevaluated)return;const a=n.let("valid",!1),c=n.name("_valid");n.block((()=>i.forEach(((t,i)=>{const s=r.subschema({keyword:o,schemaProp:i,compositeRule:!0},c);n.assign(a,e._`${a} || ${c}`);r.mergeValidEvaluated(s,c)||n.if((0,e.not)(a))})))),r.result(a,(()=>r.reset()),(()=>r.error(!0)))},code}function requireKeyword(){if(hasRequiredKeyword)return keyword;hasRequiredKeyword=1,Object.defineProperty(keyword,"__esModule",{value:!0}),keyword.validateKeywordUsage=keyword.validSchemaType=keyword.funcKeywordCode=keyword.macroKeywordCode=void 0;const e=requireCodegen(),t=requireNames(),r=requireCode(),n=requireErrors();function i(t){const{gen:r,data:n,it:i}=t;r.if(i.parentData,(()=>r.assign(n,e._`${i.parentData}[${i.parentDataProperty}]`)))}function o(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return keyword.macroKeywordCode=function(t,r){const{gen:n,keyword:i,schema:s,parentSchema:a,it:c}=t,l=r.macro.call(c.self,s,a,c),u=o(n,i,l);!1!==c.opts.validateSchema&&c.self.validateSchema(l,!0);const d=n.name("valid");t.subschema({schema:l,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${i}`,topSchemaRef:u,compositeRule:!0},d),t.pass(d,(()=>t.error(!0)))},keyword.funcKeywordCode=function(s,a){var c;const{gen:l,keyword:u,schema:d,parentSchema:h,$data:p,it:f}=s;!function(e,t){let{schemaEnv:r}=e;if(t.async&&!r.$async)throw new Error("async keyword in sync schema")}(f,a);const y=!p&&a.compile?a.compile.call(f.self,d,h,f):a.validate,g=o(l,u,y),b=l.let("valid");function m(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a.async?e._`await `:e.nil;const i=f.opts.passContext?t.default.this:t.default.self,o=!("compile"in a&&!p||!1===a.schema);l.assign(b,e._`${n}${(0,r.callValidateCode)(s,g,i,o)}`,a.modifying)}function w(t){var r;l.if((0,e.not)(null!==(r=a.valid)&&void 0!==r?r:b),t)}s.block$data(b,(function(){if(!1===a.errors)m(),a.modifying&&i(s),w((()=>s.error()));else{const r=a.async?function(){const t=l.let("ruleErrs",null);return l.try((()=>m(e._`await `)),(r=>l.assign(b,!1).if(e._`${r} instanceof ${f.ValidationError}`,(()=>l.assign(t,e._`${r}.errors`)),(()=>l.throw(r))))),t}():function(){const t=e._`${g}.errors`;return l.assign(t,null),m(e.nil),t}();a.modifying&&i(s),w((()=>function(r,i){const{gen:o}=r;o.if(e._`Array.isArray(${i})`,(()=>{o.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${i} : ${t.default.vErrors}.concat(${i})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)}),(()=>r.error()))}(s,r)))}})),s.ok(null!==(c=a.valid)&&void 0!==c?c:b)},keyword.validSchemaType=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return!t.length||t.some((t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e))},keyword.validateKeywordUsage=function(e,t,r){let{schema:n,opts:i,self:o,errSchemaPath:s}=e;if(Array.isArray(t.keyword)?!t.keyword.includes(r):t.keyword!==r)throw new Error("ajv implementation error");const a=t.dependencies;if(null==a?void 0:a.some((e=>!Object.prototype.hasOwnProperty.call(n,e))))throw new Error(`parent schema must have dependencies of ${r}: ${a.join(",")}`);if(t.validateSchema){if(!t.validateSchema(n[r])){const e=`keyword "${r}" value is invalid at path "${s}": `+o.errorsText(t.validateSchema.errors);if("log"!==i.validateSchema)throw new Error(e);o.logger.error(e)}}},keyword}var subschema={},hasRequiredSubschema;function requireSubschema(){if(hasRequiredSubschema)return subschema;hasRequiredSubschema=1,Object.defineProperty(subschema,"__esModule",{value:!0}),subschema.extendSubschemaMode=subschema.extendSubschemaData=subschema.getSubschema=void 0;const e=requireCodegen(),t=requireUtil$2();return subschema.getSubschema=function(r,n){let{keyword:i,schemaProp:o,schema:s,schemaPath:a,errSchemaPath:c,topSchemaRef:l}=n;if(void 0!==i&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==i){const n=r.schema[i];return void 0===o?{schema:n,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${r.errSchemaPath}/${i}`}:{schema:n[o],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${i}/${(0,t.escapeFragment)(o)}`}}if(void 0!==s){if(void 0===a||void 0===c||void 0===l)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:l,errSchemaPath:c}}throw new Error('either "keyword" or "schema" must be passed')},subschema.extendSubschemaData=function(r,n,i){let{dataProp:o,dataPropType:s,data:a,dataTypes:c,propertyName:l}=i;if(void 0!==a&&void 0!==o)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=n;if(void 0!==o){const{errorPath:i,dataPathArr:a,opts:c}=n;d(u.let("data",e._`${n.data}${(0,e.getProperty)(o)}`,!0)),r.errorPath=e.str`${i}${(0,t.getErrorPath)(o,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${o}`,r.dataPathArr=[...a,r.parentDataProperty]}if(void 0!==a){d(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==l&&(r.propertyName=l)}function d(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}c&&(r.dataTypes=c)},subschema.extendSubschemaMode=function(e,t){let{jtdDiscriminator:r,jtdMetadata:n,compositeRule:i,createErrors:o,allErrors:s}=t;void 0!==i&&(e.compositeRule=i),void 0!==o&&(e.createErrors=o),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=r,e.jtdMetadata=n},subschema}var resolve={},fastDeepEqual,hasRequiredFastDeepEqual;function requireFastDeepEqual(){return hasRequiredFastDeepEqual||(hasRequiredFastDeepEqual=1,fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;0!==i--;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r}),fastDeepEqual}var jsonSchemaTraverse={exports:{}},hasRequiredJsonSchemaTraverse,hasRequiredResolve,hasRequiredValidate;function requireJsonSchemaTraverse(){if(hasRequiredJsonSchemaTraverse)return jsonSchemaTraverse.exports;hasRequiredJsonSchemaTraverse=1;var e=jsonSchemaTraverse.exports=function(e,r,n){"function"==typeof r&&(n=r,r={}),t(r,"function"==typeof(n=r.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function t(r,n,i,o,s,a,c,l,u,d){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var h in n(o,s,a,c,l,u,d),o){var p=o[h];if(Array.isArray(p)){if(h in e.arrayKeywords)for(var f=0;f<p.length;f++)t(r,n,i,p[f],s+"/"+h+"/"+f,a,s,h,o,f)}else if(h in e.propsKeywords){if(p&&"object"==typeof p)for(var y in p)t(r,n,i,p[y],s+"/"+h+"/"+y.replace(/~/g,"~0").replace(/\//g,"~1"),a,s,h,o,y)}else(h in e.keywords||r.allKeys&&!(h in e.skipKeywords))&&t(r,n,i,p,s+"/"+h,a,s,h,o)}i(o,s,a,c,l,u,d)}}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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},jsonSchemaTraverse.exports}function requireResolve(){if(hasRequiredResolve)return resolve;hasRequiredResolve=1,Object.defineProperty(resolve,"__esModule",{value:!0}),resolve.getSchemaRefs=resolve.resolveUrl=resolve.normalizeId=resolve._getFullPath=resolve.getFullPath=resolve.inlineRef=void 0;const e=requireUtil$2(),t=requireFastDeepEqual(),r=requireJsonSchemaTraverse(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);resolve.inlineRef=function(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return"boolean"==typeof e||(!0===t?!o(e):!!t&&s(e)<=t)};const i=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function o(e){for(const t in e){if(i.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(o))return!0;if("object"==typeof r&&o(r))return!0}return!1}function s(t){let r=0;for(const i in t){if("$ref"===i)return 1/0;if(r++,!n.has(i)&&("object"==typeof t[i]&&(0,e.eachItem)(t[i],(e=>r+=s(e))),r===1/0))return 1/0}return r}function a(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";!1!==(arguments.length>2?arguments[2]:void 0)&&(t=u(t));const r=e.parse(t);return c(e,r)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}resolve.getFullPath=a,resolve._getFullPath=c;const l=/#\/?$/;function u(e){return e?e.replace(l,""):""}resolve.normalizeId=u,resolve.resolveUrl=function(e,t,r){return r=u(r),e.resolve(t,r)};const d=/^[a-z_][-a-z0-9._]*$/i;return resolve.getSchemaRefs=function(e,n){if("boolean"==typeof e)return{};const{schemaId:i,uriResolver:o}=this.opts,s=u(e[i]||n),c={"":s},l=a(o,s,!1),h={},p=new Set;return r(e,{allKeys:!0},((e,t,r,n)=>{if(void 0===n)return;const o=l+t;let s=c[n];function a(t){const r=this.opts.uriResolver.resolve;if(t=u(s?r(s,t):t),p.has(t))throw y(t);p.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?f(e,n.schema,t):t!==u(o)&&("#"===t[0]?(f(e,h[t],t),h[t]=e):this.refs[t]=o),t}function g(e){if("string"==typeof e){if(!d.test(e))throw new Error(`invalid anchor "${e}"`);a.call(this,`#${e}`)}}"string"==typeof e[i]&&(s=a.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=s})),h;function f(e,r,n){if(void 0!==r&&!t(e,r))throw y(n)}function y(e){return new Error(`reference "${e}" resolves to more than one schema`)}},resolve}function requireValidate(){if(hasRequiredValidate)return validate;hasRequiredValidate=1,Object.defineProperty(validate,"__esModule",{value:!0}),validate.getData=validate.KeywordCxt=validate.validateFunctionCode=void 0;const e=requireBoolSchema(),t=requireDataType(),r=requireApplicability(),n=requireDataType(),i=requireDefaults(),o=requireKeyword(),s=requireSubschema(),a=requireCodegen(),c=requireNames(),l=requireResolve(),u=requireUtil$2(),d=requireErrors();function h(e,t){let{gen:r,validateName:n,schema:i,schemaEnv:o,opts:s}=e;s.code.es5?r.func(n,a._`${c.default.data}, ${c.default.valCxt}`,o.$async,(()=>{r.code(a._`"use strict"; ${p(i,s)}`),function(e,t){e.if(c.default.valCxt,(()=>{e.var(c.default.instancePath,a._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,a._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,a._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,a._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,a._`${c.default.valCxt}.${c.default.dynamicAnchors}`)}),(()=>{e.var(c.default.instancePath,a._`""`),e.var(c.default.parentData,a._`undefined`),e.var(c.default.parentDataProperty,a._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,a._`{}`)}))}(r,s),r.code(t)})):r.func(n,a._`${c.default.data}, ${function(e){return a._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?a._`, ${c.default.dynamicAnchors}={}`:a.nil}}={}`}(s)}`,o.$async,(()=>r.code(p(i,s)).code(t)))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?a._`/*# sourceURL=${r} */`:a.nil}function f(t,r){g(t)&&(b(t),y(t))?function(e,t){const{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&w(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,l.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const o=n.const("_errs",c.default.errors);m(e,o),n.var(t,a._`${o} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function y(e){let{schema:t,self:r}=e;if("boolean"==typeof t)return!t;for(const e in t)if(r.RULES.all[e])return!0;return!1}function g(e){return"boolean"!=typeof e.schema}function b(e){(0,u.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function m(e,r){if(e.opts.jtd)return v(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);v(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function w(e){let{gen:t,schemaEnv:r,schema:n,errSchemaPath:i,opts:o}=e;const s=n.$comment;if(!0===o.$comment)t.code(a._`${c.default.self}.logger.log(${s})`);else if("function"==typeof o.$comment){const e=a.str`${i}/$comment`,n=t.scopeValue("root",{ref:r.root});t.code(a._`${c.default.self}.opts.$comment(${s}, ${e}, ${n}.schema)`)}}function v(e,t,i,o){const{gen:s,schema:l,data:d,allErrors:h,opts:p,self:f}=e,{RULES:y}=f;function g(u){(0,r.shouldUseGroup)(l,u)&&(u.type?(s.if((0,n.checkDataType)(u.type,d,p.strictNumbers)),S(e,u),1===t.length&&t[0]===u.type&&i&&(s.else(),(0,n.reportTypeError)(e)),s.endIf()):S(e,u),h||s.if(a._`${c.default.errors} === ${o||0}`))}!l.$ref||!p.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(l,y)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach((t=>{x(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)})),function(e,t){const r=[];for(const n of e.dataTypes)x(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const i in n){const o=n[i];if("object"==typeof o&&(0,r.shouldUseRule)(e.schema,o)){const{type:r}=o.definition;r.length&&!r.some((e=>$(t,e)))&&E(e,`missing type "${r.join(",")}" for keyword "${i}"`)}}}(e,e.dataTypes)}(e,t),s.block((()=>{for(const e of y.rules)g(e);g(y.post)}))):s.block((()=>P(e,"$ref",y.all.$ref.definition)))}function S(e,t){const{gen:n,schema:o,opts:{useDefaults:s}}=e;s&&(0,i.assignDefaults)(e,t.type),n.block((()=>{for(const n of t.rules)(0,r.shouldUseRule)(o,n)&&P(e,n.keyword,n.definition,t.type)}))}function $(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function x(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,u.checkStrictMode)(e,t,e.opts.strictTypes)}validate.validateFunctionCode=function(t){g(t)&&(b(t),y(t))?function(e){const{schema:t,opts:r,gen:n}=e;h(e,(()=>{r.$comment&&t.$comment&&w(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,u.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",a._`${r}.evaluated`),t.if(a._`${e.evaluated}.dynamicProps`,(()=>t.assign(a._`${e.evaluated}.props`,a._`undefined`))),t.if(a._`${e.evaluated}.dynamicItems`,(()=>t.assign(a._`${e.evaluated}.items`,a._`undefined`)))}(e),m(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if(a._`${c.default.errors} === 0`,(()=>t.return(c.default.data)),(()=>t.throw(a._`new ${i}(${c.default.vErrors})`))):(t.assign(a._`${n}.errors`,c.default.vErrors),o.unevaluated&&function(e){let{gen:t,evaluated:r,props:n,items:i}=e;n instanceof a.Name&&t.assign(a._`${r}.props`,n);i instanceof a.Name&&t.assign(a._`${r}.items`,i)}(e),t.return(a._`${c.default.errors} === 0`))}(e)}))}(t):h(t,(()=>(0,e.topBoolOrEmptySchema)(t)))};class A{constructor(e,t,r){if((0,o.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",T(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,a.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,a.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(a._`${t} !== undefined && (${(0,a.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:a.nil;this.gen.block((()=>{this.check$data(e,r),t()}))}check$data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a.nil,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a.nil;if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:i,def:o}=this;r.if((0,a.or)(a._`${n} === undefined`,t)),e!==a.nil&&r.assign(e,!0),(i.length||o.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==a.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:i,it:o}=this;return(0,a.or)(function(){if(r.length){if(!(t instanceof a.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return a._`${(0,n.checkDataTypes)(e,t,o.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}(),function(){if(i.validateSchema){const r=e.scopeValue("validate$data",{ref:i.validateSchema});return a._`!${r}(${t})`}return a.nil}())}subschema(e,t){const r=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(r,this.it,e),(0,s.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return f(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=u.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=u.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,(()=>this.mergeEvaluated(e,a.Name))),!0}}function P(e,t,r,n){const i=new A(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,o.funcKeywordCode)(i,r):"macro"in r?(0,o.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,o.funcKeywordCode)(i,r)}validate.KeywordCxt=A;const k=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function T(e,t){let r,n,{dataLevel:i,dataNames:o,dataPathArr:s}=t;if(""===e)return c.default.rootData;if("/"===e[0]){if(!k.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,n=c.default.rootData}else{const t=I.exec(e);if(!t)throw new Error(`Invalid JSON-pointer: ${e}`);const a=+t[1];if(r=t[2],"#"===r){if(a>=i)throw new Error(h("property/index",a));return s[i-a]}if(a>i)throw new Error(h("data",a));if(n=o[i-a],!r)return n}let l=n;const d=r.split("/");for(const e of d)e&&(n=a._`${n}${(0,a.getProperty)((0,u.unescapeJsonPointer)(e))}`,l=a._`${l} && ${n}`);return l;function h(e,t){return`Cannot access ${e} ${t} levels up, current level is ${i}`}}return validate.getData=T,validate}var validation_error={},hasRequiredValidation_error;function requireValidation_error(){if(hasRequiredValidation_error)return validation_error;hasRequiredValidation_error=1,Object.defineProperty(validation_error,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return validation_error.default=e,validation_error}var ref_error={},hasRequiredRef_error;function requireRef_error(){if(hasRequiredRef_error)return ref_error;hasRequiredRef_error=1,Object.defineProperty(ref_error,"__esModule",{value:!0});const e=requireResolve();class t extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,n),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return ref_error.default=t,ref_error}var compile={},hasRequiredCompile;function requireCompile(){if(hasRequiredCompile)return compile;hasRequiredCompile=1,Object.defineProperty(compile,"__esModule",{value:!0}),compile.resolveSchema=compile.getCompilingSchema=compile.resolveRef=compile.compileSchema=compile.SchemaEnv=void 0;const e=requireCodegen(),t=requireValidation_error(),r=requireNames(),n=requireResolve(),i=requireUtil$2(),o=requireValidate();class s{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,n.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function a(i){const s=l.call(this,i);if(s)return s;const a=(0,n.getFullPath)(this.opts.uriResolver,i.root.baseId),{es5:c,lines:u}=this.opts.code,{ownProperties:d}=this.opts,h=new e.CodeGen(this.scope,{es5:c,lines:u,ownProperties:d});let p;i.$async&&(p=h.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const f=h.scopeName("validate");i.validateName=f;const y={gen:h,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:i.schema,code:(0,e.stringify)(i.schema)}:{ref:i.schema}),validateName:f,ValidationError:p,schema:i.schema,schemaEnv:i,rootId:a,baseId:i.baseId||a,schemaPath:e.nil,errSchemaPath:i.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(i),(0,o.validateFunctionCode)(y),h.optimize(this.opts.code.optimize);const t=h.toString();g=`${h.scopeRefs(r.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,i));const n=new Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(f,{ref:n}),n.errors=null,n.schema=i.schema,n.schemaEnv=i,i.$async&&(n.$async=!0),!0===this.opts.code.source&&(n.source={validateName:f,validateCode:t,scopeValues:h._values}),this.opts.unevaluated){const{props:t,items:r}=y;n.evaluated={props:t instanceof e.Name?void 0:t,items:r instanceof e.Name?void 0:r,dynamicProps:t instanceof e.Name,dynamicItems:r instanceof e.Name},n.source&&(n.source.evaluated=(0,e.stringify)(n.evaluated))}return i.validate=n,i}catch(e){throw delete i.validate,delete i.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(i)}}function c(e){return(0,n.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:a.call(this,e)}function l(e){for(const t of this._compilations)if(u(t,e))return t}function u(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function d(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||h.call(this,e,t)}function h(e,t){const r=this.opts.uriResolver.parse(t),i=(0,n._getFullPath)(this.opts.uriResolver,r);let o=(0,n.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===o)return f.call(this,r,e);const c=(0,n.normalizeId)(i),l=this.refs[c]||this.schemas[c];if("string"==typeof l){const t=h.call(this,e,l);if("object"!=typeof(null==t?void 0:t.schema))return;return f.call(this,r,t)}if("object"==typeof(null==l?void 0:l.schema)){if(l.validate||a.call(this,l),c===(0,n.normalizeId)(t)){const{schema:t}=l,{schemaId:r}=this.opts,i=t[r];return i&&(o=(0,n.resolveUrl)(this.opts.uriResolver,o,i)),new s({schema:t,schemaId:r,root:e,baseId:o})}return f.call(this,r,l)}}compile.SchemaEnv=s,compile.compileSchema=a,compile.resolveRef=function(e,t,r){var i;r=(0,n.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let a=d.call(this,e,r);if(void 0===a){const n=null===(i=e.localRefs)||void 0===i?void 0:i[r],{schemaId:o}=this.opts;n&&(a=new s({schema:n,schemaId:o,root:e,baseId:t}))}return void 0!==a?e.refs[r]=c.call(this,a):void 0},compile.getCompilingSchema=l,compile.resolveSchema=h;const p=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function f(e,t){let{baseId:r,schema:o,root:a}=t;var c;if("/"!==(null===(c=e.fragment)||void 0===c?void 0:c[0]))return;for(const t of e.fragment.slice(1).split("/")){if("boolean"==typeof o)return;const e=o[(0,i.unescapeFragment)(t)];if(void 0===e)return;o=e;const s="object"==typeof o&&o[this.opts.schemaId];!p.has(t)&&s&&(r=(0,n.resolveUrl)(this.opts.uriResolver,r,s))}let l;if("boolean"!=typeof o&&o.$ref&&!(0,i.schemaHasRulesButRef)(o,this.RULES)){const e=(0,n.resolveUrl)(this.opts.uriResolver,r,o.$ref);l=h.call(this,a,e)}const{schemaId:u}=this.opts;return l=l||new s({schema:o,schemaId:u,root:a,baseId:r}),l.schema!==l.root.schema?l:void 0}return compile}var $id$1="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description="Meta-schema for $data reference (JSON AnySchema extension proposal)",type$2="object",required$1=["$data"],properties$2={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties$1=!1,require$$9={$id:$id$1,description:description,type:type$2,required:required$1,properties:properties$2,additionalProperties:additionalProperties$1},uri$1={},fastUri={exports:{}},scopedChars,hasRequiredScopedChars,utils,hasRequiredUtils,schemes,hasRequiredSchemes,hasRequiredFastUri,hasRequiredUri$1,hasRequiredCore$1;function requireScopedChars(){if(hasRequiredScopedChars)return scopedChars;hasRequiredScopedChars=1;return scopedChars={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}}function requireUtils(){if(hasRequiredUtils)return utils;hasRequiredUtils=1;const{HEX:e}=requireScopedChars(),t=/^(?:(?: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 r(e){if(s(e,".")<3)return{host:e,isIPV4:!1};const r=e.match(t)||[],[n]=r;return n?{host:o(n,"."),isIPV4:!0}:{host:e,isIPV4:!1}}function n(t){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n="",i=!0;for(const r of t){if(void 0===e[r])return;"0"!==r&&!0===i&&(i=!1),i||(n+=r)}return r&&0===n.length&&(n="0"),n}function i(e){if(s(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},i=[],o=[];let s=!1,a=!1,c=!1;function l(){if(o.length){if(!1===s){const e=n(o);if(void 0===e)return r.error=!0,!1;i.push(e)}o.length=0}return!0}for(let n=0;n<e.length;n++){const u=e[n];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!l())break;s=!0}else o.push(u);else{if(!0===a&&(c=!0),!l())break;if(t++,i.push(":"),t>7){r.error=!0;break}n-1>=0&&":"===e[n-1]&&(a=!0)}}return o.length&&(s?r.zone=o.join(""):c?i.push(o.join("")):i.push(n(o))),r.address=i.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,escapedHost:r,isIPV6:!0}}}function o(e,t){let r="",n=!0;const i=e.length;for(let o=0;o<i;o++){const s=e[o];"0"===s&&n?(o+1<=i&&e[o+1]===t||o+1===i)&&(r+=s,n=!1):(n=s===t,r+=s)}return r}function s(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}const a=/^\.\.?\//u,c=/^\/\.(?:\/|$)/u,l=/^\/\.\.(?:\/|$)/u,u=/^\/?(?:.|\n)*?(?=\/|$)/u;return utils={recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let n=unescape(e.host);const o=r(n);if(o.isIPV4)n=o.host;else{const t=i(o.host);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){const t=[];for(;e.length;)if(e.match(a))e=e.replace(a,"");else if(e.match(c))e=e.replace(c,"/");else if(e.match(l))e=e.replace(l,"/"),t.pop();else if("."===e||".."===e)e="";else{const r=e.match(u);if(!r)throw new Error("Unexpected dot segment condition");{const n=r[0];e=e.slice(n.length),t.push(n)}}return t.join("")},normalizeIPv4:r,normalizeIPv6:i,stringArrayToHexStripped:n},utils}function requireSchemes(){if(hasRequiredSchemes)return schemes;hasRequiredSchemes=1;const e=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function r(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function n(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function i(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const o={scheme:"http",domainHost:!0,parse:n,serialize:i},s={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=r(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(r(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},a={scheme:"urn",parse:function(e,r){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(t);if(n){const t=r.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const i=`${t}:${r.nid||e.nid}`,o=l[i];e.path=void 0,o&&(e=o.parse(e,r))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=l[i];o&&(e=o.serialize(e,t));const s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s},skipNormalize:!0},c={scheme:"urn:uuid",parse:function(t,r){const n=t;return n.uuid=n.nss,n.nss=void 0,r.tolerant||n.uuid&&e.test(n.uuid)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0},l={http:o,https:{scheme:"https",domainHost:o.domainHost,parse:n,serialize:i},ws:s,wss:{scheme:"wss",domainHost:s.domainHost,parse:s.parse,serialize:s.serialize},urn:a,"urn:uuid":c};return schemes=l}function requireFastUri(){if(hasRequiredFastUri)return fastUri.exports;hasRequiredFastUri=1;const{normalizeIPv6:e,normalizeIPv4:t,removeDotSegments:r,recomposeAuthority:n,normalizeComponentEncoding:i}=requireUtils(),o=requireSchemes();function s(e,t,n,i){const o={};return i||(e=u(a(e,n),n),t=u(a(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||""),o.query=t.query):(t.path?("/"===t.path.charAt(0)?o.path=r(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=r(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function a(e,t){const i={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},s=Object.assign({},t),a=[],c=o[(s.scheme||i.scheme||"").toLowerCase()];c&&c.serialize&&c.serialize(i,s),void 0!==i.path&&(s.skipEscape?i.path=unescape(i.path):(i.path=escape(i.path),void 0!==i.scheme&&(i.path=i.path.split("%3A").join(":")))),"suffix"!==s.reference&&i.scheme&&a.push(i.scheme,":");const l=n(i);if(void 0!==l&&("suffix"!==s.reference&&a.push("//"),a.push(l),i.path&&"/"!==i.path.charAt(0)&&a.push("/")),void 0!==i.path){let e=i.path;s.absolutePath||c&&c.absolutePath||(e=r(e)),void 0===l&&(e=e.replace(/^\/\//u,"/%2F")),a.push(e)}return void 0!==i.query&&a.push("?",i.query),void 0!==i.fragment&&a.push("#",i.fragment),a.join("")}const c=Array.from({length:127},((e,t)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(t))));const l=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function u(r,n){const i=Object.assign({},n),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=-1!==r.indexOf("%");let u=!1;"suffix"===i.reference&&(r=(i.scheme?i.scheme+":":"")+"//"+r);const d=r.match(l);if(d){if(s.scheme=d[1],s.userinfo=d[3],s.host=d[4],s.port=parseInt(d[5],10),s.path=d[6]||"",s.query=d[7],s.fragment=d[8],isNaN(s.port)&&(s.port=d[5]),s.host){const r=t(s.host);if(!1===r.isIPV4){const t=e(r.host);s.host=t.host.toLowerCase(),u=t.isIPV6}else s.host=r.host,u=!0}void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",i.reference&&"suffix"!==i.reference&&i.reference!==s.reference&&(s.error=s.error||"URI is not a "+i.reference+" reference.");const r=o[(i.scheme||s.scheme||"").toLowerCase()];if(!(i.unicodeSupport||r&&r.unicodeSupport)&&s.host&&(i.domainHost||r&&r.domainHost)&&!1===u&&function(e){let t=0;for(let r=0,n=e.length;r<n;++r)if(t=e.charCodeAt(r),t>126||c[t])return!0;return!1}(s.host))try{s.host=URL.domainToASCII(s.host.toLowerCase())}catch(e){s.error=s.error||"Host's domain name can not be converted to ASCII: "+e}(!r||r&&!r.skipNormalize)&&(a&&void 0!==s.scheme&&(s.scheme=unescape(s.scheme)),a&&void 0!==s.host&&(s.host=unescape(s.host)),s.path&&(s.path=escape(unescape(s.path))),s.fragment&&(s.fragment=encodeURI(decodeURIComponent(s.fragment)))),r&&r.parse&&r.parse(s,i)}else s.error=s.error||"URI can not be parsed.";return s}const d={SCHEMES:o,normalize:function(e,t){return"string"==typeof e?e=a(u(e,t),t):"object"==typeof e&&(e=u(a(e,t),t)),e},resolve:function(e,t,r){const n=Object.assign({scheme:"null"},r);return a(s(u(e,n),u(t,n),n,!0),{...n,skipEscape:!0})},resolveComponents:s,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=a(i(u(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=a(i(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=a(i(u(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=a(i(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:a,parse:u};return fastUri.exports=d,fastUri.exports.default=d,fastUri.exports.fastUri=d,fastUri.exports}function requireUri$1(){if(hasRequiredUri$1)return uri$1;hasRequiredUri$1=1,Object.defineProperty(uri$1,"__esModule",{value:!0});const e=requireFastUri();return e.code='require("ajv/dist/runtime/uri").default',uri$1.default=e,uri$1}function requireCore$1(){return hasRequiredCore$1||(hasRequiredCore$1=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=requireValidate();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=requireCodegen();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=requireValidation_error(),i=requireRef_error(),o=requireRules(),s=requireCompile(),a=requireCodegen(),c=requireResolve(),l=requireDataType(),u=requireUtil$2(),d=require$$9,h=requireUri$1(),p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={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."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function m(e){var t,r,n,i,o,s,a,c,l,u,d,f,y,g,b,m,w,v,S,$,x,E,A,P,k;const I=e.strict,T=null===(t=e.code)||void 0===t?void 0:t.optimize,O=!0===T||void 0===T?1:T||0,_=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:p,C=null!==(i=e.uriResolver)&&void 0!==i?i:h.default;return{strictSchema:null===(s=null!==(o=e.strictSchema)&&void 0!==o?o:I)||void 0===s||s,strictNumbers:null===(c=null!==(a=e.strictNumbers)&&void 0!==a?a:I)||void 0===c||c,strictTypes:null!==(u=null!==(l=e.strictTypes)&&void 0!==l?l:I)&&void 0!==u?u:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(g=null!==(y=e.strictRequired)&&void 0!==y?y:I)&&void 0!==g&&g,code:e.code?{...e.code,optimize:O,regExp:_}:{optimize:O,regExp:_},loopRequired:null!==(b=e.loopRequired)&&void 0!==b?b:200,loopEnum:null!==(m=e.loopEnum)&&void 0!==m?m:200,meta:null===(w=e.meta)||void 0===w||w,messages:null===(v=e.messages)||void 0===v||v,inlineRefs:null===(S=e.inlineRefs)||void 0===S||S,schemaId:null!==($=e.schemaId)&&void 0!==$?$:"$id",addUsedSchema:null===(x=e.addUsedSchema)||void 0===x||x,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(A=e.validateFormats)||void 0===A||A,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(k=e.int32range)||void 0===k||k,uriResolver:C}}class w{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...m(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),v.call(this,g,e,"NOT SUPPORTED"),v.call(this,b,e,"DEPRECATED","warn"),this._metaOpts=A.call(this),e.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),$.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=d;"id"===r&&(n={...d},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await o.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||s.call(this,r)}async function o(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function s(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return a.call(this,t),await c.call(this,t.missingSchema),s.call(this,e)}}function a(e){let{missingSchema:t,missingRef:r}=e;if(this.refs[t])throw new Error(`AnySchema ${t} is loaded but ${r} cannot be resolved`)}async function c(e){const r=await l.call(this,e);this.refs[e]||await o.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function l(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r){let n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema;if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,i);return this}if("object"==typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.opts.validateSchema;return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=S.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new s.SchemaEnv({schema:{},schemaId:r});if(t=s.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=S.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,r,t),!t)return(0,u.eachItem)(r,(e=>T.call(this,e))),this;_.call(this,t);const n={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(r,0===n.type.length?e=>T.call(this,e,n):e=>n.type.forEach((t=>T.call(this,e,n,t)))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex((t=>t.keyword===e));t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.errors,{separator:t=", ",dataVar:r="data"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e&&0!==e.length?e.map((e=>`${r}${e.instancePath} ${e.message}`)).reduce(((e,r)=>e+t+r)):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let i=e;for(const e of t)i=i[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,o=i[e];n&&o&&(i[e]=R(o))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r){let n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.opts.addUsedSchema;const{schemaId:a}=this.opts;if("object"==typeof e)n=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(void 0!==l)return l;r=(0,c.normalizeId)(n||r);const u=c.getSchemaRefs.call(this,e,r);return l=new s.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:r,localRefs:u}),this._cache.set(l.schema,l),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),i&&this.validateSchema(e,!0),l}_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):s.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}}function v(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"error";for(const i in e){const o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function S(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function $(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function x(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function A(){const e={...this.opts};for(const t of f)delete e[t];return e}w.ValidationError=n.default,w.MissingRefError=i.default,e.default=w;const P={log(){},warn(){},error(){}};const k=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,u.eachItem)(e,(e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!k.test(e))throw new Error(`Keyword ${e} has invalid name`)})),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function T(e,t,r){var n;const i=null==t?void 0:t.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:o}=this;let s=i?o.post:o.rules.find((e=>{let{type:t}=e;return t===r}));if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[e]=!0,!t)return;const a={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?O.call(this,s,a,t.before):s.rules.push(a),o.all[e]=a,null===(n=t.implements)||void 0===n||n.forEach((e=>this.addKeyword(e)))}function O(e,t,r){const n=e.rules.findIndex((e=>e.keyword===r));n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function _(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const C={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,C]}}}(core$1)),core$1}var draft7={},core={},id={},hasRequiredId;function requireId(){if(hasRequiredId)return id;hasRequiredId=1,Object.defineProperty(id,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return id.default=e,id}var ref$1={},hasRequiredRef$1,hasRequiredCore;function requireRef$1(){if(hasRequiredRef$1)return ref$1;hasRequiredRef$1=1,Object.defineProperty(ref$1,"__esModule",{value:!0}),ref$1.callRef=ref$1.getValidate=void 0;const e=requireRef_error(),t=requireCode(),r=requireCodegen(),n=requireNames(),i=requireCompile(),o=requireUtil$2(),s={keyword:"$ref",schemaType:"string",code(t){const{gen:n,schema:o,it:s}=t,{baseId:l,schemaEnv:u,validateName:d,opts:h,self:p}=s,{root:f}=u;if(("#"===o||"#/"===o)&&l===f.baseId)return function(){if(u===f)return c(t,d,u,u.$async);const e=n.scopeValue("root",{ref:f});return c(t,r._`${e}.validate`,f,f.$async)}();const y=i.resolveRef.call(p,f,l,o);if(void 0===y)throw new e.default(s.opts.uriResolver,l,o);return y instanceof i.SchemaEnv?function(e){const r=a(t,e);c(t,r,e,e.$async)}(y):function(e){const i=n.scopeValue("schema",!0===h.code.source?{ref:e,code:(0,r.stringify)(e)}:{ref:e}),s=n.name("valid"),a=t.subschema({schema:e,dataTypes:[],schemaPath:r.nil,topSchemaRef:i,errSchemaPath:o},s);t.mergeEvaluated(a),t.ok(s)}(y)}};function a(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):r._`${n.scopeValue("wrapper",{ref:t})}.validate`}function c(e,i,s,a){const{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:h}=l,p=h.passContext?n.default.this:r.nil;function f(e){const t=r._`${e}.errors`;c.assign(n.default.vErrors,r._`${n.default.vErrors} === null ? ${t} : ${n.default.vErrors}.concat(${t})`),c.assign(n.default.errors,r._`${n.default.vErrors}.length`)}function y(e){var t;if(!l.opts.unevaluated)return;const n=null===(t=null==s?void 0:s.validate)||void 0===t?void 0:t.evaluated;if(!0!==l.props)if(n&&!n.dynamicProps)void 0!==n.props&&(l.props=o.mergeEvaluated.props(c,n.props,l.props));else{const t=c.var("props",r._`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(!0!==l.items)if(n&&!n.dynamicItems)void 0!==n.items&&(l.items=o.mergeEvaluated.items(c,n.items,l.items));else{const t=c.var("items",r._`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}a?function(){if(!d.$async)throw new Error("async schema referenced by sync schema");const n=c.let("valid");c.try((()=>{c.code(r._`await ${(0,t.callValidateCode)(e,i,p)}`),y(i),u||c.assign(n,!0)}),(e=>{c.if(r._`!(${e} instanceof ${l.ValidationError})`,(()=>c.throw(e))),f(e),u||c.assign(n,!1)})),e.ok(n)}():e.result((0,t.callValidateCode)(e,i,p),(()=>y(i)),(()=>f(i)))}return ref$1.getValidate=a,ref$1.callRef=c,ref$1.default=s,ref$1}function requireCore(){if(hasRequiredCore)return core;hasRequiredCore=1,Object.defineProperty(core,"__esModule",{value:!0});const e=requireId(),t=requireRef$1(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return core.default=r,core}var validation={},limitNumber={},hasRequiredLimitNumber;function requireLimitNumber(){if(hasRequiredLimitNumber)return limitNumber;hasRequiredLimitNumber=1,Object.defineProperty(limitNumber,"__esModule",{value:!0});const e=requireCodegen(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:t=>{let{keyword:n,schemaCode:i}=t;return e.str`must be ${r[n].okStr} ${i}`},params:t=>{let{keyword:n,schemaCode:i}=t;return e._`{comparison: ${r[n].okStr}, limit: ${i}}`}},i={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(t){const{keyword:n,data:i,schemaCode:o}=t;t.fail$data(e._`${i} ${r[n].fail} ${o} || isNaN(${i})`)}};return limitNumber.default=i,limitNumber}var multipleOf={},hasRequiredMultipleOf;function requireMultipleOf(){if(hasRequiredMultipleOf)return multipleOf;hasRequiredMultipleOf=1,Object.defineProperty(multipleOf,"__esModule",{value:!0});const e=requireCodegen(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:t=>{let{schemaCode:r}=t;return e.str`must be multiple of ${r}`},params:t=>{let{schemaCode:r}=t;return e._`{multipleOf: ${r}}`}},code(t){const{gen:r,data:n,schemaCode:i,it:o}=t,s=o.opts.multipleOfPrecision,a=r.let("res"),c=s?e._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:e._`${a} !== parseInt(${a})`;t.fail$data(e._`(${i} === 0 || (${a} = ${n}/${i}, ${c}))`)}};return multipleOf.default=t,multipleOf}var limitLength={},ucs2length={},hasRequiredUcs2length,hasRequiredLimitLength;function requireUcs2length(){if(hasRequiredUcs2length)return ucs2length;function e(e){const t=e.length;let r,n=0,i=0;for(;i<t;)n++,r=e.charCodeAt(i++),r>=55296&&r<=56319&&i<t&&(r=e.charCodeAt(i),56320==(64512&r)&&i++);return n}return hasRequiredUcs2length=1,Object.defineProperty(ucs2length,"__esModule",{value:!0}),ucs2length.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ucs2length}function requireLimitLength(){if(hasRequiredLimitLength)return limitLength;hasRequiredLimitLength=1,Object.defineProperty(limitLength,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r=requireUcs2length(),n={message(t){let{keyword:r,schemaCode:n}=t;const i="maxLength"===r?"more":"fewer";return e.str`must NOT have ${i} than ${n} characters`},params:t=>{let{schemaCode:r}=t;return e._`{limit: ${r}}`}},i={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n,code(n){const{keyword:i,data:o,schemaCode:s,it:a}=n,c="maxLength"===i?e.operators.GT:e.operators.LT,l=!1===a.opts.unicode?e._`${o}.length`:e._`${(0,t.useFunc)(n.gen,r.default)}(${o})`;n.fail$data(e._`${l} ${c} ${s}`)}};return limitLength.default=i,limitLength}var pattern={},hasRequiredPattern;function requirePattern(){if(hasRequiredPattern)return pattern;hasRequiredPattern=1,Object.defineProperty(pattern,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:e=>{let{schemaCode:r}=e;return t.str`must match pattern "${r}"`},params:e=>{let{schemaCode:r}=e;return t._`{pattern: ${r}}`}},code(r){const{data:n,$data:i,schema:o,schemaCode:s,it:a}=r,c=a.opts.unicodeRegExp?"u":"",l=i?t._`(new RegExp(${s}, ${c}))`:(0,e.usePattern)(r,o);r.fail$data(t._`!${l}.test(${n})`)}};return pattern.default=r,pattern}var limitProperties={},hasRequiredLimitProperties;function requireLimitProperties(){if(hasRequiredLimitProperties)return limitProperties;hasRequiredLimitProperties=1,Object.defineProperty(limitProperties,"__esModule",{value:!0});const e=requireCodegen(),t={message(t){let{keyword:r,schemaCode:n}=t;const i="maxProperties"===r?"more":"fewer";return e.str`must NOT have ${i} than ${n} properties`},params:t=>{let{schemaCode:r}=t;return e._`{limit: ${r}}`}},r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:i}=t,o="maxProperties"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${n}).length ${o} ${i}`)}};return limitProperties.default=r,limitProperties}var required={},hasRequiredRequired;function requireRequired(){if(hasRequiredRequired)return required;hasRequiredRequired=1,Object.defineProperty(required,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireUtil$2(),n={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:e=>{let{params:{missingProperty:r}}=e;return t.str`must have required property '${r}'`},params:e=>{let{params:{missingProperty:r}}=e;return t._`{missingProperty: ${r}}`}},code(n){const{gen:i,schema:o,schemaCode:s,data:a,$data:c,it:l}=n,{opts:u}=l;if(!c&&0===o.length)return;const d=o.length>=u.loopRequired;if(l.allErrors?function(){if(d||c)n.block$data(t.nil,h);else for(const t of o)(0,e.checkReportMissingProp)(n,t)}():function(){const r=i.let("missing");if(d||c){const o=i.let("valid",!0);n.block$data(o,(()=>function(r,o){n.setParams({missingProperty:r}),i.forOf(r,s,(()=>{i.assign(o,(0,e.propertyInData)(i,a,r,u.ownProperties)),i.if((0,t.not)(o),(()=>{n.error(),i.break()}))}),t.nil)}(r,o))),n.ok(o)}else i.if((0,e.checkMissingProp)(n,o,r)),(0,e.reportMissingProp)(n,r),i.else()}(),u.strictRequired){const e=n.parentSchema.properties,{definedProperties:t}=n.it;for(const n of o)if(void 0===(null==e?void 0:e[n])&&!t.has(n)){const e=`required property "${n}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,e,l.opts.strictRequired)}}function h(){i.forOf("prop",s,(t=>{n.setParams({missingProperty:t}),i.if((0,e.noPropertyInData)(i,a,t,u.ownProperties),(()=>n.error()))}))}}};return required.default=n,required}var limitItems={},hasRequiredLimitItems;function requireLimitItems(){if(hasRequiredLimitItems)return limitItems;hasRequiredLimitItems=1,Object.defineProperty(limitItems,"__esModule",{value:!0});const e=requireCodegen(),t={message(t){let{keyword:r,schemaCode:n}=t;const i="maxItems"===r?"more":"fewer";return e.str`must NOT have ${i} than ${n} items`},params:t=>{let{schemaCode:r}=t;return e._`{limit: ${r}}`}},r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:i}=t,o="maxItems"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`${n}.length ${o} ${i}`)}};return limitItems.default=r,limitItems}var uniqueItems={},equal={},hasRequiredEqual,hasRequiredUniqueItems;function requireEqual(){if(hasRequiredEqual)return equal;hasRequiredEqual=1,Object.defineProperty(equal,"__esModule",{value:!0});const e=requireFastDeepEqual();return e.code='require("ajv/dist/runtime/equal").default',equal.default=e,equal}function requireUniqueItems(){if(hasRequiredUniqueItems)return uniqueItems;hasRequiredUniqueItems=1,Object.defineProperty(uniqueItems,"__esModule",{value:!0});const e=requireDataType(),t=requireCodegen(),r=requireUtil$2(),n=requireEqual(),i={message:e=>{let{params:{i:r,j:n}}=e;return t.str`must NOT have duplicate items (items ## ${n} and ${r} are identical)`},params:e=>{let{params:{i:r,j:n}}=e;return t._`{i: ${r}, j: ${n}}`}},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:i,code(i){const{gen:o,data:s,$data:a,schema:c,parentSchema:l,schemaCode:u,it:d}=i;if(!a&&!c)return;const h=o.let("valid"),p=l.items?(0,e.getSchemaTypes)(l.items):[];function f(r,n){const a=o.name("item"),c=(0,e.checkDataTypes)(p,a,d.opts.strictNumbers,e.DataType.Wrong),l=o.const("indices",t._`{}`);o.for(t._`;${r}--;`,(()=>{o.let(a,t._`${s}[${r}]`),o.if(c,t._`continue`),p.length>1&&o.if(t._`typeof ${a} == "string"`,t._`${a} += "_"`),o.if(t._`typeof ${l}[${a}] == "number"`,(()=>{o.assign(n,t._`${l}[${a}]`),i.error(),o.assign(h,!1).break()})).code(t._`${l}[${a}] = ${r}`)}))}function y(e,a){const c=(0,r.useFunc)(o,n.default),l=o.name("outer");o.label(l).for(t._`;${e}--;`,(()=>o.for(t._`${a} = ${e}; ${a}--;`,(()=>o.if(t._`${c}(${s}[${e}], ${s}[${a}])`,(()=>{i.error(),o.assign(h,!1).break(l)}))))))}i.block$data(h,(function(){const e=o.let("i",t._`${s}.length`),r=o.let("j");i.setParams({i:e,j:r}),o.assign(h,!0),o.if(t._`${e} > 1`,(()=>(p.length>0&&!p.some((e=>"object"===e||"array"===e))?f:y)(e,r)))}),t._`${u} === false`),i.ok(h)}};return uniqueItems.default=o,uniqueItems}var _const={},hasRequired_const;function require_const(){if(hasRequired_const)return _const;hasRequired_const=1,Object.defineProperty(_const,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r=requireEqual(),n={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:t=>{let{schemaCode:r}=t;return e._`{allowedValue: ${r}}`}},code(n){const{gen:i,data:o,$data:s,schemaCode:a,schema:c}=n;s||c&&"object"==typeof c?n.fail$data(e._`!${(0,t.useFunc)(i,r.default)}(${o}, ${a})`):n.fail(e._`${c} !== ${o}`)}};return _const.default=n,_const}var _enum={},hasRequired_enum,hasRequiredValidation;function require_enum(){if(hasRequired_enum)return _enum;hasRequired_enum=1,Object.defineProperty(_enum,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r=requireEqual(),n={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:t=>{let{schemaCode:r}=t;return e._`{allowedValues: ${r}}`}},code(n){const{gen:i,data:o,$data:s,schema:a,schemaCode:c,it:l}=n;if(!s&&0===a.length)throw new Error("enum must have non-empty array");const u=a.length>=l.opts.loopEnum;let d;const h=()=>null!=d?d:d=(0,t.useFunc)(i,r.default);let p;if(u||s)p=i.let("valid"),n.block$data(p,(function(){i.assign(p,!1),i.forOf("v",c,(t=>i.if(e._`${h()}(${o}, ${t})`,(()=>i.assign(p,!0).break()))))}));else{if(!Array.isArray(a))throw new Error("ajv implementation error");const t=i.const("vSchema",c);p=(0,e.or)(...a.map(((r,n)=>function(t,r){const n=a[r];return"object"==typeof n&&null!==n?e._`${h()}(${o}, ${t}[${r}])`:e._`${o} === ${n}`}(t,n))))}n.pass(p)}};return _enum.default=n,_enum}function requireValidation(){if(hasRequiredValidation)return validation;hasRequiredValidation=1,Object.defineProperty(validation,"__esModule",{value:!0});const e=requireLimitNumber(),t=requireMultipleOf(),r=requireLimitLength(),n=requirePattern(),i=requireLimitProperties(),o=requireRequired(),s=requireLimitItems(),a=requireUniqueItems(),c=require_const(),l=require_enum(),u=[e.default,t.default,r.default,n.default,i.default,o.default,s.default,a.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return validation.default=u,validation}var applicator={},additionalItems={},hasRequiredAdditionalItems;function requireAdditionalItems(){if(hasRequiredAdditionalItems)return additionalItems;hasRequiredAdditionalItems=1,Object.defineProperty(additionalItems,"__esModule",{value:!0}),additionalItems.validateAdditionalItems=void 0;const e=requireCodegen(),t=requireUtil$2(),r={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:t=>{let{params:{len:r}}=t;return e.str`must NOT have more than ${r} items`},params:t=>{let{params:{len:r}}=t;return e._`{limit: ${r}}`}},code(e){const{parentSchema:r,it:i}=e,{items:o}=r;Array.isArray(o)?n(e,o):(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas')}};function n(r,n){const{gen:i,schema:o,data:s,keyword:a,it:c}=r;c.items=!0;const l=i.const("len",e._`${s}.length`);if(!1===o)r.setParams({len:n.length}),r.pass(e._`${l} <= ${n.length}`);else if("object"==typeof o&&!(0,t.alwaysValidSchema)(c,o)){const o=i.var("valid",e._`${l} <= ${n.length}`);i.if((0,e.not)(o),(()=>function(o){i.forRange("i",n.length,l,(n=>{r.subschema({keyword:a,dataProp:n,dataPropType:t.Type.Num},o),c.allErrors||i.if((0,e.not)(o),(()=>i.break()))}))}(o))),r.ok(o)}}return additionalItems.validateAdditionalItems=n,additionalItems.default=r,additionalItems}var prefixItems={},items={},hasRequiredItems,hasRequiredPrefixItems;function requireItems(){if(hasRequiredItems)return items;hasRequiredItems=1,Object.defineProperty(items,"__esModule",{value:!0}),items.validateTuple=void 0;const e=requireCodegen(),t=requireUtil$2(),r=requireCode(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:n,it:o}=e;if(Array.isArray(n))return i(e,"additionalItems",n);o.items=!0,(0,t.alwaysValidSchema)(o,n)||e.ok((0,r.validateArray)(e))}};function i(r,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:r.schema;const{gen:o,parentSchema:s,data:a,keyword:c,it:l}=r;!function(e){const{opts:r,errSchemaPath:o}=l,s=i.length,a=s===e.minItems&&(s===e.maxItems||!1===e[n]);if(r.strictTuples&&!a){const e=`"${c}" is ${s}-tuple, but minItems or maxItems/${n} are not specified or different at path "${o}"`;(0,t.checkStrictMode)(l,e,r.strictTuples)}}(s),l.opts.unevaluated&&i.length&&!0!==l.items&&(l.items=t.mergeEvaluated.items(o,i.length,l.items));const u=o.name("valid"),d=o.const("len",e._`${a}.length`);i.forEach(((n,i)=>{(0,t.alwaysValidSchema)(l,n)||(o.if(e._`${d} > ${i}`,(()=>r.subschema({keyword:c,schemaProp:i,dataProp:i},u))),r.ok(u))}))}return items.validateTuple=i,items.default=n,items}function requirePrefixItems(){if(hasRequiredPrefixItems)return prefixItems;hasRequiredPrefixItems=1,Object.defineProperty(prefixItems,"__esModule",{value:!0});const e=requireItems(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return prefixItems.default=t,prefixItems}var items2020={},hasRequiredItems2020;function requireItems2020(){if(hasRequiredItems2020)return items2020;hasRequiredItems2020=1,Object.defineProperty(items2020,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r=requireCode(),n=requireAdditionalItems(),i={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:t=>{let{params:{len:r}}=t;return e.str`must NOT have more than ${r} items`},params:t=>{let{params:{len:r}}=t;return e._`{limit: ${r}}`}},code(e){const{schema:i,parentSchema:o,it:s}=e,{prefixItems:a}=o;s.items=!0,(0,t.alwaysValidSchema)(s,i)||(a?(0,n.validateAdditionalItems)(e,a):e.ok((0,r.validateArray)(e)))}};return items2020.default=i,items2020}var contains={},hasRequiredContains;function requireContains(){if(hasRequiredContains)return contains;hasRequiredContains=1,Object.defineProperty(contains,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={message:t=>{let{params:{min:r,max:n}}=t;return void 0===n?e.str`must contain at least ${r} valid item(s)`:e.str`must contain at least ${r} and no more than ${n} valid item(s)`},params:t=>{let{params:{min:r,max:n}}=t;return void 0===n?e._`{minContains: ${r}}`:e._`{minContains: ${r}, maxContains: ${n}}`}},n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:r,code(r){const{gen:n,schema:i,parentSchema:o,data:s,it:a}=r;let c,l;const{minContains:u,maxContains:d}=o;a.opts.next?(c=void 0===u?1:u,l=d):c=1;const h=n.const("len",e._`${s}.length`);if(r.setParams({min:c,max:l}),void 0===l&&0===c)return void(0,t.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==l&&c>l)return(0,t.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void r.fail();if((0,t.alwaysValidSchema)(a,i)){let t=e._`${h} >= ${c}`;return void 0!==l&&(t=e._`${t} && ${h} <= ${l}`),void r.pass(t)}a.items=!0;const p=n.name("valid");function f(){const t=n.name("_valid"),r=n.let("count",0);y(t,(()=>n.if(t,(()=>function(t){n.code(e._`${t}++`),void 0===l?n.if(e._`${t} >= ${c}`,(()=>n.assign(p,!0).break())):(n.if(e._`${t} > ${l}`,(()=>n.assign(p,!1).break())),1===c?n.assign(p,!0):n.if(e._`${t} >= ${c}`,(()=>n.assign(p,!0))))}(r)))))}function y(e,i){n.forRange("i",0,h,(n=>{r.subschema({keyword:"contains",dataProp:n,dataPropType:t.Type.Num,compositeRule:!0},e),i()}))}void 0===l&&1===c?y(p,(()=>n.if(p,(()=>n.break())))):0===c?(n.let(p,!0),void 0!==l&&n.if(e._`${s}.length > 0`,f)):(n.let(p,!1),f()),r.result(p,(()=>r.reset()))}};return contains.default=n,contains}var dependencies={},hasRequiredDependencies;function requireDependencies(){return hasRequiredDependencies||(hasRequiredDependencies=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=requireCodegen(),r=requireUtil$2(),n=requireCode();e.error={message:e=>{let{params:{property:r,depsCount:n,deps:i}}=e;const o=1===n?"property":"properties";return t.str`must have ${o} ${i} when property ${r} is present`},params:e=>{let{params:{property:r,depsCount:n,deps:i,missingProperty:o}}=e;return t._`{property: ${r},
5
5
  missingProperty: ${o},
6
6
  depsCount: ${n},
7
- deps: ${i}}`}};const i={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function(e){let{schema:t}=e;const r={},n={};for(const e in t){if("__proto__"===e)continue;(Array.isArray(t[e])?r:n)[e]=t[e]}return[r,n]}(e);o(e,t),s(e,r)}};function o(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:i,data:o,it:s}=e;if(0===Object.keys(r).length)return;const a=i.let("missing");for(const c in r){const l=r[c];if(0===l.length)continue;const u=(0,n.propertyInData)(i,o,c,s.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),s.allErrors?i.if(u,(()=>{for(const t of l)(0,n.checkReportMissingProp)(e,t)})):(i.if(t._`${u} && (${(0,n.checkMissingProp)(e,l,a)})`),(0,n.reportMissingProp)(e,a),i.else())}}function s(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:i,data:o,keyword:s,it:a}=e,c=i.name("valid");for(const l in t)(0,r.alwaysValidSchema)(a,t[l])||(i.if((0,n.propertyInData)(i,o,l,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:s,schemaProp:l},c);e.mergeValidEvaluated(t,c)}),(()=>i.var(c,!0))),e.ok(c))}e.validatePropertyDeps=o,e.validateSchemaDeps=s,e.default=i}(dependencies)),dependencies}var propertyNames={},hasRequiredPropertyNames;function requirePropertyNames(){if(hasRequiredPropertyNames)return propertyNames;hasRequiredPropertyNames=1,Object.defineProperty(propertyNames,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:t=>{let{params:r}=t;return e._`{propertyName: ${r.propertyName}}`}},code(r){const{gen:n,schema:i,data:o,it:s}=r;if((0,t.alwaysValidSchema)(s,i))return;const a=n.name("valid");n.forIn("key",o,(t=>{r.setParams({propertyName:t}),r.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},a),n.if((0,e.not)(a),(()=>{r.error(!0),s.allErrors||n.break()}))})),r.ok(a)}};return propertyNames.default=r,propertyNames}var additionalProperties={},hasRequiredAdditionalProperties;function requireAdditionalProperties(){if(hasRequiredAdditionalProperties)return additionalProperties;hasRequiredAdditionalProperties=1,Object.defineProperty(additionalProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireNames(),n=requireUtil$2(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:e=>{let{params:r}=e;return t._`{additionalProperty: ${r.additionalProperty}}`}},code(i){const{gen:o,schema:s,parentSchema:a,data:c,errsCount:l,it:u}=i;if(!l)throw new Error("ajv implementation error");const{allErrors:d,opts:h}=u;if(u.props=!0,"all"!==h.removeAdditional&&(0,n.alwaysValidSchema)(u,s))return;const p=(0,e.allSchemaProperties)(a.properties),f=(0,e.allSchemaProperties)(a.patternProperties);function y(e){o.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===h.removeAdditional||h.removeAdditional&&!1===s)y(e);else{if(!1===s)return i.setParams({additionalProperty:e}),i.error(),void(d||o.break());if("object"==typeof s&&!(0,n.alwaysValidSchema)(u,s)){const r=o.name("valid");"failing"===h.removeAdditional?(b(e,r,!1),o.if((0,t.not)(r),(()=>{i.reset(),y(e)}))):(b(e,r),d||o.if((0,t.not)(r),(()=>o.break())))}}}function b(e,t,r){const o={keyword:"additionalProperties",dataProp:e,dataPropType:n.Type.Str};!1===r&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(o,t)}o.forIn("key",c,(r=>{p.length||f.length?o.if(function(r){let s;if(p.length>8){const t=(0,n.schemaRefOrVal)(u,a.properties,"properties");s=(0,e.isOwnProperty)(o,t,r)}else s=p.length?(0,t.or)(...p.map((e=>t._`${r} === ${e}`))):t.nil;return f.length&&(s=(0,t.or)(s,...f.map((n=>t._`${(0,e.usePattern)(i,n)}.test(${r})`)))),(0,t.not)(s)}(r),(()=>g(r))):g(r)})),i.ok(t._`${l} === ${r.default.errors}`)}};return additionalProperties.default=i,additionalProperties}var properties$1={},hasRequiredProperties;function requireProperties(){if(hasRequiredProperties)return properties$1;hasRequiredProperties=1,Object.defineProperty(properties$1,"__esModule",{value:!0});const e=requireValidate(),t=requireCode(),r=requireUtil$2(),n=requireAdditionalProperties(),i={keyword:"properties",type:"object",schemaType:"object",code(i){const{gen:o,schema:s,parentSchema:a,data:c,it:l}=i;"all"===l.opts.removeAdditional&&void 0===a.additionalProperties&&n.default.code(new e.KeywordCxt(l,n.default,"additionalProperties"));const u=(0,t.allSchemaProperties)(s);for(const e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&!0!==l.props&&(l.props=r.mergeEvaluated.props(o,(0,r.toHash)(u),l.props));const d=u.filter((e=>!(0,r.alwaysValidSchema)(l,s[e])));if(0===d.length)return;const h=o.name("valid");for(const e of d)p(e)?f(e):(o.if((0,t.propertyInData)(o,c,e,l.opts.ownProperties)),f(e),l.allErrors||o.else().var(h,!0),o.endIf()),i.it.definedProperties.add(e),i.ok(h);function p(e){return l.opts.useDefaults&&!l.compositeRule&&void 0!==s[e].default}function f(e){i.subschema({keyword:"properties",schemaProp:e,dataProp:e},h)}}};return properties$1.default=i,properties$1}var patternProperties={},hasRequiredPatternProperties;function requirePatternProperties(){if(hasRequiredPatternProperties)return patternProperties;hasRequiredPatternProperties=1,Object.defineProperty(patternProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireUtil$2(),n=requireUtil$2(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(i){const{gen:o,schema:s,data:a,parentSchema:c,it:l}=i,{opts:u}=l,d=(0,e.allSchemaProperties)(s),h=d.filter((e=>(0,r.alwaysValidSchema)(l,s[e])));if(0===d.length||h.length===d.length&&(!l.opts.unevaluated||!0===l.props))return;const p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,f=o.name("valid");!0===l.props||l.props instanceof t.Name||(l.props=(0,n.evaluatedPropsToName)(o,l.props));const{props:y}=l;function g(e){for(const t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function b(r){o.forIn("key",a,(s=>{o.if(t._`${(0,e.usePattern)(i,r)}.test(${s})`,(()=>{const e=h.includes(r);e||i.subschema({keyword:"patternProperties",schemaProp:r,dataProp:s,dataPropType:n.Type.Str},f),l.opts.unevaluated&&!0!==y?o.assign(t._`${y}[${s}]`,!0):e||l.allErrors||o.if((0,t.not)(f),(()=>o.break()))}))}))}!function(){for(const e of d)p&&g(e),l.allErrors?b(e):(o.var(f,!0),b(e),o.if(f))}()}};return patternProperties.default=i,patternProperties}var not={},hasRequiredNot;function requireNot(){if(hasRequiredNot)return not;hasRequiredNot=1,Object.defineProperty(not,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:r,schema:n,it:i}=t;if((0,e.alwaysValidSchema)(i,n))return void t.fail();const o=r.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,(()=>t.reset()),(()=>t.error()))},error:{message:"must NOT be valid"}};return not.default=t,not}var anyOf={},hasRequiredAnyOf;function requireAnyOf(){if(hasRequiredAnyOf)return anyOf;hasRequiredAnyOf=1,Object.defineProperty(anyOf,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:requireCode().validateUnion,error:{message:"must match a schema in anyOf"}};return anyOf.default=e,anyOf}var oneOf={},hasRequiredOneOf;function requireOneOf(){if(hasRequiredOneOf)return oneOf;hasRequiredOneOf=1,Object.defineProperty(oneOf,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:t=>{let{params:r}=t;return e._`{passingSchemas: ${r.passing}}`}},code(r){const{gen:n,schema:i,parentSchema:o,it:s}=r;if(!Array.isArray(i))throw new Error("ajv implementation error");if(s.opts.discriminator&&o.discriminator)return;const a=i,c=n.let("valid",!1),l=n.let("passing",null),u=n.name("_valid");r.setParams({passing:l}),n.block((function(){a.forEach(((i,o)=>{let a;(0,t.alwaysValidSchema)(s,i)?n.var(u,!0):a=r.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},u),o>0&&n.if(e._`${u} && ${c}`).assign(c,!1).assign(l,e._`[${l}, ${o}]`).else(),n.if(u,(()=>{n.assign(c,!0),n.assign(l,o),a&&r.mergeEvaluated(a,e.Name)}))}))})),r.result(c,(()=>r.reset()),(()=>r.error(!0)))}};return oneOf.default=r,oneOf}var allOf={},hasRequiredAllOf;function requireAllOf(){if(hasRequiredAllOf)return allOf;hasRequiredAllOf=1,Object.defineProperty(allOf,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:r,schema:n,it:i}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=r.name("valid");n.forEach(((r,n)=>{if((0,e.alwaysValidSchema)(i,r))return;const s=t.subschema({keyword:"allOf",schemaProp:n},o);t.ok(o),t.mergeEvaluated(s)}))}};return allOf.default=t,allOf}var _if={},hasRequired_if;function require_if(){if(hasRequired_if)return _if;hasRequired_if=1,Object.defineProperty(_if,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:t=>{let{params:r}=t;return e.str`must match "${r.ifClause}" schema`},params:t=>{let{params:r}=t;return e._`{failingKeyword: ${r.ifClause}}`}},code(r){const{gen:i,parentSchema:o,it:s}=r;void 0===o.then&&void 0===o.else&&(0,t.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const a=n(s,"then"),c=n(s,"else");if(!a&&!c)return;const l=i.let("valid",!0),u=i.name("_valid");if(function(){const e=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);r.mergeEvaluated(e)}(),r.reset(),a&&c){const e=i.let("ifClause");r.setParams({ifClause:e}),i.if(u,d("then",e),d("else",e))}else a?i.if(u,d("then")):i.if((0,e.not)(u),d("else"));function d(t,n){return()=>{const o=r.subschema({keyword:t},u);i.assign(l,u),r.mergeValidEvaluated(o,l),n?i.assign(n,e._`${t}`):r.setParams({ifClause:t})}}r.pass(l,(()=>r.error(!0)))}};function n(e,r){const n=e.schema[r];return void 0!==n&&!(0,t.alwaysValidSchema)(e,n)}return _if.default=r,_if}var thenElse={},hasRequiredThenElse,hasRequiredApplicator;function requireThenElse(){if(hasRequiredThenElse)return thenElse;hasRequiredThenElse=1,Object.defineProperty(thenElse,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:["then","else"],schemaType:["object","boolean"],code(t){let{keyword:r,parentSchema:n,it:i}=t;void 0===n.if&&(0,e.checkStrictMode)(i,`"${r}" without "if" is ignored`)}};return thenElse.default=t,thenElse}function requireApplicator(){if(hasRequiredApplicator)return applicator;hasRequiredApplicator=1,Object.defineProperty(applicator,"__esModule",{value:!0});const e=requireAdditionalItems(),t=requirePrefixItems(),r=requireItems(),n=requireItems2020(),i=requireContains(),o=requireDependencies(),s=requirePropertyNames(),a=requireAdditionalProperties(),c=requireProperties(),l=requirePatternProperties(),u=requireNot(),d=requireAnyOf(),h=requireOneOf(),p=requireAllOf(),f=require_if(),y=requireThenElse();return applicator.default=function(){let g=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const b=[u.default,d.default,h.default,p.default,f.default,y.default,s.default,a.default,o.default,c.default,l.default];return g?b.push(t.default,n.default):b.push(e.default,r.default),b.push(i.default),b},applicator}var format$1={},format={},hasRequiredFormat$1,hasRequiredFormat;function requireFormat$1(){if(hasRequiredFormat$1)return format;hasRequiredFormat$1=1,Object.defineProperty(format,"__esModule",{value:!0});const e=requireCodegen(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:t=>{let{schemaCode:r}=t;return e.str`must match format "${r}"`},params:t=>{let{schemaCode:r}=t;return e._`{format: ${r}}`}},code(t,r){const{gen:n,data:i,$data:o,schema:s,schemaCode:a,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:h}=c;l.validateFormats&&(o?function(){const o=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),s=n.const("fDef",e._`${o}[${a}]`),c=n.let("fType"),u=n.let("format");n.if(e._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,(()=>n.assign(c,e._`${s}.type || "string"`).assign(u,e._`${s}.validate`)),(()=>n.assign(c,e._`"string"`).assign(u,s))),t.fail$data((0,e.or)(!1===l.strictSchema?e.nil:e._`${a} && !${u}`,function(){const t=d.$async?e._`(${s}.async ? await ${u}(${i}) : ${u}(${i}))`:e._`${u}(${i})`,n=e._`(typeof ${u} == "function" ? ${t} : ${u}.test(${i}))`;return e._`${u} && ${u} !== true && ${c} === ${r} && !${n}`}()))}():function(){const o=h.formats[s];if(!o)return void function(){if(!1===l.strictSchema)return void h.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===o)return;const[a,c,p]=function(t){const r=t instanceof RegExp?(0,e.regexpCode)(t):l.code.formats?e._`${l.code.formats}${(0,e.getProperty)(s)}`:void 0,i=n.scopeValue("formats",{key:s,ref:t,code:r});if("object"==typeof t&&!(t instanceof RegExp))return[t.type||"string",t.validate,e._`${i}.validate`];return["string",t,i]}(o);a===r&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!d.$async)throw new Error("async format in sync schema");return e._`await ${p}(${i})`}return"function"==typeof c?e._`${p}(${i})`:e._`${p}.test(${i})`}())}())}};return format.default=t,format}function requireFormat(){if(hasRequiredFormat)return format$1;hasRequiredFormat=1,Object.defineProperty(format$1,"__esModule",{value:!0});const e=[requireFormat$1().default];return format$1.default=e,format$1}var metadata={},hasRequiredMetadata,hasRequiredDraft7;function requireMetadata(){return hasRequiredMetadata||(hasRequiredMetadata=1,Object.defineProperty(metadata,"__esModule",{value:!0}),metadata.contentVocabulary=metadata.metadataVocabulary=void 0,metadata.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],metadata.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),metadata}function requireDraft7(){if(hasRequiredDraft7)return draft7;hasRequiredDraft7=1,Object.defineProperty(draft7,"__esModule",{value:!0});const e=requireCore(),t=requireValidation(),r=requireApplicator(),n=requireFormat(),i=requireMetadata(),o=[e.default,t.default,(0,r.default)(),n.default,i.metadataVocabulary,i.contentVocabulary];return draft7.default=o,draft7}var discriminator={},types$1={},hasRequiredTypes$1,hasRequiredDiscriminator;function requireTypes$1(){return hasRequiredTypes$1||(hasRequiredTypes$1=1,Object.defineProperty(types$1,"__esModule",{value:!0}),types$1.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(e||(types$1.DiscrError=e={}))),types$1;var e}function requireDiscriminator(){if(hasRequiredDiscriminator)return discriminator;hasRequiredDiscriminator=1,Object.defineProperty(discriminator,"__esModule",{value:!0});const e=requireCodegen(),t=requireTypes$1(),r=requireCompile(),n=requireRef_error(),i=requireUtil$2(),o={message:e=>{let{params:{discrError:r,tagName:n}}=e;return r===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`},params:t=>{let{params:{discrError:r,tag:n,tagName:i}}=t;return e._`{error: ${r}, tag: ${i}, tagValue: ${n}}`}},s={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(o){const{gen:s,data:a,schema:c,parentSchema:l,it:u}=o,{oneOf:d}=l;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const p=s.let("valid",!1),f=s.const("tag",e._`${a}${(0,e.getProperty)(h)}`);function y(t){const r=s.name("valid"),n=o.subschema({keyword:"oneOf",schemaProp:t},r);return o.mergeEvaluated(n,e.Name),r}s.if(e._`typeof ${f} == "string"`,(()=>function(){const a=function(){var e;const t={},o=a(l);let s=!0;for(let t=0;t<d.length;t++){let l=d[t];if((null==l?void 0:l.$ref)&&!(0,i.schemaHasRulesButRef)(l,u.self.RULES)){const e=l.$ref;if(l=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),l instanceof r.SchemaEnv&&(l=l.schema),void 0===l)throw new n.default(u.opts.uriResolver,u.baseId,e)}const p=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[h];if("object"!=typeof p)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(o||a(l)),c(p,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function a(e){let{required:t}=e;return Array.isArray(t)&&t.includes(h)}function c(e,t){if(e.const)p(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const r of e.enum)p(r,t)}}function p(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=r}}();s.if(!1);for(const t in a)s.elseIf(e._`${f} === ${t}`),s.assign(p,y(a[t]));s.else(),o.error(!1,{discrError:t.DiscrError.Mapping,tag:f,tagName:h}),s.endIf()}()),(()=>o.error(!1,{discrError:t.DiscrError.Tag,tag:f,tagName:h}))),o.ok(p)}};return discriminator.default=s,discriminator}var $schema="http://json-schema.org/draft-07/schema#",$id="http://json-schema.org/draft-07/schema#",title="Core schema meta-schema",definitions={schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type$1=["object","boolean"],properties={$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},require$$3={$schema:$schema,$id:$id,title:title,definitions:definitions,type:type$1,properties:properties,default:!0},hasRequiredAjv;function requireAjv(){return hasRequiredAjv||(hasRequiredAjv=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=requireCore$1(),n=requireDraft7(),i=requireDiscriminator(),o=require$$3,s=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach((e=>this.addVocabulary(e))),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(o,s):o;this.addMetaSchema(e,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var l=requireValidate();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=requireCodegen();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=requireValidation_error();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=requireRef_error();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(ajv,ajv.exports)),ajv.exports}var ajvExports=requireAjv(),Ajv=getDefaultExportFromCjs(ajvExports);const{Buffer:Buffer$2}=buffer$1,dsDispatcherPrefix=DBPrefix.dsPrefix.child(new Key$1("dispatcher"));class Dispatcher{constructor(e){Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reducers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.store=e,this.reducers=[],this.lock={lock:()=>{},unlock:()=>{}},this.lastID=0}getStore(){return this.store}register(e){this.lock.lock(),this.lastID++,this.reducers.push(e),this.lock.unlock()}async dispatch(e){this.lock.lock();const t=await this.store.newTransactionExtended(!1);try{for(const r of e){const e=this.getKey(r),n=Buffer$2.from(jsonStringify(r));await t.put(e,n)}await t.commit()}catch(e){throw t.discard(),e}finally{this.lock.unlock()}this.reducers.map((async t=>{await t.reduce(e)}))}async*query(e){return this.store.query(e)}getKey(e){const t=e.timestamp,r=e.collection,n=e.instanceID;return dsDispatcherPrefix.child(new Key$1(t.toString())).child(new Key$1(r.toString())).child(new Key$1(n.toString()))}}class Query{constructor(){Object.defineProperty(this,"ands",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"ors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,writable:!0,value:new Sort}),Object.defineProperty(this,"seek",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"limit",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"skip",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:""}),this.ands=[],this.ors=[],this.sort=new Sort,this.seek="",this.limit=0,this.skip=0,this.index=""}validate(){if(!this)return null;for(const e of this.ands){const t=e.validate();if(t)return t}for(const e of this.ors){const t=e.validate();if(t)return t}return null}and(e){return new Criterion(e)}or(e){return this.ors.push(e),this}useIndex(e){return this.index=e,this}orderBy(e){return this.sort.fieldPath=e,this.sort.desc=!1,this}orderByDesc(e){return this.sort.fieldPath=e,this.sort.desc=!0,this}orderById(){return this.sort.fieldPath="_id",this.sort.desc=!1,this}orderByIdDesc(){return this.sort.fieldPath="_id",this.sort.desc=!0,this}seekId(e){return this.seek=e,this}limitTo(e){return this.limit=e,this}skipNum(e){return this.skip=e,this}match(e){if(!this)throw new Error("query can't be null");let t=!0;for(const r of this.ands)try{const n=traverseFieldPathMap(e,r.fieldPath),i=r.match(n);if(t=t&&i,!t)break}catch(e){return!1}if(t)return!0;for(const t of this.ors)try{if(t.match(e))return!0}catch(e){return!1}return!1}}class Criterion{constructor(e,t,r){Object.defineProperty(this,"fieldPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:Operation.eq}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:new Value}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.fieldPath=e,this.operation=t,this.value=r}validate(){if(!this)return null;let e=0;return null!==this.value.bool&&e++,null!==this.value.string&&e++,null!==this.value.float&&e++,1!==e?new Error("value type should describe exactly one type"):null}eq(e){return this.createCriterion(Operation.eq,e)}ne(e){return this.createCriterion(Operation.ne,e)}gt(e){return this.createCriterion(Operation.gt,e)}lt(e){return this.createCriterion(Operation.lt,e)}ge(e){return this.createCriterion(Operation.ge,e)}le(e){return this.createCriterion(Operation.le,e)}createCriterion(e,t){return this.operation=e,this.value=createValue(t),this.query||(this.query=new Query),this.query.ands.push(this),this.query}match(e){try{const t=compareValue(e,this.value);switch(this.operation){case Operation.eq:return 0===t;case Operation.ne:return 0!==t;case Operation.gt:return t>0;case Operation.lt:return t<0;case Operation.le:return t<=0;case Operation.ge:return t>=0;default:throw new Error("invalid operation")}}catch(e){return!1}}}class Value{constructor(){Object.defineProperty(this,"string",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"bool",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"float",{enumerable:!0,configurable:!0,writable:!0,value:null})}}class Sort{constructor(){Object.defineProperty(this,"fieldPath",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"desc",{enumerable:!0,configurable:!0,writable:!0,value:!1})}}var Operation;function createValue(e){const t=new Value;return"string"==typeof e?t.string=e:"boolean"==typeof e?t.bool=e:"number"==typeof e&&(t.float=e),t}function compareValue(e,t){if(null!==t.string){return("string"==typeof e?e:"").localeCompare(t.string)}if(null!==t.bool){return("boolean"==typeof e&&e)===t.bool?0:-1}if(null!==t.float){const r="number"==typeof e?e:0;return r===t.float?0:r<t.float?-1:1}throw new Error("no underlying value for criterion was provided")}function traverseFieldPathMap(e,t){const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n)return;n=n[e]}return n}function compare(e,t){if(e===t)return 0;if(typeof e!=typeof t)throw new Error("Cannot compare different types");if("string"==typeof e)return e.localeCompare(t);if("number"==typeof e)return e-t;if("boolean"==typeof e)return e===t?0:e?1:-1;throw new Error("Cannot compare values of type "+typeof e)}!function(e){e[e.eq=0]="eq",e[e.ne=1]="ne",e[e.gt=2]="gt",e[e.lt=3]="lt",e[e.ge=4]="ge",e[e.le=5]="le",e[e.fn=6]="fn"}(Operation||(Operation={}));const iteratorKeyMinCacheSize=100;class IndexError extends Error{constructor(e){super(e),this.name="IndexError"}}new IndexError("unique constraint violation");const ErrNotIndexable=new IndexError("value not indexable"),ErrCantCreateUniqueIndex=new IndexError("can't create unique index (duplicate instances exist)"),ErrIndexNotFound=new IndexError("index not found"),indexPrefix=new Key$1("_index"),indexTypes=["string","number","integer","boolean"];class InvalidSortingFieldError extends Error{constructor(){super("sorting field doesn't correspond to instance type"),this.name="InvalidSortingFieldError"}}new InvalidSortingFieldError;class ThreadDBError extends Error{constructor(e){super(e),this.name="ThreadDBError"}}const ErrInvalidCollectionSchemaPath=new ThreadDBError("collection schema does not contain path"),ErrCollectionNotFound=new ThreadDBError("collection not found");new ThreadDBError("collection already registered");const ErrInstanceNotFound=new ThreadDBError("instance not found"),ErrReadonlyTx=new ThreadDBError("read only transaction"),ErrInvalidSchemaInstance=new ThreadDBError("instance doesn't correspond to schema");new ThreadDBError("invalid collection schema"),new ThreadDBError("invalid collection name");const errMissingInstanceID=new ThreadDBError("invalid instance: missing _id attribute"),errAlreadyDiscardedCommitedTxn=new ThreadDBError("can't commit discarded/committed txn"),errCantCreateExistingInstance=new ThreadDBError("can't create already existing instance"),baseKey$1=dsPrefix.child(new Key$1("collection")),vmTimeout=200,writeValidatorFn="_validate",readFilterFn="_filter",EmptyInstanceID="";function NewInstanceID(){return nanoid$1()}class BrowserJSRuntime{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:vmTimeout;Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"functions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:null})}runScript(e){try{const t=new Function("context",`\n with(context) { \n ${e}; \n return context; \n }\n `);let r=!1;return this.timeoutId=window.setTimeout((()=>{}),this.timeout),this.context=t(this.context)||this.context,r=!0,this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),!0}catch(e){throw this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),new Error(`Script execution error: ${e instanceof Error?e.message:String(e)}`)}}getGlobal(e){return this.context[e]}call(e){const t=this.context[e];if("function"!=typeof t)throw new Error(`${e} is not a function`);try{let e=!1;this.timeoutId=window.setTimeout((()=>{}),this.timeout);for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];const o=t.apply(this.context,n);return e=!0,this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),o}catch(e){throw this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),new Error(`Function execution error: ${e instanceof Error?e.message:String(e)}`)}}}class Collection{constructor(e,t,r,n,i){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"db",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"rawWriteValidator",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"rawReadFilter",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"schemaValidator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"vm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writeValidator",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"readFilter",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"indexes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.schemaValidator=new Ajv({allErrors:!0}),this.vm=new BrowserJSRuntime(vmTimeout),n&&this.compileAndLoadValidator(n,writeValidatorFn,["writer","event","instance"]),i&&this.compileAndLoadValidator(i,readFilterFn,["reader","instance"])}compileAndLoadValidator(e,t,r){try{const n=`function ${t}(${r.join(",")}) {${e}}`;this.vm.runScript(n);if("function"!=typeof this.vm.getGlobal(t))throw new Error(`${t} is not a function`);t===writeValidatorFn?this.writeValidator=(e,t,r)=>this.vm.call(writeValidatorFn,e,t,r):t===readFilterFn&&(this.readFilter=(e,t)=>this.vm.call(readFilterFn,e,t))}catch(e){throw new Error(`Failed to compile ${t}: ${e instanceof Error?e.message:String(e)}`)}}baseKey(){return baseKey$1.child(new Key$1(this.name))}getName(){return this.name}getSchema(){return(new TextEncoder).encode(JSON.stringify(this.schema))}getWriteValidator(){return(new TextEncoder).encode(this.rawWriteValidator||"")}getReadFilter(){return(new TextEncoder).encode(this.rawReadFilter||"")}async readTxn(e,t){return this.db.readTxn(this,e,t)}async writeTxn(e,t){return this.db.writeTxn(this,e,t)}async findByID(e,t){let r=null;return await this.readTxn((async t=>{r=await t.findByID(e)}),t),r}async create(e,t){let r="";return await this.writeTxn((async t=>{const n=await t.create(e);n.length>0&&(r=n[0])}),t),r}async createMany(e,t){let r=[];return await this.writeTxn((async t=>{r=await t.create(...e)}),t),r}async delete(e,t){await this.writeTxn((async t=>{await t.delete(e)}),t)}async deleteMany(e,t){await this.writeTxn((async t=>{await t.delete(...e)}),t)}async save(e,t){await this.writeTxn((async t=>{await t.save(e)}),t)}async saveMany(e,t){await this.writeTxn((async t=>{await t.save(...e)}),t)}async verify(e,t){await this.writeTxn((async t=>{await t.verify(e)}),t)}async verifyMany(e,t){await this.writeTxn((async t=>{await t.verify(...e)}),t)}async has(e,t){let r=!1;return await this.readTxn((async t=>{r=await t.has(e)}),t),r}async hasMany(e,t){let r=!1;return await this.readTxn((async t=>{r=await t.has(...e)}),t),r}async find(e,t){let r=[];return await this.readTxn((async t=>{r=await t.find(e)}),t),r}async modifiedSince(e,t){let r=[];return await this.readTxn((async t=>{r=await t.modifiedSince(e)}),t),r}validInstance(e){try{const t=JSON.parse((new TextDecoder).decode(e)),r=this.schemaValidator.compile(this.schema);if(!r(t)&&r.errors&&r.errors.length>0){let e="";for(let t=0;t<r.errors.length;t++){const n=r.errors[t];e+=`${n?.schemaPath}: ${n?.message}`,t!==r.errors.length-1&&(e+="; ")}throw new Error(`${ErrInvalidSchemaInstance.message}: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(ErrInvalidSchemaInstance.message))throw e;throw new Error(`Error validating instance: ${e instanceof Error?e.message:String(e)}`)}}async validWrite(e,t){if(this.writeValidator)try{const r=e?e.toString():null,n=await t.marshal(),i=JSON.parse((new TextDecoder).decode(n));let o=null;try{const e=this.baseKey().child(new Key$1(t.instanceID)),r=await this.db.datastore.get(e);r&&(o=JSON.parse((new TextDecoder).decode(r)))}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(!0!==this.writeValidator(r,i,o))throw new Error("Write validation failed")}catch(e){throw new Error(`Write validation error: ${e instanceof Error?e.message:String(e)}`)}}async filterRead(e,t){if(!this.readFilter)return t;try{const r=e?e.toString():null,n=JSON.parse((new TextDecoder).decode(t)),i=this.readFilter(r,n);return null===i?null:(new TextEncoder).encode(jsonStringify(i))}catch(e){throw new Error(`Read filter error: ${e instanceof Error?e.message:String(e)}`)}}getIndexes(){if(0===this.indexes.size)return[];const e=[];return this.indexes.forEach(((t,r)=>{r!==idFieldName&&e.push(t)})),e}async addIndex(e,t){if(e.path!==idFieldName||!this.indexes.has(idFieldName))try{const r=getSchemaTypeAtPath(this.schema,e.path);let n=!1;for(const e of indexTypes)if(r?.type===e){n=!0;break}if(!n)throw ErrNotIndexable;const i=this.indexes.get(e.path);if(i&&i.unique===e.unique)return;if(e.unique&&e.path!==idFieldName){const r=new Map,n=await this.find(new Query,t);for(const t of n){const n=traverseFieldPathMap(t,e.path);if(void 0!==n){if(r.has(n))throw ErrCantCreateUniqueIndex;r.set(n,!0)}}}this.indexes.set(e.path,e),await this.saveIndexes()}catch(e){throw e}}async dropIndex(e){if(e===idFieldName)throw new Error(`${idFieldName} index cannot be dropped`);this.indexes.delete(e),await this.saveIndexes()}async saveIndexes(){try{const e={};this.indexes.forEach(((t,r)=>{e[r]=t}));const t=(new TextEncoder).encode(JSON.stringify(e));await this.db.datastore.put(DBPrefix.dsIndexes.child(new Key$1(this.name)),t)}catch(e){throw new Error(`Failed to save indexes: ${e instanceof Error?e.message:String(e)}`)}}async indexAdd(e,t,r){for(const[n,i]of this.indexes.entries())try{const o=decode$e(r);await this.indexUpdate(n,i,e,t,o,!1)}catch(e){throw e}}async indexDelete(e,t,r){for(const[n,i]of this.indexes.entries())try{await this.indexUpdate(n,i,e,t,r,!0)}catch(e){throw e}}async indexUpdate(e,t,r,n,i,o){try{const s=getIndexValue(e,i),a=indexPrefix.child(this.baseKey()).child(new Key$1(e)).child(new Key$1(s.toString().substring(1)));let c=null;try{c=await r.get(a)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}const l=new KeyList;if(c){const e=JSON.parse((new TextDecoder).decode(c));l.fromArray(e)}if(o?l.remove(n):(t.unique&&l.remove(n),l.add(n)),0===l.size())await r.delete(a);else{const e=(new TextEncoder).encode(JSON.stringify(l.toArray()));await r.put(a,e)}}catch(e){if(e===ErrNotIndexable)return;throw e}}}function getIndexValue(e,t){const r=traverseFieldPathMap(JSON.parse((new TextDecoder).decode(t)),e);if(void 0===r)throw ErrNotIndexable;return new Key$1(String(r))}class KeyList{constructor(){Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:[]})}add(e){const t=e.uint8Array();let r=this.binarySearch(t);r<this.keys.length&&this.bytesEqual(this.keys[r],t)||this.keys.splice(r,0,t)}remove(e){const t=e.uint8Array();let r=this.binarySearch(t);r<this.keys.length&&this.keys[r]&&this.bytesEqual(this.keys[r],t)&&this.keys.splice(r,1)}in(e){const t=e.uint8Array(),r=this.binarySearch(t);return r<this.keys.length&&void 0!==this.keys[r]&&this.bytesEqual(this.keys[r],t)}size(){return this.keys.length}toArray(){return[...this.keys]}fromArray(e){this.keys=[...e]}binarySearch(e){let t=0,r=this.keys.length-1;for(;t<=r;){const n=Math.floor((t+r)/2),i=this.bytesCompare(this.keys[n],e);if(i<0)t=n+1;else{if(!(i>0))return n;r=n-1}}return t}bytesCompare(e,t){const r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return e.length<t.length?-1:e.length>t.length?1:0}bytesEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}}class Txn{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];Object.defineProperty(this,"collection",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"readonly",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"actions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"discarded",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"committed",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async create(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=new Array(t.length);for(let e=0;e<t.length;e++){if(this.readonly)throw ErrReadonlyTx;const r=t[e].slice(0);let i=await getInstanceID(r);if(i===EmptyInstanceID){const t=setNewInstanceID(r);i=t.id;const o=t.data;this.collection.validInstance(o),n[e]=i;const s=this.collection.baseKey().child(new Key$1(i));try{if(await this.collection.db.datastore.has(s))throw errCantCreateExistingInstance}catch(e){if(e!==errCantCreateExistingInstance)throw new Error(`Error checking if instance exists: ${e instanceof Error?e.message:String(e)}`);throw e}const{data:a}=setModifiedTag(o);this.actions.push({type:CoreActionType.Create,instanceID:i,collectionName:this.collection.name,current:a})}}return n}async verify(){try{const n=await(this.token?.pubKey());if(!n)throw new Error("Identity not found");for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const i=await this.createSaveActions(n,...t),{events:o}=await this.createEvents(i);if(0===o.length)return;for(const e of o)await this.collection.validWrite(n,e)}catch(e){throw new Error(`Verification failed: ${e instanceof Error?e.message:String(e)}`)}}async save(){try{const n=await(this.token?.pubKey())||null;for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const i=await this.createSaveActions(n,...t);this.actions.push(...i)}catch(e){throw new Error(`Save failed: ${e instanceof Error?e.message:String(e)}`)}}async createSaveActions(e){const t=[];for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];for(let r=0;r<n.length;r++){if(this.readonly)throw ErrReadonlyTx;const i=n[r].slice(0);this.collection.validInstance(i);const{data:o}=setModifiedTag(i),s=await getInstanceID(o);if(s===EmptyInstanceID)throw errMissingInstanceID;const a=this.collection.baseKey().child(new Key$1(s));let c;try{c=await this.collection.db.datastore.get(a)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e;c=(new TextEncoder).encode("{}")}if(c.length>0&&null!==e){c=await this.collection.filterRead(e,c)||c}t.push({type:CoreActionType.Save,instanceID:s,collectionName:this.collection.name,previous:c,current:o})}return t}async delete(){for(let e=0;e<arguments.length;e++){if(this.readonly)throw ErrReadonlyTx;const t=this.collection.baseKey().child(new Key$1(e<0||arguments.length<=e?void 0:arguments[e]));await this.collection.db.datastore.has(t)&&this.actions.push({type:CoreActionType.Delete,instanceID:e<0||arguments.length<=e?void 0:arguments[e],collectionName:this.collection.name})}}async has(){const e=await(this.collection.db.connector?.validate(this.token));if(e)throw e;const t=await(this.token?.pubKey());for(let e=0;e<arguments.length;e++){const r=this.collection.baseKey().child(new Key$1(e<0||arguments.length<=e?void 0:arguments[e]));if(!await this.collection.db.datastore.has(r))return!1;{if(!this.collection.readFilter)continue;const e=await this.collection.db.datastore.get(r);if(!await this.collection.filterRead(t,e))return!1}}return!0}async findByID(e){const t=await(this.collection.db.connector?.validate(this.token));if(t)throw t;const r=this.collection.baseKey().child(new Key$1(e));let n;try{n=await this.collection.db.datastore.get(r)}catch(e){if("ERR_NOT_FOUND"===e.code)throw ErrInstanceNotFound;throw e}const i=await(this.token?.pubKey()),o=await this.collection.filterRead(i,n);if(!o)throw ErrInstanceNotFound;let s;try{s=JSON.parse((new TextDecoder).decode(o))}catch(e){s={}}return s}async find(e){try{const t=await(this.collection.db.connector?.validate(this.token));if(t)throw t;e||(e=new Query);const r=e.validate();if(r)throw new Error(`Invalid query: ${r.message}`);const n=await this.collection.db.datastore.newTransactionExtended(!0);try{const t=await this.newIterator(n,this.collection.baseKey(),e);try{const r=await(this.token?.pubKey()),n=[];let i=0;for(;;){const o=await t.next();if(!o||!1==!o.done)break;let s=null;try{s=await this.collection.filterRead(r,o.value)}catch(e){throw new Error(`Filter read error: ${e instanceof Error?e.message:String(e)}`)}if(s&&(i++,i>e.skip)){let e;try{e=JSON.parse((new TextDecoder).decode(s))}catch(t){e={}}n.push({instanceID:o.instanceID,key:o.key,value:s,marshaledValue:e})}if(e.limit>0&&n.length===e.limit)break}e.sort.fieldPath&&e.sort.fieldPath!==idFieldName&&n.sort(((t,r)=>{const n=traverseFieldPathMap(t.marshaledValue||{},e.sort.fieldPath),i=traverseFieldPathMap(r.marshaledValue||{},e.sort.fieldPath);if(void 0===n||void 0===i)return void 0===n&&void 0===i?0:void 0===n?-1:1;try{let t=compare(n,i);return e.sort.desc&&(t*=-1),t}catch(e){return 0}}));const o=n.map((e=>e.marshaledValue));return o}finally{t&&"function"==typeof t.close&&await t.close()}}finally{n.discard()}}catch(e){throw new Error(`Find operation failed: ${e instanceof Error?e.message:String(e)}`)}}async newIterator(e,t,r){const n={prefix:t.toString()};r.index&&(n.index=r.index),r.seek&&(n.start=t.child(new Key$1(r.seek)).toString());const i=await e.query(n);return{async next(){const e=await i.next();if(e.done)return{done:!0};if(e.value&&r&&e.value.value)try{const t=JSON.parse((new TextDecoder).decode(e.value.value));if(!r.match(t))return this.next()}catch(e){}return{done:!1,key:e.value.key,instanceID:new Key$1(e.value.key).name(),value:e.value.value}},async close(){i&&"function"==typeof i.return&&await i.return()}}}async modifiedSince(e){const t=await this.collection.db.datastore.newTransactionExtended(!0);try{const r=e=>{const t=e.key.toString();return new Key$1(t).type()===this.collection.name},n=e.toString(),i=t.queryExtended({prefix:dsDispatcherPrefix.toString(),filters:[r],seekPrefix:dsDispatcherPrefix.child(new Key$1(n)).toString()}),o=new Set;for await(const e of i){const t=new Key$1(e.key).name();o.add(t)}return Array.from(o)}finally{t.discard()}}async commit(){try{const{events:e,node:t}=await this.createEvents(this.actions);if(!t)return;await(this.collection.db.connector?.createNetRecord(t,this.token)),await(this.collection.db.dispatcher?.dispatch(e)),this.committed=!0}catch(e){throw new Error(`Commit failed: ${e instanceof Error?e.message:String(e)}`)}}discard(){this.discarded=!0}refreshCollection(){const e=this.collection.db.collections.get(this.collection.name);if(!e)throw ErrCollectionNotFound;this.collection=e}async createEvents(e){if(this.discarded||this.committed)throw errAlreadyDiscardedCommitedTxn;try{const[t,r]=await this.collection.db.eventcodec.create(e);return 0===t.length&&r?{events:[],node:null}:{events:t,node:r}}catch(e){throw new Error(`Error creating events: ${e instanceof Error?e.message:String(e)}`)}}}function getSchemaTypeAtPath(e,t){const r=t.split(".");let n=e;for(const t of r){if(n=getSchemaTypeProperties(n,e.definitions)[t],!n)throw ErrInvalidCollectionSchemaPath}return n}function getSchemaTypeProperties(e,t){if(!e)return{};let r=e.properties||{};if(e.$ref){const n=e.$ref.split("/");if(n.length>0){const e=n[n.length-1],i=t?.[e];i&&(r=i.properties||{})}}return r}async function getInstanceID(e){try{const t=JSON.parse((new TextDecoder).decode(e));return t._id?t._id:EmptyInstanceID}catch(e){throw new Error(`Error getting instance ID: ${e instanceof Error?e.message:String(e)}`)}}function setNewInstanceID(e){const t=NewInstanceID();try{const r=JSON.parse((new TextDecoder).decode(e));return r._id=t,{id:t,data:(new TextEncoder).encode(JSON.stringify(r))}}catch(e){throw new Error(`Error setting instance ID: ${e instanceof Error?e.message:String(e)}`)}}function setModifiedTag(e){const t=1000000n*BigInt(Date.now())+BigInt(Math.floor(1e6*Math.random()));try{const r=JSON.parse((new TextDecoder).decode(e));r["_mod"]=t;return{time:t,data:(new TextEncoder).encode(jsonStringify(r))}}catch(e){throw new Error(`设置 _mod 字段失败: ${e instanceof Error?e.message:String(e)}`)}}let Iterator$1=class{constructor(e,t){Object.defineProperty(this,"nextKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"txn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyCache",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"iter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.txn=e,this.query=t,this.nextKeys=async()=>[]}async nextSync(){if(""===this.query.index){const e={result:{entry:{},error:null}};let t=!1;for await(const r of this.iter.next())try{const n=JSON.parse((new TextDecoder).decode(r.value));if(t=this.query.match(n),e.result.error)break;if(t)return{result:r,marshaledValue:n}}catch(t){e.result.error=t;break}return t?e:null}if(0===this.keyCache.length)try{const e=await this.nextKeys();if(0===e.length)return{result:{entry:{},error:null}};this.keyCache=[...this.keyCache,...e]}catch(e){return{result:{entry:{},error:e}}}const e=this.keyCache[0];this.keyCache=this.keyCache.slice(1);try{const t=await this.txn.get(e);return{result:{entry:{key:e.toString(),value:t},error:null}}}catch(e){return{result:{entry:{},error:e}}}}async close(){this.iter&&"function"==typeof this.iter.close&&await this.iter.close()}};async function newIterator(e,t,r){const n=new Iterator$1(e,r);let i;i=r.index?indexPrefix.child(t).child(new Key$1(r.index)):t;const o={query:{prefix:i.toString()}};r.sort.fieldPath===idFieldName&&(r.sort.desc?o.orders=[{orderByKeyDescending:!0}]:o.orders=[{orderByKey:!0}]),r.seek&&(o.seekPrefix=i.child(new Key$1(r.seek)).toString());try{const t=await e.queryExtended(o);if(n.iter=t,!r.index)return n.nextKeys=async()=>[],n;let s=!0;return n.nextKeys=async()=>{const e=[];for(;e.length<iteratorKeyMinCacheSize;){const t=await n.iter.nextSync();if(!t){if(s)throw ErrIndexNotFound;return e}s=!1;const o=new Key$1(t.result.entry.key),a=i.name(),c=o.name();let l=c;if(isValidJSON(c)){const e=JSON.parse(c);l=null!==e?e:c}else l=c;try{const n=JSON.stringify({[a]:l}),i=JSON.parse(n);if(r.match(i)){const r=decodeKeyList(t.result.entry.value);for(const t of r)e.push(new Key$1((new TextDecoder).decode(t)))}}catch(e){continue}}return e},n}catch(e){throw e}}function isValidJSON(e){try{return JSON.parse(e),!0}catch{return!1}}function decodeKeyList(e){if(!e)return[];try{return JSON.parse((new TextDecoder).decode(e))}catch{return[]}}const DAG_CBOR_CODEC={name:name$4,code:code$4,encode:encode$b,decode:decode$e};class JsonPatcher{async create(e){const t=this.convertActions(e),r={patches:t},n=await wrapObject(r);return[this.wrapEvents(t),n]}async reduce(e,t,r,n){const i=await t.newTransactionExtended(!1);try{const t=[];for(const o of this.sortEvents(e)){const e=await this.parseEvent(o);await this.processEvent(e,r,i,n),t.push({type:e.patch.type,collection:e.collectionName||"default",instanceID:e.iD})}return await i.commit(),t}catch(e){throw i.discard(),this.wrapError(e)}}async eventsFromBytes(e){let t=await decode$e(e);if(t&&"object"==typeof t&&"patches"in t&&Array.isArray(t.patches))return this.wrapEvents(t.patches);throw new Error("Invalid block format: expected RecordEvents with patches array")}convertActions(e){const t=BigInt(1e6*Date.now()+Math.floor(1e6*Math.random()));return e.map((e=>({timestamp:t,iD:e.instanceID,collectionName:e.collectionName||"default",patch:e.current?{type:e.type,instanceID:e.instanceID,jSONPatch:e.current}:{type:e.type,instanceID:e.instanceID,jSONPatch:new Uint8Array}})))}wrapEvents(e){return e&&0!==e.length?e.map((e=>({collection:e.collectionName||"default",instanceID:e.iD||e.patch.instanceID,timestamp:e.timestamp,payload:e.patch.jSONPatch?e.patch.jSONPatch:new Uint8Array,marshal:async()=>this.marshalPatchEvent(e)}))):[]}async marshalPatchEvent(e){return encode$b({t:e.timestamp,i:e.iD||e.iD,c:e.collectionName,op:{type:e.patch.type,id:e.patch.instanceID,patch:e.patch.jSONPatch?e.patch.jSONPatch:new Uint8Array}})}sortEvents(e){return[...e].sort(((e,t)=>e.timestamp<t.timestamp?-1:e.timestamp>t.timestamp?1:0))}async parseEvent(e){const t=decode$e(await e.marshal());return{timestamp:t.t,iD:t.i,collectionName:t.c,patch:{type:t.op.type,instanceID:t.op.id,jSONPatch:t.op.patch?encode$b(t.op.patch):new Uint8Array}}}async processEvent(e,t,r,n){const i=t.child(new Key$1(e.collectionName||"default")).child(new Key$1(e.iD)),o=await r.get(i).catch((()=>{})),s=e.patch.type===CoreActionType.Delete?void 0:e.patch.jSONPatch;if(await n(e.collectionName||"default",i,r,o,s),e.patch.type===CoreActionType.Delete)await r.delete(i);else if(s){const e=decode$e(s);if(!e)throw new Error("Failed to decode JSON patch");await r.put(i,e)}}wrapError(e){return new Error(`JSONPATCHER_ERROR: ${e.message}`)}}Object.defineProperty(JsonPatcher,"ENCODER_SETTINGS",{enumerable:!0,configurable:!0,writable:!0,value:{codec:DAG_CBOR_CODEC,hasher:sha256$3,cidVersion:1}});const baseKey=DBPrefix.dsPrefix.child(new Key$1("collection")),getBlockInitialTimeout=500,getBlockRetries=3;class CollectionExistsError extends Error{constructor(e){super(`Collection ${e} already exists`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="CollectionExistsError"}}class DB{constructor(e,t,r,n){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connector",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"datastore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"eventcodec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"collections",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"localEventsBus",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webLock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writeQueue",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),this.datastore=e,this.name=n.name||"unnamed",this.eventcodec=n.eventCodec||new JsonPatcher,this.webLock="webLock_db_"+r}static async newDB(e,t,r,n){const i=n||new NewOptions;i.eventCodec||(i.eventCodec=new JsonPatcher);const o=new DB(e,t,r.toString(),i);o.name="",o.dispatcher=new Dispatcher(e),o.localEventsBus=new LocalEventsBus;try{await o.loadName()}catch(e){throw new Error("Failed to load DB name")}const s=o.name;i.name?o.name=i.name:""===s&&(o.name="unnamed"),await o.saveName(s),await o.reCreateCollections(),o.dispatcher.register(o);try{const e=await t.connectApp(o,r);o.connector=e}catch(e){throw new Error(`Failed to connect app: ${e instanceof Error?e.message:String(e)}`)}if(i.collections&&i.collections.length>0)for(const e of i.collections)try{await o.newCollection(e)}catch(e){throw new Error(`Failed to create collection: ${e instanceof Error?e.message:String(e)}`)}return o}async getDBInfo(e){try{const t=await(this.connector?.net.getThread(this.connector?.threadId,{token:e?.token}));return{id:this.connector?this.connector.threadId.toString():"",name:this.name,addrs:t?t.addrs.map((e=>e.toString())):[],key:t?t.key?.toString():""}}catch(e){throw new Error(`Failed to get DB info: ${e instanceof Error?e.message:String(e)}`)}}async saveName(e){if(this.name!==e){if(!this.name.match(/^[a-zA-Z0-9_-]+$/))throw new Error("Invalid name");await this.datastore.put(DBPrefix.dsName,(new TextEncoder).encode(this.name))}}async loadName(){try{const e=await this.datastore.get(DBPrefix.dsName);e&&(this.name=(new TextDecoder).decode(e))}catch(e){}}async saveVerno(e){await this.datastore.put(DBPrefix.dsVerno,(new TextEncoder).encode(e.toString()))}async loadVerno(){try{const e=await this.datastore.get(DBPrefix.dsVerno);if(e)return parseInt((new TextDecoder).decode(e))}catch(e){}return 0}async initCollections(e){for(const t of e)await this.newCollection(t)}async upgradeCollections(e){for(const t of e)await this.newCollection(t,!0)}async newCollection(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.collections.has(e.name)&&!t)throw new CollectionExistsError(e.name);const r=new Collection(e.name,e.schema,this);await r.addIndex({path:"_id",unique:!0});for(const t of e.indexes||[])await r.addIndex(t);return this.saveCollection(r),r}async saveCollection(e){try{await this.datastore.put(DBPrefix.dsSchemas.child(new Key$1(e.name)),e.getSchema()),e.rawWriteValidator&&await this.datastore.put(DBPrefix.dsValidators.child(new Key$1(e.name)),(new TextEncoder).encode(e.rawWriteValidator)),e.rawReadFilter&&await this.datastore.put(DBPrefix.dsFilters.child(new Key$1(e.name)),(new TextEncoder).encode(e.rawReadFilter)),this.collections.set(e.name,e)}catch(t){throw new Error(`Failed to save collection ${e.name}: ${t instanceof Error?t.message:String(t)}`)}}async reCreateCollections(){try{const e=this.datastore.query({prefix:DBPrefix.dsSchemas.toString()});try{for await(const t of e){const e=t.key.name(),r=JSON.parse((new TextDecoder).decode(t.value));let n,i;try{const t=await this.datastore.get(DBPrefix.dsValidators.child(new Key$1(e)));n=(new TextDecoder).decode(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}try{const t=await this.datastore.get(DBPrefix.dsFilters.child(new Key$1(e)));i=(new TextDecoder).decode(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}const o=new Collection(e,r,this);try{const t=await this.datastore.get(DBPrefix.dsIndexes.child(new Key$1(e))),r=JSON.parse((new TextDecoder).decode(t));for(const[e,t]of Object.entries(r))e&&o.indexes.set(e,t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}this.collections.set(o.name,o)}}catch(e){throw new Error(`Error re-creating collections: ${e instanceof Error?e.message:String(e)}`)}}catch(e){throw new Error(`Error re-creating collections: ${e instanceof Error?e.message:String(e)}`)}}getCollection(e){const t=this.collections.get(e);if(!t)throw new Error(`Collection ${e} not found`);return t}async close(){}async reduce(e){try{const t=(await this.eventcodec.reduce(e,this.datastore,baseKey,this.defaultIndexFunc())).map((e=>({collectionName:e.collection,type:e.type,instanceID:e.instanceID})));this.notifyStateChanged(t)}catch(e){throw new Error(`Error reducing events: ${e instanceof Error?e.message:String(e)}`)}}defaultIndexFunc(){return async(e,t,r,n,i)=>{const o=this.collections.get(e);if(!o)throw new Error(`collection (${e}) not found`);n&&await o.indexDelete(r,t,n),i&&await o.indexAdd(r,t,i)}}notifyStateChanged(e){this.localEventsBus}async notifyTxnEvents(e,t){try{await(this.localEventsBus?.send({node:e,token:t}))}catch(e){throw new Error(`Failed to notify transaction events: ${e instanceof Error?e.message:String(e)}`)}}async dispatch(e){for(const t of e)await this.reduce([t])}async validateNetRecordBody(e,t){try{const t=await this.eventcodec.eventsFromBytes(e.data());if(0===t.length)return;for(const e of t){if(!this.collections.get(e.collection))return Errors$6.ErrCollectionNotFound}return}catch(e){return e}}async handleNetRecord(e,t){let r;try{if(!this.connector)return new Error("no connector");r=await EventFromRecord(this.connector?.net.bstore,e.value())}catch(t){try{const t=await this.getBlockWithRetry(e.value());r=await EventFromNode(t)}catch(e){return e}}try{const e=await r.getBody(this.connector?.net,t.read()),n=await this.eventcodec.eventsFromBytes(e.rawData());await this.dispatch(n)}catch(e){return new Error(`error when processing event: ${e instanceof Error?e.message:String(e)}`)}}async getNetRecordCreateTime(e,t){let r,n,i;if(!this.connector)throw new Error("no connector");try{r=await EventFromRecord(this.connector?.net.bstore,e.value())}catch(t){try{const t=await this.getBlockWithRetry(e.value());r=await EventFromNode(t)}catch(e){throw new Error(`Error when decoding block to event: ${e instanceof Error?e.message:String(e)}`)}}try{n=await r.getBody(this.connector?.net.bstore,t.read())}catch(t){throw new Error(`Error when getting body of event on thread ${this.connector?.threadId}/${e.logID()}: ${t instanceof Error?t.message:String(t)}`)}try{i=await this.eventcodec.eventsFromBytes(n.data())}catch(e){throw new Error(`Error when unmarshaling event from bytes: ${e instanceof Error?e.message:String(e)}`)}if(0===i.length)throw new Error("No events found in record");return i[0].timestamp}async getBlockWithRetry(e){let t=getBlockInitialTimeout;if(!this.connector)throw new Error("no connector");for(let r=1;r<=getBlockRetries;r++)try{return await e.getBlock(this.connector?.net.bstore)}catch(e){await new Promise((e=>setTimeout(e,t))),t*=2}}async readTxn(e,t,r){const n=new Txn(e,r,!0);try{await t(n)}finally{n.discard()}}async writeTxn(e,t,r){const n=this.writeQueue,i=new Promise(((i,o)=>{n.catch((()=>{})).finally((async()=>{const n=new Txn(e,r,!1);try{await t(n),await n.commit(),i()}catch(e){o(e)}finally{n.discard()}}))}));return this.writeQueue=i.catch((()=>Promise.resolve())),i}}function isKeyFilter(e){return"key"===e.$type&&"string"==typeof e.key}function isPrefixFilter(e){return"prefix"===e.$type&&"string"==typeof e.prefix}function createTransformedDatastore(e,t){return new TransformedDatastore(e,t)}class TransformedDatastore extends BaseDatastore{constructor(e,t){super(),Object.defineProperty(this,"child",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"transform",{enumerable:!0,configurable:!0,writable:!0,value:t})}async put(e,t,r){return this.child.put(this.transform.convert(e),t,r)}async get(e,t){return this.child.get(this.transform.convert(e))}async has(e,t){return this.child.has(this.transform.convert(e),t)}async delete(e,t){return this.child.delete(this.transform.convert(e),t)}async beginTransaction(){const e=await this.getTransaction();return new TransformedTransaction(e,this.transform)}async newTransactionExtended(e){const t=await this.getTransaction();return new TransformedTransaction(t,this.transform)}async getTransaction(){if("function"==typeof this.child.newTransactionExtended)return this.child.newTransactionExtended(!1);throw new Error("Transactions not supported by underlying datastore")}async*query(e){const t=this.queryExtended(e);for await(const e of t)yield{key:new Key$1(e.key),value:e.value}}async*queryExtended(e){const t=this.transformQuery(e);for await(const e of this.child.query(t)){const t=this.transform.invert(new Key$1(e.key.toString()));t&&(yield{...e,key:t.toString()})}}transformQuery(e){return FilterProcessor.process(e,this.transform)}}class TransformedTransaction{constructor(e,t){Object.defineProperty(this,"txn",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"transform",{enumerable:!0,configurable:!0,writable:!0,value:t})}async put(e,t){return this.txn.put(this.transform.convert(e),t)}async delete(e){return this.txn.delete(this.transform.convert(e))}async get(e){return this.txn.get(this.transform.convert(e))}async has(e){return this.txn.has(this.transform.convert(e))}async commit(){return this.txn.commit()}discard(){this.txn.discard()}async*query(e){yield*this.queryExtended(e)}async*queryExtended(e){const t=FilterProcessor.process(e,this.transform);for await(const e of this.txn.queryExtended(t)){const t=this.transform.invert(new Key$1(e.key));t&&(yield{...e,key:t.toString()})}}}class FilterProcessor{static process(e,t){const r=structuredClone(e);return r.prefix&&(r.prefix=t.convert(new Key$1(r.prefix)).toString()),r.filters&&(r.filters=r.filters.map((e=>this.transformFilter(e,t)))),r}static transformFilter(e,t){if(isKeyFilter(e)){const r=t.convert(new Key$1(e.key)).toString(),n=function(e){return e.key.toString()===r};return Object.assign(n,{key:r,$type:"key"}),n}if(isPrefixFilter(e)){const r=t.convert(new Key$1(e.prefix)).toString(),n=function(e){return e.key.toString().startsWith(r)};return Object.assign(n,{prefix:r,$type:"prefix"}),n}throw new Error("Unsupported filter type")}static createKeyFilter(e){return t=>t.key.toString()===e}static createPrefixFilter(e){return t=>t.key.toString().startsWith(e)}}class PrefixTransform{constructor(e){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prefix=new Key$1(e)}convert(e){return new Key$1(this.prefix.toString()+e.toString())}invert(e){const t=e.toString(),r=this.prefix.toString();if(!t.startsWith(r))throw new Error("Invalid prefix");return new Key$1(t.slice(r.length))}}const encoder=new TextEncoder,decoder=new TextDecoder;function concat(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=t.reduce(((e,t)=>{let{length:r}=t;return e+r}),0),i=new Uint8Array(n);let o=0;for(const e of t)i.set(e,o),o+=e.length;return i}function encodeBase64(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}function decodeBase64(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function decode(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:decoder.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=decoder.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return decodeBase64(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function encode(e){let t=e;return"string"==typeof t&&(t=encoder.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):encodeBase64(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class JOSEError extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class JWTClaimValidationFailed extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JWTExpired extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JOSENotSupported extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class JWSInvalid extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class JWTInvalid extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class JWSSignatureVerificationFailed extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0)}}function unusable(e){return new TypeError(`CryptoKey does not support this operation, its ${arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name"} must be ${e}`)}function isAlgorithm(e,t){return e.name===t}function getHashLength(e){return parseInt(e.name.slice(4),10)}function getNamedCurve(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function checkUsage(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function checkSigCryptoKey(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!isAlgorithm(e.algorithm,"HMAC"))throw unusable("HMAC");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!isAlgorithm(e.algorithm,"RSASSA-PKCS1-v1_5"))throw unusable("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!isAlgorithm(e.algorithm,"RSA-PSS"))throw unusable("RSA-PSS");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!isAlgorithm(e.algorithm,"Ed25519"))throw unusable("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!isAlgorithm(e.algorithm,"ECDSA"))throw unusable("ECDSA");const r=getNamedCurve(t);if(e.algorithm.namedCurve!==r)throw unusable(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}checkUsage(e,r)}function message(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];if((n=n.filter(Boolean)).length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var invalidKeyInput=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return message("Key must be ",e,...r)};function withAlg(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return message(`Key for the ${e} algorithm must be `,t,...n)}function isCryptoKey(e){return"CryptoKey"===e?.[Symbol.toStringTag]}function isKeyObject(e){return"KeyObject"===e?.[Symbol.toStringTag]}var isKeyLike=e=>isCryptoKey(e)||isKeyObject(e),isDisjoint=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=t.filter(Boolean);if(0===n.length||1===n.length)return!0;let i;for(const e of n){const t=Object.keys(e);if(i&&0!==i.size)for(const e of t){if(i.has(e))return!1;i.add(e)}else i=new Set(t)}return!0};function isObjectLike(e){return"object"==typeof e&&null!==e}var isObject=e=>{if(!isObjectLike(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t},checkKeyLength=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function subtleMapping(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var importJWK=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=subtleMapping(e),n={...e};return delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!e.d,e.key_ops??r)},validateCrit=(e,t,r,n,i)=>{if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)};function isJWK(e){return isObject(e)&&"string"==typeof e.kty}function isPrivateJWK(e){return"oct"!==e.kty&&"string"==typeof e.d}function isPublicJWK(e){return"oct"!==e.kty&&void 0===e.d}function isSecretJWK(e){return"oct"===e.kty&&"string"==typeof e.k}let cache;const handleJWK=async function(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];cache||=new WeakMap;let i=cache.get(e);if(i?.[r])return i[r];const o=await importJWK({...t,alg:r});return n&&Object.freeze(e),i?i[r]=o:cache.set(e,{[r]:o}),o},handleKeyObject=(e,t)=>{cache||=new WeakMap;let r=cache.get(e);if(r?.[t])return r[t];const n="public"===e.type,i=!!n;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,i,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let r;switch(t){case"RSA-OAEP":r="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":r="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":r="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":r="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:r},i,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:r},i,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const r=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!r)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),"ES384"===t&&"P-384"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),"ES512"===t&&"P-521"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:r},i,n?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[t]=o:cache.set(e,{[t]:o}),o};var normalizeKey=async(e,t)=>{if(e instanceof Uint8Array)return e;if(isCryptoKey(e))return e;if(isKeyObject(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return handleKeyObject(e,t)}catch(e){if(e instanceof TypeError)throw e}let r=e.export({format:"jwk"});return handleJWK(e,r,t)}if(isJWK(e))return e.k?decode(e.k):handleJWK(e,e,t,!0);throw new Error("unreachable")};const tag=e=>e?.[Symbol.toStringTag],jwkMatchesOp=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&!1===t.key_ops?.includes?.(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},symmetricTypeCheck=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(isJWK(t)){if(isSecretJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${tag(t)} instances for symmetric algorithms must be of type "secret"`)}},asymmetricTypeCheck=(e,t,r)=>{if(isJWK(t))switch(r){case"decrypt":case"sign":if(isPrivateJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(isPublicJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw new TypeError(`${tag(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${tag(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw new TypeError(`${tag(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${tag(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};var checkKeyType=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?symmetricTypeCheck(e,t,r):asymmetricTypeCheck(e,t,r)},subtleAlgorithm=(e,t)=>{const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};default:throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}},getSignKey=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(invalidKeyInput(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return checkSigCryptoKey(t,e,r),t},verify=async(e,t,r,n)=>{const i=await getSignKey(e,t,"verify");checkKeyLength(e,i);const o=subtleAlgorithm(e,i.algorithm);try{return await crypto.subtle.verify(o,i,r,n)}catch{return!1}};async function flattenedVerify(e,t,r){if(!isObject(e))throw new JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!isObject(e.header))throw new JWSInvalid("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=decode(e.protected);n=JSON.parse(decoder.decode(t))}catch{throw new JWSInvalid("JWS Protected Header is invalid")}if(!isDisjoint(n,e.header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header};let o=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),r?.crit,n,i).has("b64")&&(o=n.b64,"boolean"!=typeof o))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=i;if("string"!=typeof s||!s)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(o){if("string"!=typeof e.payload)throw new JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let a=!1;"function"==typeof t&&(t=await t(n,e),a=!0),checkKeyType(s,t,"verify");const c=concat(encoder.encode(e.protected??""),encoder.encode("."),"string"==typeof e.payload?encoder.encode(e.payload):e.payload);let l;try{l=decode(e.signature)}catch{throw new JWSInvalid("Failed to base64url decode the signature")}const u=await normalizeKey(t,s);if(!await verify(s,u,l,c))throw new JWSSignatureVerificationFailed;let d;if(o)try{d=decode(e.payload)}catch{throw new JWSInvalid("Failed to base64url decode the payload")}else d="string"==typeof e.payload?encoder.encode(e.payload):e.payload;const h={payload:d};return void 0!==e.protected&&(h.protectedHeader=n),void 0!==e.header&&(h.unprotectedHeader=e.header),a?{...h,key:u}:h}async function compactVerify(e,t,r){if(e instanceof Uint8Array&&(e=decoder.decode(e)),"string"!=typeof e)throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(3!==s)throw new JWSInvalid("Invalid Compact JWS");const a=await flattenedVerify({payload:i,protected:n,signature:o},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}var epoch=e=>Math.floor(e.getTime()/1e3);const minute=60,hour=60*minute,day=24*hour,week=7*day,year=365.25*day,REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var secs=e=>{const t=REGEX.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*minute);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*hour);break;case"day":case"days":case"d":n=Math.round(r*day);break;case"week":case"weeks":case"w":n=Math.round(r*week);break;default:n=Math.round(r*year)}return"-"===t[1]||"ago"===t[4]?-n:n};function validateInput(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}const normalizeTyp=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,checkAudiencePresence=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));function validateClaimsSet(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{r=JSON.parse(decoder.decode(t))}catch{}if(!isObject(r))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:i}=n;if(i&&("string"!=typeof e.typ||normalizeTyp(e.typ)!==normalizeTyp(i)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:o=[],issuer:s,subject:a,audience:c,maxTokenAge:l}=n,u=[...o];void 0!==l&&u.push("iat"),void 0!==c&&u.push("aud"),void 0!==a&&u.push("sub"),void 0!==s&&u.push("iss");for(const e of new Set(u.reverse()))if(!(e in r))throw new JWTClaimValidationFailed(`missing required "${e}" claim`,r,e,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(r.iss))throw new JWTClaimValidationFailed('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new JWTClaimValidationFailed('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!checkAudiencePresence(r.aud,"string"==typeof c?[c]:c))throw new JWTClaimValidationFailed('unexpected "aud" claim value',r,"aud","check_failed");let d;switch(typeof n.clockTolerance){case"string":d=secs(n.clockTolerance);break;case"number":d=n.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=n,p=epoch(h||new Date);if((void 0!==r.iat||l)&&"number"!=typeof r.iat)throw new JWTClaimValidationFailed('"iat" claim must be a number',r,"iat","invalid");if(void 0!==r.nbf){if("number"!=typeof r.nbf)throw new JWTClaimValidationFailed('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>p+d)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(void 0!==r.exp){if("number"!=typeof r.exp)throw new JWTClaimValidationFailed('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=p-d)throw new JWTExpired('"exp" claim timestamp check failed',r,"exp","check_failed")}if(l){const e=p-r.iat;if(e-d>("number"==typeof l?l:secs(l)))throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(e<0-d)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}class JWTClaimsBuilder{#He;constructor(e){if(!isObject(e))throw new TypeError("JWT Claims Set MUST be an object");this.#He=structuredClone(e)}data(){return encoder.encode(JSON.stringify(this.#He))}get iss(){return this.#He.iss}set iss(e){this.#He.iss=e}get sub(){return this.#He.sub}set sub(e){this.#He.sub=e}get aud(){return this.#He.aud}set aud(e){this.#He.aud=e}set jti(e){this.#He.jti=e}set nbf(e){"number"==typeof e?this.#He.nbf=validateInput("setNotBefore",e):e instanceof Date?this.#He.nbf=validateInput("setNotBefore",epoch(e)):this.#He.nbf=epoch(new Date)+secs(e)}set exp(e){"number"==typeof e?this.#He.exp=validateInput("setExpirationTime",e):e instanceof Date?this.#He.exp=validateInput("setExpirationTime",epoch(e)):this.#He.exp=epoch(new Date)+secs(e)}set iat(e){void 0===e?this.#He.iat=epoch(new Date):e instanceof Date?this.#He.iat=validateInput("setIssuedAt",epoch(e)):this.#He.iat=validateInput("setIssuedAt","string"==typeof e?epoch(new Date)+secs(e):e)}}async function jwtVerify(e,t,r){const n=await compactVerify(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const i={payload:validateClaimsSet(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}var sign$1=async(e,t,r)=>{const n=await getSignKey(e,t,"sign");checkKeyLength(e,n);const i=await crypto.subtle.sign(subtleAlgorithm(e,n.algorithm),n,r);return new Uint8Array(i)};class FlattenedSign{#He;#ze;#We;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#He=e}setProtectedHeader(e){if(this.#ze)throw new TypeError("setProtectedHeader can only be called once");return this.#ze=e,this}setUnprotectedHeader(e){if(this.#We)throw new TypeError("setUnprotectedHeader can only be called once");return this.#We=e,this}async sign(e,t){if(!this.#ze&&!this.#We)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!isDisjoint(this.#ze,this.#We))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#ze,...this.#We};let n=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,this.#ze,r).has("b64")&&(n=this.#ze.b64,"boolean"!=typeof n))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');checkKeyType(i,e,"sign");let o,s=this.#He;n&&(s=encoder.encode(encode(s))),o=this.#ze?encoder.encode(encode(JSON.stringify(this.#ze))):encoder.encode("");const a=concat(o,encoder.encode("."),s),c=await normalizeKey(e,i),l={signature:encode(await sign$1(i,c,a)),payload:""};return n&&(l.payload=decoder.decode(s)),this.#We&&(l.header=this.#We),this.#ze&&(l.protected=decoder.decode(o)),l}}class CompactSign{#Ge;constructor(e){this.#Ge=new FlattenedSign(e)}setProtectedHeader(e){return this.#Ge.setProtectedHeader(e),this}async sign(e,t){const r=await this.#Ge.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}class SignJWT{#ze;#Xe;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.#Xe=new JWTClaimsBuilder(e)}setIssuer(e){return this.#Xe.iss=e,this}setSubject(e){return this.#Xe.sub=e,this}setAudience(e){return this.#Xe.aud=e,this}setJti(e){return this.#Xe.jti=e,this}setNotBefore(e){return this.#Xe.nbf=e,this}setExpirationTime(e){return this.#Xe.exp=e,this}setIssuedAt(e){return this.#Xe.iat=e,this}setProtectedHeader(e){return this.#ze=e,this}async sign(e,t){const r=new CompactSign(this.#Xe.data());if(r.setProtectedHeader(this.#ze),Array.isArray(this.#ze?.crit)&&this.#ze.crit.includes("b64")&&!1===this.#ze.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";class ThreadToken{constructor(e){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:e})}static async issue(e,t){const r=await ed25519PrivateKeyToCryptoKey(e.privateKey.raw);return new ThreadToken(await new SignJWT({sub:t.toString(),iss:e.getPublic().toString()}).setProtectedHeader({alg:"EdDSA"}).setIssuedAt().sign(r))}async pubKey(){if(this.value)try{const e=jwtDecode(this.value);if(!e.sub)throw new Error("Token subject is missing");try{return Ed25519PubKey.unmarshalString(e.sub)}catch(e){throw new Error(`Failed to unmarshal public key: ${e instanceof Error?e.message:String(e)}`)}}catch(e){throw e instanceof Error&&e.message.includes("Invalid token")?new Error("Invalid token format"):new Error("Token not found or invalid")}}async validate(e){try{const t=await ed25519PrivateKeyToCryptoKey(e.raw,"raw"),{payload:r}=await jwtVerify(this.value,t);return this.parsePubKey(r.sub)}catch{return}}parsePubKey(e){return new Ed25519PubKey(base32$5.decode(e))}get defined(){return this.value.length>0}}new Headers;const ErrInvalidQueryConditionFormat=new Error("无效的查询条件格式");function parseJsonToQuery(e){const t={condition:"",ors:[],sort:{},seek:"",limit:0,skip:0,index:""};""===e&&(e="{}");try{return Object.assign(t,JSON.parse(e)),dcQueryToDbQuery(t)}catch(e){throw new Error(`解析查询JSON失败: ${e instanceof Error?e.message:String(e)}`)}}function dcQueryToDbQuery(e){try{const t=parseCondition(e.condition),r=new Query;return r.ands=t,r.sort=e.sort,r.seek=e.seek,r.limit=e.limit,r.skip=e.skip,r.index=e.index,r.ors=[],r.ors=e.ors?.map((e=>dcQueryToDbQuery(e)))||[],0===r.limit&&(r.limit=-1),r}catch(e){throw new Error(`转换查询对象失败: ${e instanceof Error?e.message:String(e)}`)}}function parseCondition(e){if(!e)return[];const t=e.split(" and "),r=[];for(const e of t)try{const t=parseSingleCondition(e);if(!t||3!==t.length)continue;const n=parseValue(t[2]),i=new Criterion(t[0],getDbQueryOperation(t[1]),n);r.push(i)}catch(e){continue}return r}function parseValue(e){const t=new Value;if("'"===e[0]||'"'===e[0]){const r=e.substring(1,e.length-1);t.string=r}else if("true"===e||"false"===e){const r="true"===e;t.bool=r}else{const r=parseFloat(e);if(isNaN(r))throw new Error(`无效的数字格式: ${e}`);t.float=r}return t}const splitOp=["!=",">=","<=","=","<>",">","<"];function parseSingleCondition(e){for(const t of splitOp){const r=e.indexOf(t);if(r>0){const n=e.indexOf("'"),i=e.indexOf('"');if(n>0&&r>n||i>0&&r>i)continue;const o=new Array(3);return o[0]=e.substring(0,r).trim(),o[1]=t.trim(),o[2]=e.substring(r+t.length).trim(),o}}throw ErrInvalidQueryConditionFormat}function getDbQueryOperation(e){switch(e.trim()){case"=":default:return Operation.eq;case"!=":case"<>":return Operation.ne;case">":return Operation.gt;case"<":return Operation.lt;case">=":return Operation.ge;case"<=":return Operation.le}}var src$1={exports:{}},src,hasRequiredSrc$1;function requireSrc$1(){if(hasRequiredSrc$1)return src;return hasRequiredSrc$1=1,src=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),o=i.charCodeAt(0);if(255!==t[o])throw new TypeError(i+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),l=Math.log(256)/Math.log(s);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var r=0;if(" "!==e[r]){for(var n=0,i=0;e[r]===a;)n++,r++;for(var o=(e.length-r)*c+1>>>0,l=new Uint8Array(o);e[r];){var u=t[e.charCodeAt(r)];if(255===u)return;for(var d=0,h=o-1;(0!==u||d<i)&&-1!==h;h--,d++)u+=s*l[h]>>>0,l[h]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");i=d,r++}if(" "!==e[r]){for(var p=o-i;p!==o&&0===l[p];)p++;for(var f=new Uint8Array(n+(o-p)),y=n;p!==o;)f[y++]=l[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var c=(o-i)*l+1>>>0,u=new Uint8Array(c);i!==o;){for(var d=t[i],h=0,p=c-1;(0!==d||h<n)&&-1!==p;p--,h++)d+=256*u[p]>>>0,u[p]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var f=c-n;f!==c&&0===u[f];)f++;for(var y=a.repeat(r);f<c;++f)y+=e.charAt(u[f]);return y},decodeUnsafe:u,decode:function(e){var t=u(e);if(t)return t;throw new Error("Non-base"+s+" character")}}},src}var lib={},util$1={},types={},shams$1,hasRequiredShams$1,shams,hasRequiredShams,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,callBound,hasRequiredCallBound,isArguments,hasRequiredIsArguments,isRegex,hasRequiredIsRegex,safeRegexTest,hasRequiredSafeRegexTest,isGeneratorFunction,hasRequiredIsGeneratorFunction,isCallable,hasRequiredIsCallable,forEach,hasRequiredForEach,possibleTypedArrayNames,hasRequiredPossibleTypedArrayNames,availableTypedArrays,hasRequiredAvailableTypedArrays;function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0})}function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN||(hasRequired_isNaN=1,_isNaN=Number.isNaN||function(e){return e!=e}),_isNaN}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var e=require_isNaN();return sign=function(t){return e(t)||0===t?t:t<0?-1:1},sign}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var e=requireGOPD();if(e)try{e([],"length")}catch(t){e=null}return gopd=e}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return esDefineProperty=e}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var e="undefined"!=typeof Symbol&&Symbol,t=requireShams$1();return hasSymbols=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"==typeof e("foo")&&("symbol"==typeof Symbol("bar")&&t())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var o,s=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),a=t(0,i.length-s.length),c=[],l=0;l<a;l++)c[l]="$"+l;if(o=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof o){var e=i.apply(this,r(s,arguments));return Object(e)===e?e:this}return i.apply(n,r(s,arguments))})),i.prototype){var u=function(){};u.prototype=i.prototype,o.prototype=new u,u.prototype=null}return o},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireFunctionCall(),n=requireReflectApply();return actualApply=n||e.call(r,t)}function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var e=requireFunctionBind(),t=requireType(),r=requireFunctionCall(),n=requireActualApply();return callBindApplyHelpers=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var e,t=requireCallBindApplyHelpers(),r=requireGopd();try{e=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return get=n&&"function"==typeof n.get?t([n.get]):"function"==typeof o&&function(e){return o(null==e?e:i(e))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var e=requireReflect_getPrototypeOf(),t=requireObject_getPrototypeOf(),r=requireGet();return getProto=e?function(t){return e(t)}:t?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null,getProto}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;var e;hasRequiredGetIntrinsic=1;var t=requireEsObjectAtoms(),r=requireEsErrors(),n=require_eval(),i=requireRange(),o=requireRef(),s=requireSyntax(),a=requireType(),c=requireUri(),l=requireAbs(),u=requireFloor(),d=requireMax(),h=requireMin(),p=requirePow(),f=requireRound(),y=requireSign(),g=Function,b=function(e){try{return g('"use strict"; return ('+e+").constructor;")()}catch(e){}},m=requireGopd(),w=requireEsDefineProperty(),v=function(){throw new a},S=m?function(){try{return v}catch(e){try{return m(arguments,"callee").get}catch(e){return v}}}():v,$=requireHasSymbols()(),x=requireGetProto(),E=requireObject_getPrototypeOf(),A=requireReflect_getPrototypeOf(),P=requireFunctionApply(),k=requireFunctionCall(),I={},T="undefined"!=typeof Uint8Array&&x?x(Uint8Array):e,O={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":$&&x?x([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":I,"%AsyncGenerator%":I,"%AsyncGeneratorFunction%":I,"%AsyncIteratorPrototype%":I,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?e:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":I,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":$&&x?x(x([][Symbol.iterator]())):e,"%JSON%":"object"==typeof JSON?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&$&&x?x((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":m,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&$&&x?x((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":$&&x?x(""[Symbol.iterator]()):e,"%Symbol%":$?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":S,"%TypedArray%":T,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":P,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":E,"%Math.abs%":l,"%Math.floor%":u,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":y,"%Reflect.getPrototypeOf%":A};if(x)try{null.error}catch(e){var _=x(x(e));O["%Error.prototype%"]=_}var C=function e(t){var r;if("%AsyncFunction%"===t)r=b("async function () {}");else if("%GeneratorFunction%"===t)r=b("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=b("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&x&&(r=x(i.prototype))}return O[t]=r,r},R={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},B=requireFunctionBind(),D=requireHasown(),N=B.call(k,Array.prototype.concat),M=B.call(P,Array.prototype.splice),j=B.call(k,String.prototype.replace),L=B.call(k,String.prototype.slice),U=B.call(k,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,V=function(e,t){var r,n=e;if(D(R,n)&&(n="%"+(r=R[n])[0]+"%"),D(O,n)){var i=O[n];if(i===I&&(i=C(n)),void 0===i&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new s("intrinsic "+e+" does not exist!")};return getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');if(null===U(/^%?[^%]*%?$/,e))throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=L(e,0,1),r=L(e,-1);if("%"===t&&"%"!==r)throw new s("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new s("invalid intrinsic syntax, expected opening `%`");var n=[];return j(e,q,(function(e,t,r,i){n[n.length]=r?j(i,F,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",i=V("%"+n+"%",t),o=i.name,c=i.value,l=!1,u=i.alias;u&&(n=u[0],M(r,N([0,1],u)));for(var d=1,h=!0;d<r.length;d+=1){var p=r[d],f=L(p,0,1),y=L(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===y||"'"===y||"`"===y)&&f!==y)throw new s("property names with quotes must have matching quotes");if("constructor"!==p&&h||(l=!0),D(O,o="%"+(n+="."+p)+"%"))c=O[o];else if(null!=c){if(!(p in c)){if(!t)throw new a("base intrinsic for "+e+" exists, but the property is not available.");return}if(m&&d+1>=r.length){var g=m(c,p);c=(h=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:c[p]}else h=D(c,p),c=c[p];h&&!l&&(O[o]=c)}}return c},getIntrinsic}function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var e=requireGetIntrinsic(),t=requireCallBindApplyHelpers(),r=t([e("%String.prototype.indexOf%")]);return callBound=function(n,i){var o=e(n,!!i);return"function"==typeof o&&r(n,".prototype.")>-1?t([o]):o},callBound}function requireIsArguments(){if(hasRequiredIsArguments)return isArguments;hasRequiredIsArguments=1;var e=requireShams()(),t=requireCallBound()("Object.prototype.toString"),r=function(r){return!(e&&r&&"object"==typeof r&&Symbol.toStringTag in r)&&"[object Arguments]"===t(r)},n=function(e){return!!r(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==t(e)&&"callee"in e&&"[object Function]"===t(e.callee)},i=function(){return r(arguments)}();return r.isLegacyArguments=n,isArguments=i?r:n}function requireIsRegex(){if(hasRequiredIsRegex)return isRegex;hasRequiredIsRegex=1;var e,t=requireCallBound(),r=requireShams()(),n=requireHasown(),i=requireGopd();if(r){var o=t("RegExp.prototype.exec"),s={},a=function(){throw s},c={toString:a,valueOf:a};"symbol"==typeof Symbol.toPrimitive&&(c[Symbol.toPrimitive]=a),e=function(e){if(!e||"object"!=typeof e)return!1;var t=i(e,"lastIndex");if(!(t&&n(t,"value")))return!1;try{o(e,c)}catch(e){return e===s}}}else{var l=t("Object.prototype.toString");e=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&"[object RegExp]"===l(e)}}return isRegex=e}function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest;hasRequiredSafeRegexTest=1;var e=requireCallBound(),t=requireIsRegex(),r=e("RegExp.prototype.exec"),n=requireType();return safeRegexTest=function(e){if(!t(e))throw new n("`regex` must be a RegExp");return function(t){return null!==r(e,t)}},safeRegexTest}function requireIsGeneratorFunction(){if(hasRequiredIsGeneratorFunction)return isGeneratorFunction;hasRequiredIsGeneratorFunction=1;var e,t=requireCallBound(),r=requireSafeRegexTest()(/^\s*(?:function)?\*/),n=requireShams()(),i=requireGetProto(),o=t("Object.prototype.toString"),s=t("Function.prototype.toString");return isGeneratorFunction=function(t){if("function"!=typeof t)return!1;if(r(s(t)))return!0;if(!n)return"[object GeneratorFunction]"===o(t);if(!i)return!1;if(void 0===e){var a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch(e){}}();e=!!a&&i(a)}return i(t)===e}}function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;var e,t,r=Function.prototype.toString,n="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof n&&"function"==typeof Object.defineProperty)try{e=Object.defineProperty({},"length",{get:function(){throw t}}),t={},n((function(){throw 42}),null,e)}catch(e){e!==t&&(n=null)}else n=null;var i=/^\s*class\b/,o=function(e){try{var t=r.call(e);return i.test(t)}catch(e){return!1}},s=function(e){try{return!o(e)&&(r.call(e),!0)}catch(e){return!1}},a=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),u=function(){return!1};if("object"==typeof document){var d=document.all;a.call(d)===a.call(document.all)&&(u=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=a.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}return isCallable=n?function(r){if(u(r))return!0;if(!r)return!1;if("function"!=typeof r&&"object"!=typeof r)return!1;try{n(r,null,e)}catch(e){if(e!==t)return!1}return!o(r)&&s(r)}:function(e){if(u(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return s(e);if(o(e))return!1;var t=a.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)},isCallable}function requireForEach(){if(hasRequiredForEach)return forEach;hasRequiredForEach=1;var e=requireIsCallable(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty;return forEach=function(n,i,o){if(!e(i))throw new TypeError("iterator must be a function");var s;arguments.length>=3&&(s=o),function(e){return"[object Array]"===t.call(e)}(n)?function(e,t,n){for(var i=0,o=e.length;i<o;i++)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,s):"string"==typeof n?function(e,t,r){for(var n=0,i=e.length;n<i;n++)null==r?t(e.charAt(n),n,e):t.call(r,e.charAt(n),n,e)}(n,i,s):function(e,t,n){for(var i in e)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,s)},forEach}function requirePossibleTypedArrayNames(){return hasRequiredPossibleTypedArrayNames?possibleTypedArrayNames:(hasRequiredPossibleTypedArrayNames=1,possibleTypedArrayNames=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"])}function requireAvailableTypedArrays(){if(hasRequiredAvailableTypedArrays)return availableTypedArrays;hasRequiredAvailableTypedArrays=1;var e=requirePossibleTypedArrayNames(),t="undefined"==typeof globalThis?commonjsGlobal:globalThis;return availableTypedArrays=function(){for(var r=[],n=0;n<e.length;n++)"function"==typeof t[e[n]]&&(r[r.length]=e[n]);return r},availableTypedArrays}var callBind={exports:{}},defineDataProperty,hasRequiredDefineDataProperty,hasPropertyDescriptors_1,hasRequiredHasPropertyDescriptors,setFunctionLength,hasRequiredSetFunctionLength,applyBind,hasRequiredApplyBind,hasRequiredCallBind,whichTypedArray,hasRequiredWhichTypedArray,isTypedArray,hasRequiredIsTypedArray,hasRequiredTypes,isBufferBrowser,hasRequiredIsBufferBrowser;function requireDefineDataProperty(){if(hasRequiredDefineDataProperty)return defineDataProperty;hasRequiredDefineDataProperty=1;var e=requireEsDefineProperty(),t=requireSyntax(),r=requireType(),n=requireGopd();return defineDataProperty=function(i,o,s){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!n&&n(i,o);if(e)e(i,o,{configurable:null===l&&d?d.configurable:!l,enumerable:null===a&&d?d.enumerable:!a,value:s,writable:null===c&&d?d.writable:!c});else{if(!u&&(a||c||l))throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[o]=s}},defineDataProperty}function requireHasPropertyDescriptors(){if(hasRequiredHasPropertyDescriptors)return hasPropertyDescriptors_1;hasRequiredHasPropertyDescriptors=1;var e=requireEsDefineProperty(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return 1!==e([],"length",{value:1}).length}catch(e){return!0}},hasPropertyDescriptors_1=t}function requireSetFunctionLength(){if(hasRequiredSetFunctionLength)return setFunctionLength;hasRequiredSetFunctionLength=1;var e=requireGetIntrinsic(),t=requireDefineDataProperty(),r=requireHasPropertyDescriptors()(),n=requireGopd(),i=requireType(),o=e("%Math.floor%");return setFunctionLength=function(e,s){if("function"!=typeof e)throw new i("`fn` is not a function");if("number"!=typeof s||s<0||s>4294967295||o(s)!==s)throw new i("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,l=!0;if("length"in e&&n){var u=n(e,"length");u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!a)&&(r?t(e,"length",s,!0,!0):t(e,"length",s)),e},setFunctionLength}function requireApplyBind(){if(hasRequiredApplyBind)return applyBind;hasRequiredApplyBind=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireActualApply();return applyBind=function(){return r(e,t,arguments)},applyBind}function requireCallBind(){return hasRequiredCallBind||(hasRequiredCallBind=1,function(e){var t=requireSetFunctionLength(),r=requireEsDefineProperty(),n=requireCallBindApplyHelpers(),i=requireApplyBind();e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(callBind)),callBind.exports}function requireWhichTypedArray(){if(hasRequiredWhichTypedArray)return whichTypedArray;hasRequiredWhichTypedArray=1;var e=requireForEach(),t=requireAvailableTypedArrays(),r=requireCallBind(),n=requireCallBound(),i=requireGopd(),o=requireGetProto(),s=n("Object.prototype.toString"),a=requireShams()(),c="undefined"==typeof globalThis?commonjsGlobal:globalThis,l=t(),u=n("String.prototype.slice"),d=n("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r<e.length;r+=1)if(e[r]===t)return r;return-1},h={__proto__:null};e(l,a&&i&&o?function(e){var t=new c[e];if(Symbol.toStringTag in t&&o){var n=o(t),s=i(n,Symbol.toStringTag);if(!s&&n){var a=o(n);s=i(a,Symbol.toStringTag)}h["$"+e]=r(s.get)}}:function(e){var t=new c[e],n=t.slice||t.set;n&&(h["$"+e]=r(n))});return whichTypedArray=function(t){if(!t||"object"!=typeof t)return!1;if(!a){var r=u(s(t),8,-1);return d(l,r)>-1?r:"Object"===r&&function(t){var r=!1;return e(h,(function(e,n){if(!r)try{e(t),r=u(n,1)}catch(e){}})),r}(t)}return i?function(t){var r=!1;return e(h,(function(e,n){if(!r)try{"$"+e(t)===n&&(r=u(n,1))}catch(e){}})),r}(t):null},whichTypedArray}function requireIsTypedArray(){if(hasRequiredIsTypedArray)return isTypedArray;hasRequiredIsTypedArray=1;var e=requireWhichTypedArray();return isTypedArray=function(t){return!!e(t)}}function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(e){var t=requireIsArguments(),r=requireIsGeneratorFunction(),n=requireWhichTypedArray(),i=requireIsTypedArray();function o(e){return e.call.bind(e)}var s="undefined"!=typeof BigInt,a="undefined"!=typeof Symbol,c=o(Object.prototype.toString),l=o(Number.prototype.valueOf),u=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(s)var h=o(BigInt.prototype.valueOf);if(a)var p=o(Symbol.prototype.valueOf);function f(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function y(e){return"[object Map]"===c(e)}function g(e){return"[object Set]"===c(e)}function b(e){return"[object WeakMap]"===c(e)}function m(e){return"[object WeakSet]"===c(e)}function w(e){return"[object ArrayBuffer]"===c(e)}function v(e){return"undefined"!=typeof ArrayBuffer&&(w.working?w(e):e instanceof ArrayBuffer)}function S(e){return"[object DataView]"===c(e)}function $(e){return"undefined"!=typeof DataView&&(S.working?S(e):e instanceof DataView)}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i,e.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},e.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||$(e)},e.isUint8Array=function(e){return"Uint8Array"===n(e)},e.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===n(e)},e.isUint16Array=function(e){return"Uint16Array"===n(e)},e.isUint32Array=function(e){return"Uint32Array"===n(e)},e.isInt8Array=function(e){return"Int8Array"===n(e)},e.isInt16Array=function(e){return"Int16Array"===n(e)},e.isInt32Array=function(e){return"Int32Array"===n(e)},e.isFloat32Array=function(e){return"Float32Array"===n(e)},e.isFloat64Array=function(e){return"Float64Array"===n(e)},e.isBigInt64Array=function(e){return"BigInt64Array"===n(e)},e.isBigUint64Array=function(e){return"BigUint64Array"===n(e)},y.working="undefined"!=typeof Map&&y(new Map),e.isMap=function(e){return"undefined"!=typeof Map&&(y.working?y(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),e.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),e.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},m.working="undefined"!=typeof WeakSet&&m(new WeakSet),e.isWeakSet=function(e){return m(e)},w.working="undefined"!=typeof ArrayBuffer&&w(new ArrayBuffer),e.isArrayBuffer=v,S.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&S(new DataView(new ArrayBuffer(1),0,1)),e.isDataView=$;var x="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function E(e){return"[object SharedArrayBuffer]"===c(e)}function A(e){return void 0!==x&&(void 0===E.working&&(E.working=E(new x)),E.working?E(e):e instanceof x)}function P(e){return f(e,l)}function k(e){return f(e,u)}function I(e){return f(e,d)}function T(e){return s&&f(e,h)}function O(e){return a&&f(e,p)}e.isSharedArrayBuffer=A,e.isAsyncFunction=function(e){return"[object AsyncFunction]"===c(e)},e.isMapIterator=function(e){return"[object Map Iterator]"===c(e)},e.isSetIterator=function(e){return"[object Set Iterator]"===c(e)},e.isGeneratorObject=function(e){return"[object Generator]"===c(e)},e.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===c(e)},e.isNumberObject=P,e.isStringObject=k,e.isBooleanObject=I,e.isBigIntObject=T,e.isSymbolObject=O,e.isBoxedPrimitive=function(e){return P(e)||k(e)||I(e)||T(e)||O(e)},e.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(v(e)||A(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw new Error(t+" is not supported in userland")}})}))}(types)),types}function requireIsBufferBrowser(){return hasRequiredIsBufferBrowser?isBufferBrowser:(hasRequiredIsBufferBrowser=1,isBufferBrowser=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8})}var inherits_browser={exports:{}},hasRequiredInherits_browser,hasRequiredUtil$1,hasRequiredLib,util,hasRequiredUtil,base,hasRequiredBase,rfc4648_1,hasRequiredRfc4648,constants_1,hasRequiredConstants,hasRequiredSrc;function requireInherits_browser(){return hasRequiredInherits_browser||(hasRequiredInherits_browser=1,"function"==typeof Object.create?inherits_browser.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),inherits_browser.exports}function requireUtil$1(){return hasRequiredUtil$1||(hasRequiredUtil$1=1,function(e){var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},r=/%[sdj%]/g;e.format=function(e){if(!g(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(s(arguments[n]));return t.join(" ")}n=1;for(var i=arguments,o=i.length,a=String(e).replace(r,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(e){return"[Circular]"}default:return e}})),c=i[n];n<o;c=i[++n])f(c)||!w(c)?a+=" "+c:a+=" "+s(c);return a},e.deprecate=function(t,r){if("undefined"!=typeof process&&!0===process.noDeprecation)return t;if("undefined"==typeof process)return function(){return e.deprecate(t,r).apply(this,arguments)};var n=!1;return function(){if(!n){if(process.throwDeprecation)throw new Error(r);process.traceDeprecation,n=!0}return t.apply(this,arguments)}};var n={},i=/^$/;if(process.env.NODE_DEBUG){var o=process.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}function s(t,r){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(r)?n.showHidden=r:r&&e._extend(n,r),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=a),l(n,t,n.depth)}function a(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function l(t,r,n){if(t.customInspect&&r&&$(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return g(i)||(i=l(t,i,n)),i}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(f(t))return e.stylize("null","null")}(t,r);if(o)return o;var s=Object.keys(r),a=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),S(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return u(r);if(0===s.length){if($(r)){var c=r.name?": "+r.name:"";return t.stylize("[Function"+c+"]","special")}if(m(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(v(r))return t.stylize(Date.prototype.toString.call(r),"date");if(S(r))return u(r)}var w,x="",A=!1,P=["{","}"];(h(r)&&(A=!0,P=["[","]"]),$(r))&&(x=" [Function"+(r.name?": "+r.name:"")+"]");return m(r)&&(x=" "+RegExp.prototype.toString.call(r)),v(r)&&(x=" "+Date.prototype.toUTCString.call(r)),S(r)&&(x=" "+u(r)),0!==s.length||A&&0!=r.length?n<0?m(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),w=A?function(e,t,r,n,i){for(var o=[],s=0,a=t.length;s<a;++s)E(t,String(s))?o.push(d(e,t,r,n,String(s),!0)):o.push("");return i.forEach((function(i){i.match(/^\d+$/)||o.push(d(e,t,r,n,i,!0))})),o}(t,r,n,a,s):s.map((function(e){return d(t,r,n,a,e,A)})),t.seen.pop(),function(e,t,r){var n=e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(w,x,P)):P[0]+x+P[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),E(n,i)||(s="["+i+"]"),a||(e.seen.indexOf(c.value)<0?(a=f(r)?l(e,c.value,null):l(e,c.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.slice(1,-1),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function y(e){return"number"==typeof e}function g(e){return"string"==typeof e}function b(e){return void 0===e}function m(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function v(e){return w(e)&&"[object Date]"===x(e)}function S(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function $(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}e.debuglog=function(t){if(t=t.toUpperCase(),!n[t])if(i.test(t)){process.pid;n[t]=function(){e.format.apply(e,arguments)}}else n[t]=function(){};return n[t]},e.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.types=requireTypes(),e.isArray=h,e.isBoolean=p,e.isNull=f,e.isNullOrUndefined=function(e){return null==e},e.isNumber=y,e.isString=g,e.isSymbol=function(e){return"symbol"==typeof e},e.isUndefined=b,e.isRegExp=m,e.types.isRegExp=m,e.isObject=w,e.isDate=v,e.types.isDate=v,e.isError=S,e.types.isNativeError=S,e.isFunction=$,e.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},e.isBuffer=requireIsBufferBrowser();function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.log=function(){},e.inherits=requireInherits_browser(),e._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var A="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function P(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}e.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(A&&e[A]){var r;if("function"!=typeof(r=e[A]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(r,A,{value:r,enumerable:!1,writable:!1,configurable:!0}),r}function r(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push((function(e,n){e?r(e):t(n)}));try{e.apply(this,i)}catch(e){r(e)}return n}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),A&&Object.defineProperty(r,A,{value:r,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(r,t(e))},e.promisify.custom=A,e.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function r(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var n=t.pop();if("function"!=typeof n)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return n.apply(i,arguments)};e.apply(this,t).then((function(e){process.nextTick(o.bind(null,null,e))}),(function(e){process.nextTick(P.bind(null,e,o))}))}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),Object.defineProperties(r,t(e)),r}}(util$1)),util$1}function requireLib(){return hasRequiredLib||(hasRequiredLib=1,lib.TextEncoder="undefined"!=typeof TextEncoder?TextEncoder:requireUtil$1().TextEncoder,lib.TextDecoder="undefined"!=typeof TextDecoder?TextDecoder:requireUtil$1().TextDecoder),lib}function requireUtil(){if(hasRequiredUtil)return util;hasRequiredUtil=1;const{TextEncoder:e,TextDecoder:t}=requireLib(),r=new t,n=new e;return util={decodeText:e=>r.decode(e),encodeText:e=>n.encode(e),concat:function(e,t){const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}},util}function requireBase(){if(hasRequiredBase)return base;hasRequiredBase=1;const{encodeText:e}=requireUtil();return base=class{constructor(t,r,n,i){this.name=t,this.code=r,this.codeBuf=e(this.code),this.alphabet=i,this.codec=n(i)}encode(e){return this.codec.encode(e)}decode(e){for(const t of e)if(this.alphabet&&this.alphabet.indexOf(t)<0)throw new Error(`invalid character '${t}' in '${e}'`);return this.codec.decode(e)}},base}function requireRfc4648(){if(hasRequiredRfc4648)return rfc4648_1;hasRequiredRfc4648=1;return rfc4648_1={rfc4648:e=>t=>({encode:r=>((e,t,r)=>{const n="="===t[t.length-1],i=(1<<r)-1;let o="",s=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],s+=8;s>r;)s-=r,o+=t[i&a>>s];if(s&&(o+=t[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o})(r,t,e),decode:r=>((e,t,r)=>{const n={};for(let e=0;e<t.length;++e)n[t[e]]=e;let i=e.length;for(;"="===e[i-1];)--i;const o=new Uint8Array(i*r/8|0);let s=0,a=0,c=0;for(let t=0;t<i;++t){const i=n[e[t]];if(void 0===i)throw new SyntaxError("Invalid character "+e[t]);a=a<<r|i,s+=r,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=r||255&a<<8-s)throw new SyntaxError("Unexpected end of data");return o})(r,t,e)})},rfc4648_1}function requireConstants(){if(hasRequiredConstants)return constants_1;hasRequiredConstants=1;const e=requireSrc$1(),t=requireBase(),{rfc4648:r}=requireRfc4648(),{decodeText:n,encodeText:i}=requireUtil(),o=[["identity","\0",()=>({encode:n,decode:i}),""],["base2","0",r(1),"01"],["base8","7",r(3),"01234567"],["base10","9",e,"0123456789"],["base16","f",r(4),"0123456789abcdef"],["base16upper","F",r(4),"0123456789ABCDEF"],["base32hex","v",r(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",r(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",r(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",r(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",r(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",r(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",r(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",r(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",r(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",e,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",e,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",e,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",e,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],s=o.reduce(((e,r)=>(e[r[0]]=new t(r[0],r[1],r[2],r[3]),e)),{}),a=o.reduce(((e,t)=>(e[t[1]]=s[t[0]],e)),{});return constants_1={names:s,codes:a}}function requireSrc(){return hasRequiredSrc||(hasRequiredSrc=1,function(e,t){const r=requireConstants(),{encodeText:n,decodeText:i,concat:o}=requireUtil();function s(e){if(Object.prototype.hasOwnProperty.call(r.names,e))return r.names[e];if(Object.prototype.hasOwnProperty.call(r.codes,e))return r.codes[e];throw new Error(`Unsupported encoding: ${e}`)}t=e.exports=function(e,t){if(!t)throw new Error("requires an encoded Uint8Array");const{name:r,codeBuf:n}=s(e);return function(e,t){const r=s(e);r.decode(i(t))}(r,t),o([n,t],n.length+t.length)},t.encode=function(e,t){const r=s(e),i=n(r.encode(t));return o([r.codeBuf,i],r.codeBuf.length+i.length)},t.decode=function(e){e instanceof Uint8Array&&(e=i(e));const t=e[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(t)&&(e=e.toLowerCase()),s(e[0]).decode(e.substring(1))},t.isEncoded=function(e){if(e instanceof Uint8Array&&(e=i(e)),"[object String]"!==Object.prototype.toString.call(e))return!1;try{return s(e[0]).name}catch(e){return!1}},t.encoding=s,t.encodingFromData=function(e){return e instanceof Uint8Array&&(e=i(e)),s(e[0])},t.names=Object.freeze(r.names),t.codes=Object.freeze(r.codes)}(src$1,src$1.exports)),src$1.exports}var srcExports=requireSrc(),multibase=getDefaultExportFromCjs(srcExports);class LineReader{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf-8";Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"textDecoder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"isEOF",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.reader=e.getReader(),this.textDecoder=new TextDecoder(t)}async readLine(){if(this.isEOF&&0===this.buffer.length)return null;const e=this.buffer.indexOf("\n");if(-1!==e){const t=this.buffer.substring(0,e);return this.buffer=this.buffer.substring(e+1),t}if(!this.isEOF){const{value:e,done:t}=await this.reader.read();if(t){if(this.isEOF=!0,this.buffer.length>0){const e=this.buffer;return this.buffer="",e}return null}return this.buffer+=this.textDecoder.decode(e,{stream:!0}),this.readLine()}if(this.buffer.length>0){const e=this.buffer;return this.buffer="",e}return null}release(){this.reader.releaseLock()}}const{Buffer:Buffer$1}=buffer$1;Protocol.name,Protocol.version;const dsManagerBaseKey=new Key$1("/manager");function newGrpcClient(e,t){if(null==e.p2pNode||null==e.p2pNode.peerId)throw new Error("p2pNode is null or node privateKey is null");return new DBGrpcClient(e.p2pNode,e.peerAddr,e.token,t,e.protocol)}class DBManager{constructor(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=arguments.length>5?arguments[5]:void 0,s=arguments.length>6?arguments[6]:void 0,a=arguments.length>7?arguments[7]:void 0;Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"network",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"storagePrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.store=e,this.network=t,this.dc=r,this.storagePrefix=s,this.opts=i,this.dbs=new Map,this.lock=new AsyncLock,this.chainUtil=o,this.connectedDc=n,this.context=a}async loadDbs(){try{const e={prefix:dsManagerBaseKey.toString(),keysOnly:!0},t=this.store.query(e),r=new Map;for await(const e of t)try{const t=e.key.toString().split("/");if(t.length<3)continue;const n=q.fromString(t[2]||"");if(r.has(n.toString()))continue;r.set(n.toString(),!0);const[i,o,s]=await this.wrapDB(this.store,n,this.opts,"",[]);if(s)continue;const a=await DB.newDB(i,this.network,n,o);this.dbs.set(n.toString(),a)}catch(e){}}catch(e){throw e}}async getLogKey(e){const t=`${this.storagePrefix}_${e.toString()}_logkey`;try{const e=await this.store.get(new Key$1(t));if(e){return Ed25519PrivKey.fromString(Buffer$1.from(e).toString("hex"))}{const e=await this.newLogKey();return this.store.put(new Key$1(t),Buffer$1.from(e.raw)),e}}catch(e){if("ERR_NOT_FOUND"===e.code){const e=await this.newLogKey();return this.store.put(new Key$1(t),Buffer$1.from(e.raw)),e}throw new Error(`Failed to get/create log key: ${e}`)}}async newLogKey(){try{const e=await generateKeyPair("Ed25519");return new Ed25519PrivKey(e.raw)}catch(e){throw new Error(`Failed to generate log key: ${e}`)}}static fromAddr(e){try{const t=e.toString().split("/"),r=t.indexOf(Protocol.name);if(-1===r||r===t.length-1)throw new Error("thread protocol not found in multiaddr");const n=t[r+1]||"";return q.fromString(n)}catch(e){throw new Error(`Failed to extract ID from multiaddr: ${e.message}`)}}toAddr(){try{return multiaddr(`/${Protocol.name}/${this.toString()}`)}catch(e){throw new Error(`Failed to create multiaddr: ${e.message}`)}}async newDBFromAddr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=e.id;return await this.lock.acquire("dbs",(async()=>{if(this.dbs.has(n.toString()))throw Errors$6.ErrDBExists;if(r.name&&!isValidName(r.name))throw Errors$6.ErrInvalidName;if(t.defined()&&!t.canRead())throw Errors$6.ErrThreadReadKeyRequired;await this.network.addThread(e,{token:r.token,logKey:r.logKey,threadKey:t});const i=r.collections||[],o=r.name||"",[s,a,c]=await this.wrapDB(this.store,n,this.opts,o,i);if(c)throw new Error(`wrapping db: ${c.message}`);const l=await DB.newDB(s,this.network,n,a);return this.dbs.set(n.toString(),l),r.block?await this.network.pullThread(n,pullThreadBackgroundTimeout,{token:r.token}):this.pullThreadBackground(n,r.token),l}))}async pullThreadBackground(e,t){try{await this.network.pullThread(e,pullThreadBackgroundTimeout,{token:t})}catch(e){}}async preloadDBFromDC(e,t,r,n,i,o,s,a){if(!this)throw Errors$6.ErrNoDbManager;let c,l,u;try{c=await this.decodeThreadId(e)}catch(e){throw e}try{l=await this.getLogKey(c)}catch(e){throw e}try{u=peerIdFromPrivateKey(l)}catch(e){throw e}await this.dc._connectToObjNodes(c.toString()).catch((e=>{}));const d=createContext(3e4);try{await this.addLogToThreadStart(d,c,u)}catch(e){}let h,p;try{const e=SymmetricKey.fromString(o),t=SymmetricKey.fromString(i);h=new Key(e,t)}catch(e){throw e}let f=!1;if(n.length>10)try{const e=multiaddr(n);try{await(this.dc.dcNodeClient?.libp2p.dial(e,{signal:AbortSignal.timeout(3e3)}))&&(f=!0,p=multiaddr(n))}catch(e){}}catch(e){}if(f)this.dc._connectToObjNodes(c.toString()).catch((e=>{}));else try{const[e,t]=await(this.dc?._connectToObjNodes(c.toString()));if(!e&&t)throw Errors$6.ErrNoThreadOnDc;const r=this.dc.dcNodeClient?.libp2p.getConnections(undefined);if(!r||0==r.length)throw Errors$6.ErrNoThreadOnDc}catch(e){throw e}let y=[];try{y=JSON.parse(a)}catch(e){throw e}const g=y.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),b={name:r,collections:g,key:h,logKey:l,block:s};try{await this.deleteDB(c,!0)}catch(e){if(e!==Errors$6.ErrDBNotFound&&e!==Errors$6.ErrThreadNotFound)throw e}if(null==this.dc.dcNodeClient)throw Errors$6.ErrNoDcNodeClient;const m=createContext(30*PullTimeout),w=new FileManager(this.dc,this.connectedDc,this.chainUtil,this.dc.dcNodeClient,this.context),v=await w.createSeekableFileStream(t,"");if(null==v)throw Errors$6.ErrFileNotFound;const S=new ThreadMuliaddr(p,c);await this.preloadDBFromReader(m,v.createReadableStream(),S,h,b)}async preloadDBFromReader(e,t,r,n){let i,o,s,a,c=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};try{i=DBManager.fromAddr(r.addr)}catch(e){throw e}if(await this.lock.acquire("dbs",(async()=>{if(this.dbs.has(i.toString()))throw Errors$6.ErrDBExists})),c.name&&!isValidName(c.name))throw Errors$6.ErrInvalidName;if(n.defined()&&!n.canRead())throw Errors$6.ErrThreadReadKeyRequired;try{await this.network.addThread(r,{threadKey:n,logKey:c.logKey,token:c.token})}catch(e){throw e}try{const e=c.collections||[],t=c.name||"";[o,s]=await this.wrapDB(this.store,i,this.opts,t,e)}catch(e){throw e}try{a=await DB.newDB(o,this.network,i,s)}catch(e){throw e}await this.lock.acquire("dbs",(async()=>{this.dbs.set(i.toString(),a)}));const l=n.read();if(!l)throw new Error(`read key not found for thread ${i}`);const u=new LineReader(t);new TextDecoder;let d="";try{const e=await u.readLine();e&&(d=e)}catch(e){throw e}if(""==d)throw new Error(`empty state value for thread ${i}`);d=d.slice(32);const h=d.split(";"),p=[];for(const e of h)try{const t=srcExports.decode(e),r=net.pb.Log.decode(t);p.push(r)}catch(e){continue}try{await this.network.preLoadLogs(i,p)}catch(e){throw await this.deleteDB(i,!1),e}try{await this.importDBStateFromReader(i,u,l)}catch(e){throw await this.deleteDB(i,!1),e}}async exportDBToFile(e,t,r,n){let i,o,s="";[i,o]=await this.network.getPbLogs(t);for(let e=0;i&&e<i.length;e++){if(!i[e])continue;const t=i[e],r=net.pb.Log.encode(t).finish(),n=multibase.encode("base64",r);s=0===e?n.toString():`${s};${n.toString()}`}let a=s+"\n";const c=this.dbs.get(t.toString());if(!c)throw Errors$6.ErrDBNotFound;const l=await c.datastore.newTransactionExtended(!0);try{const e=new Query,i=new Key$1("/"),s=await newIterator(l,i,e);for await(const e of s.iter.next()){if(e.error)throw e.error;let t;if(n){const r=await n.encrypt(e.entry.value),i=multibase.encode("base64",r);t=`${e.entry.key}|${i.toString()}`}else{const r=multibase.encode("base64",e.entry.value);t=`${e.entry.key}|${r.toString()}`}a+=t+"\n"}s.close(),l.discard();const c=new Blob([a],{type:"text/plain"}),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=r||`db-export-${t.toString().substring(0,8)}.txt`,document.body.appendChild(d),d.click(),setTimeout((()=>{document.body.removeChild(d),URL.revokeObjectURL(u)}),100),o}catch(e){throw l.discard(),e}}async importDBStateFromReader(e,t,r){let n;if(await this.lock.acquire("dbs",(async()=>{n=this.dbs.get(e.toString())})),!n)throw Errors$6.ErrDBNotFound;const i=n.defaultIndexFunc();new TextDecoder;let o="";for(;o=await t.readLine(),o;){let e;try{e=await n.datastore.newTransactionExtended(!1)}catch(e){throw new Error(`创建事务错误: ${e instanceof Error?e.message:String(e)}`)}try{const t=o.split("|");if(2!==t.length)throw e.discard(),new Error("无效的记录格式");const n=t[0],s=t[1]||"";let a;try{a=srcExports.decode(s)}catch(t){throw await e.discard(),new Error(`multibase解码失败: ${t instanceof Error?t.message:String(t)}`)}let c=a;if(r)try{c=await r.decrypt(a)}catch(t){throw await e.discard(),new Error(`解密值失败: ${t instanceof Error?t.message:String(t)}`)}const l=new Key$1(n||"");try{if(await e.has(l)){e.discard();continue}}catch(t){throw e.discard(),new Error(`检查键存在性失败: ${t instanceof Error?t.message:String(t)}`)}try{await e.put(l,c)}catch(t){throw e.discard(),new Error(`存储值失败: ${t instanceof Error?t.message:String(t)}`)}const u=n?.split("/");if(!u||u.length<2)throw e.discard(),new Error("无效的键格式: 未找到集合名称");const d=u[u.length-2]||"";try{await i(d,l,e,c)}catch(t){throw e.discard(),new Error(`应用索引失败: ${t instanceof Error?t.message:String(t)}`)}try{await e.commit()}catch(t){throw e.discard(),new Error(`提交事务失败: ${t instanceof Error?t.message:String(t)}`)}}catch(t){try{e.discard()}catch{}throw t}}}async wrapDB(e,t,r,n,i){if(!await this.validateThreadId(t.toString()))return[null,null,new Error("Invalid Thread ID")];const o=dsManagerBaseKey.child(new Key$1(t.toString())).toString();return[createTransformedDatastore(e,new PrefixTransform(o)),{name:n,collections:[...r.collections||[],...i],eventCodec:r.eventCodec,debug:r.debug},null]}async listDBs(){const e=new Map;return await this.lock.acquire("dbs",(async()=>{for(const[t,r]of this.dbs){const n=q.fromString(t);await this.network.getThread(n),e.set(n,r)}})),e}async ifSyncDBToDCSuccess(e){try{const[t,r]=await this.chainUtil.objectState(e);return!(!t||r)&&new Promise((r=>{const n=setTimeout((()=>r(!1)),PullTimeout);(async()=>{for(const i of Object.keys(t.peers))try{const o=peerIdFromString$1(i),s=q.fromString(e),a=await this.network.getThreadFromPeer(s,o,{}),c=await this.network.getThread(s);if(this.compareThreadSync(c,a,t))return clearTimeout(n),void r(!0)}catch{continue}r(!1)})()}))}catch{return!1}}compareThreadSync(e,t,r){for(const n of e.logs){if(!r.logs.has(n.id.toString()))continue;if(!n.head)continue;const e=t.logs.find((e=>e.id===n.id));if(!e?.head)return!1;if(!e||n.head.counter>e.head.counter)return!1}return!0}async ifDbInitSuccess(e){try{const t=peerIdFromPrivateKey(await this.getLogKey(e)),[r,n]=await this.chainUtil.objectState(e.toString());if(!r||n)return!1;return!!r&&r?.logs.has(t.toString())}catch{return!1}}async syncDBFromDC(e,t,r,n,i,o,s,a){try{const c=await this.decodeThreadId(t),l=await this.getLogKey(c),u=peerIdFromPrivateKey(l);await this.dc._connectToObjNodes(t),await this.addLogToThreadStart(e,c,u);const d=SymmetricKey.fromString(o),h=SymmetricKey.fromString(i),p=new Key(d,h);let f,y,g;if(n.length>0)try{f=await(this.dc.dcNodeClient?.libp2p.dial(multiaddr(n),{signal:AbortSignal.timeout(dial_timeout)}))}catch(e){e.message}if(f)y=f?.remotePeer,g=f.remoteAddr;else{const[e,r]=await this.dc._connectToObjNodes(t);if(!e)throw new Error("connect to obj nodes failed");g=e}const b=a.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),m={name:r,collections:b,key:p,logKey:l,block:s};try{await this.deleteDB(c,!1)}catch(e){const t=e.message;if(t!=Errors$6.ErrDBNotFound.message&&t!=Errors$6.ErrThreadNotFound.message)throw e}const w=new ThreadMuliaddr(g,c);return await this.newDBFromAddr(w,p,m),null}catch(e){const t=e.message;return t==Errors$6.ErrorThreadIDValidation.message?t:e}}async getDBRecordsCount(e){let t=0;try{const r=await this.decodeThreadId(e),n=await this.network.getThread(r);if(!n)return t;for(const e of n.logs)e.head&&t<e.head.counter&&(t=e.head.counter)}catch(e){}return t}async addLogToThread(e,t,r){let n;try{n=await this.chainUtil.getBlockHeight()||0}catch(e){throw e}const i=uint32ToLittleEndianBytes(n||0),o=(new TextEncoder).encode(this.connectedDc.nodeAddr?.getPeerId()||""),s=new Uint8Array([...(new TextEncoder).encode(t.toString()),...(new TextEncoder).encode(r.toString()),...i,...o]);let a;try{a=await this.context.sign(s)}catch(e){throw e}if(!this.connectedDc?.client)throw Errors$6.ErrNoDcPeerConnected;const c={token:new ThreadToken(this.connectedDc.client.token),blockHeight:n,signature:a},l=newGrpcClient(this.connectedDc.client,this.network);await l.addLogToThread(t.toString(),r.toString(),c)}async addLogToThreadStart(e,t,r){e||(e=createContext(3e4));const n=new AbortController,i=e?.signal||n.signal,[o,s]=await this.chainUtil.objectState(t.toString());if(o&&!s){const e=this.context.getPublicKey();let t=!1;for(const r of o.users){if(r.replace("0x","")===e.toString()){t=!0;break}}if(!t)throw new Error("user not in the thread")}let a=null;if(e.deadline){const t=e.deadline.getTime()-Date.now();t>0&&(a=setTimeout((()=>{n.abort()}),t))}let c=0;let l=!1;try{await this.addLogToThread(e,t,r)}catch(e){}const u=setInterval((async()=>i.aborted?(clearInterval(u),void(a&&clearTimeout(a))):await this.ifDbInitSuccess(t)?(clearInterval(u),a&&clearTimeout(a),void(l=!0)):void(c>=6?(await this.addLogToThread(e,t,r),c=0):c++)),1e3);await new Promise((e=>{const t=setInterval((()=>{l&&(clearInterval(t),e())}),1e3);i.addEventListener("abort",(()=>{clearInterval(t),e()}))}))}async newDB(e,t,r,n){if(!this.connectedDc?.client)return["",Errors$6.ErrNoDcPeerConnected];try{const i=newGrpcClient(this.connectedDc.client,this.network),o=await i.requestThreadID(),s=await this.decodeThreadId(o),a=await this.getLogKey(s),c=(a.publicKey,peerIdFromPrivateKey(a)),l=SymmetricKey.fromString(r),u=SymmetricKey.fromString(t),d=new Key(l,u),h=await this.chainUtil.getBlockHeight()||0,p=uint32ToLittleEndianBytes(h||0);if(!this.connectedDc?.nodeAddr)return["",Errors$6.ErrNodeAddrIsNull];const f=await extractPeerIdFromMultiaddr(this.connectedDc.nodeAddr),y=(new TextEncoder).encode(f.toString()),g=uint64ToLittleEndianBytes(50<<20),b=(new TextEncoder).encode(o),m=uint32ToLittleEndianBytes(Type.Threaddbtype),w=new Uint8Array([...b,...g,...p,...m,...y]),v=await this.context.sign(w),S={threadKey:d,logKey:a,token:new ThreadToken(this.connectedDc.client.token),blockHeight:h,signature:v},$=await i.createThread(s.toString(),S),x=n.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),E={name:e,collections:x,key:d,logKey:a,block:!0},A=[];for(const e of $.addrs)try{await this.newDBFromAddr(e,d,E);break}catch(e){A.push(e.message)}if(A.length===$.addrs.length)throw new Error(`create db failed:${A.join(",")}`);const P=createContext(3e4);return await this.addLogToThreadStart(P,s,c),[s.toString(),null]}catch(e){return["",e]}}async refreshDBFromDC(e){try{const t=await this.decodeThreadId(e);return await this.network.pullThread(t,600,{multiPeersFlag:!0}),null}catch(e){return e}}async syncDBToDC(e){if(!this.network)return Errors$6.ErrP2pNetworkNotInit;try{const t=await this.decodeThreadId(e);return await this.network.exchange(t),null}catch(e){return e}}async upgradeCollections(e,t){try{const r=await this.decodeThreadId(e),n=this.dbs.get(r.toString());return n?(await n.upgradeCollections(t),null):Errors$6.ErrDBNotFound}catch(e){return e}}async decodeThreadId(e){if(!e)throw new Error("Thread ID is empty");try{if(!/^[a-zA-Z0-9]+$/.test(e))throw Errors$6.ErrorThreadIDValidation;const t=q.fromString(e);if(t.toBytes().length<32)throw new Error("Thread ID too short");return t}catch(e){if(e.message===Errors$6.ErrorThreadIDValidation.message)throw e;throw new Error("Failed to decode thread ID: $errMsg}")}}async validateThreadId(e){try{return await this.decodeThreadId(e),!0}catch{return!1}}async close(){await this.lock.acquire("dbs",(async()=>{for(const e of this.dbs.values())await e.close();this.dbs.clear()}))}async getDB(e,t){try{await this.network.getThread(e,{token:t?.token})}catch(e){throw e}const r=this.dbs.get(e.toString());if(!r)throw Errors$6.ErrDBNotFound;return r}async getDBInfo(e,t){let r=null;try{const n=this.dbs.get(e.toString());if(!n)throw Errors$6.ErrDBNotFound;if(r=await n.getDBInfo(t),!r||null===r)throw new Error(`No info available for db ${e}`)}catch(e){return[null,e]}return[r,null]}async deleteDB(e,t,r){try{await this.network.getThread(e,{token:r?.token})}catch(e){throw e}const n=this.dbs.get(e.toString());if(!n)throw Errors$6.ErrDBNotFound;try{await n.close()}catch(e){throw e}if(t)try{await this.network.deleteThread(e,{token:r?.token,apiToken:n.connector?.token})}catch(e){throw e}try{await this.deleteThreadNamespace(e)}catch(e){throw e}this.lock.acquire("dbs",(async()=>{this.dbs.delete(e.toString())}))}async deleteThreadNamespace(e){const t={prefix:dsManagerBaseKey.child(new Key$1(e.toString())).toString(),keysOnly:!0},r=this.store.query(t);for await(const e of r)await this.store.delete(e.key)}async create(e,t,r){try{const e=JSON.parse(r);e&&"object"==typeof e&&"_mod"in e&&(delete e._mod,r=JSON.stringify(e))}catch(e){throw new Error("Invalid instance JSON format")}try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.create(Buffer$1.from(r));return o?o.toString():""}catch(e){throw e}}async delete(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");await i.delete(r)}catch(e){throw e}}async save(e,t,r){try{const n=q.fromString(e);try{const e=JSON.parse(r);e&&"object"==typeof e&&"_mod"in e&&(delete e._mod,r=JSON.stringify(e))}catch(e){throw new Error("Invalid instance JSON format")}const i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");await i.save(Buffer$1.from(r))}catch(e){throw e}}async deleteMany(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");let o=[];if(""===(r=r.trim()))return;if("["!==r[0])o=r.split(",");else try{o=JSON.parse(r)}catch(e){o=[r]}const s=o.length;for(let e=0;e<s;e+=100){const t=o.slice(e,Math.min(e+100,s));await i.deleteMany(t)}}catch(e){throw e}}async has(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);return!!i&&await i.has(r)}catch(e){return!1}}async find(e,t,r){try{r||(r="{}");const n=parseJsonToQuery(r),i=q.fromString(e),o=(await this.getDB(i)).getCollection(t);if(!o)throw new Error("Collection does not exist");const s=await o.find(n);if(Array.isArray(s))return jsonStringify(s);{const e=s,t=Buffer$1.concat([Buffer$1.from("["),Buffer$1.concat(e.map(((t,r)=>Buffer$1.concat([t,r<e.length-1?Buffer$1.from(","):Buffer$1.from("")])))),Buffer$1.from("]")]);return t.toString()}}catch(e){throw e}}async findByID(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.findByID(r);return o instanceof Buffer$1?o.toString():jsonStringify(o)}catch(e){throw e}}async modifiedSince(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.modifiedSince(r);return JSON.stringify(o)}catch(e){throw e}}}class AsyncLock{constructor(){Object.defineProperty(this,"locks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.locks=new Map}async acquire(e,t){for(;this.locks.has(e);)await this.locks.get(e);let r;const n=new Promise((e=>r=e));this.locks.set(e,n);try{return await t()}catch(e){throw e}finally{this.locks.delete(e),r()}}}function isValidName(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function createContext(e){const t={deadline:new Date(Date.now()+e)};return 0===e&&(t.deadline=void 0),"undefined"!=typeof AbortController&&(t.signal=(new AbortController).signal),t}const logger$7=createLogger("DatabaseModule"),storagePrefix="dc-";class DatabaseModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.DATABASE}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.context=e,this.initialized=!0,!0}catch(e){return logger$7.error("数据库模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async initDBManager(){try{if(this.assertInitialized(),this.context.dbManager)return null;const e=await createTxnDatastore(this.context.appInfo?.appName),t=await newKeyBook(e),r=await newAddrBook(e),n=newHeadBook(e),i=newLogstore(t,r,n,newThreadMetadata(e)),o=dagCbor(this.context.dcNodeClient);if(!this.context.publicKey)throw new Error("公钥未初始化");const s=new Network(this.context.dcutil,this.context.dcChain,this.context.dcNodeClient.libp2p,this.context.grpcServer,i,this.context.dcNodeClient.blockstore,o,this.context),a=new DBManager(e,s,this.context.dcutil,this.context.connectedDc,{},this.context.dcChain,storagePrefix,this.context);return await a.loadDbs(),this.context.dbManager=a,logger$7.info("数据库管理器初始化成功"),null}catch(e){return logger$7.error("初始化数据库管理器失败:",e),e}}async newDB(e,t,r,n){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const[i,o]=await this.context.dbManager.newDB(e,t,r,n);if(o)throw logger$7.error("创建数据库失败:",o),o;return logger$7.info(`创建数据库 ${e} 成功,线程ID: ${i}`),[i,null]}catch(t){return logger$7.error(`创建数据库 ${e} 失败:`,t),[null,t instanceof Error?t:new Error(String(t))]}}async loadVerno(e){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const t=q.fromString(e),r=await this.context.dbManager.getDB(t);if(!r)return logger$7.error("数据库信息为空"),0;return await r.loadVerno()}catch(e){return logger$7.error("加载数据库版本号失败:",e),0}}async saveVerno(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const r=q.fromString(e),n=await this.context.dbManager.getDB(r);return n?(await n.saveVerno(t),0):(logger$7.error("数据库信息为空"),-1)}catch(e){return logger$7.error("加载数据库版本号失败:",e),-1}}async syncDbFromDC(e,t,r,n,i,o,s){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const a=createContext(6e4);return await this.context.dbManager.syncDBFromDC(a,e,t,r,n,i,o,s),logger$7.info(`从DC同步数据库 ${t} 成功`),null}catch(e){return logger$7.error(`从DC同步数据库 ${t} 失败:`,e),e instanceof Error?e:new Error(String(e))}}async refreshDBFromDC(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.refreshDBFromDC(e),null}catch(t){return logger$7.error(`刷新数据库 ${e} 失败:`,t),t}}async syncDBToDC(e){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.syncDBToDC(e),logger$7.info(`同步数据库 ${e} 到DC成功`),null}catch(t){return logger$7.error(`同步数据库 ${e} 到DC失败:`,t),t}}async upgradeCollections(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.upgradeCollections(e,t),null}catch(e){return e}}async close(){try{if(this.assertInitialized(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.close(),logger$7.info("数据库管理器关闭成功"),null}catch(e){return logger$7.error("关闭数据库管理器失败:",e),e instanceof Error?e:new Error(String(e))}}async getDBInfo(e){try{if(!e||0==e.length)return[null,new Error("数据库ID不能为空")];if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)return[null,new Error("数据库管理器未初始化")];const t=q.fromString(e),[r,n]=await this.context.dbManager.getDBInfo(t);return[r,n]}catch(e){return logger$7.error("获取数据库信息失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async create(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const n=await this.context.dbManager.create(e,t,r);return logger$7.info(`创建实例成功,ID: ${n}`),[n,null]}catch(e){return logger$7.error("创建实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async delete(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.delete(e,t,r),logger$7.info(`删除实例成功,ID: ${r}`),null}catch(e){return logger$7.error("删除实例失败:",e),e instanceof Error?e:new Error(String(e))}}async save(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.save(e,t,r),logger$7.info("更新实例成功"),null}catch(e){return logger$7.error("更新实例失败:",e),e instanceof Error?e:new Error(String(e))}}async deleteMany(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.deleteMany(e,t,r),logger$7.info("删除多个实例成功"),null}catch(e){return logger$7.error("删除多个实例失败:",e),e instanceof Error?e:new Error(String(e))}}async has(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.has(e,t,r)}catch(e){return logger$7.error("检查实例是否存在失败:",e),!1}}async find(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.find(e,t,r),null]}catch(e){return logger$7.error("查询实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async findByID(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.findByID(e,t,r),null]}catch(e){return logger$7.error("通过ID查询实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async modifiedSince(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.modifiedSince(e,t,r),null]}catch(e){return logger$7.error("查询修改时间大于指定时间的实例ID失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)throw new Error("数据库模块未初始化")}}class MessageClient{constructor(e,t,r){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiverClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMsgToUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{const t=this.client.peerAddr.getPeerId();if(!t)throw new Error("peerId is undefined");if(!this.receiverClient)throw new Error("receiverClient is undefined");const r=await this.getToUserBoxAuth(e.signature),n=new dcnet.pb.SendMsgToUserBoxRequest({});n.msg=e,n.AuthSignature=r,n.PeerId=(new TextEncoder).encode(t.toString());const i=dcnet.pb.SendMsgToUserBoxRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.receiverClient.p2pNode,this.receiverClient.peerAddr,this.receiverClient.token,this.receiverClient.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/SendMsgToUserBox",i,3e4);return dcnet.pb.SendMsgToUserBoxReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.receiverClient.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/SendMsgToUserBox",i,3e4);return dcnet.pb.SendMsgToUserBoxReply.decode(e).flag}throw e}}}),Object.defineProperty(this,"getToUserBoxAuth",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{const t=new dcnet.pb.GetToUserBoxAuthRequest({});t.msgSignature=e;const r=dcnet.pb.GetToUserBoxAuthRequest.encode(t).finish(),n=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await n.unaryCall("/dcnet.pb.Service/GetToUserBoxAuth",r,3e4);return dcnet.pb.GetToUserBoxAuthReply.decode(e).signature}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await n.unaryCall("/dcnet.pb.Service/GetToUserBoxAuth",r,3e4);return dcnet.pb.GetToUserBoxAuthReply.decode(e).signature}throw e}}}),this.client=e,this.context=t,this.receiverClient=r}async getMaxKeyFromUserBox(e){const t=new dcnet.pb.GetMaxKeyFromUserBoxRequest;t.appId=(new TextEncoder).encode(e);const r=dcnet.pb.GetMaxKeyFromUserBoxRequest.encode(t).finish();try{const e=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),t=await e.unaryCall("/dcnet.pb.Service/GetMaxKeyFromUserBox",r,3e4),n=dcnet.pb.GetMaxKeyFromUserBoxReply.decode(t);return n.maxkey?toString$9(n.maxkey):""}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),n=await t.unaryCall("/dcnet.pb.Service/GetMaxKeyFromUserBox",r,3e4),i=dcnet.pb.GetMaxKeyFromUserBoxReply.decode(n);return i.maxkey?toString$9(i.maxkey):""}if(-1!=t.message.indexOf("datastore: key not found"))return"";throw t}}async getMsgFromUserBox(e,t,r){const n=new dcnet.pb.GetMsgFromUserBoxRequest;n.appId=(new TextEncoder).encode(e),n.blockheight=0,n.seekKey=(new TextEncoder).encode(t),n.limit=r;const i=dcnet.pb.GetMsgFromUserBoxRequest.encode(n).finish();try{const e=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),t=await e.unaryCall("/dcnet.pb.Service/GetMsgFromUserBox",i,3e4);return dcnet.pb.GetMsgFromUserBoxReply.decode(t).toJSON()}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),r=await t.unaryCall("/dcnet.pb.Service/getMsgFromUserBox",i,3e4);return dcnet.pb.GetMsgFromUserBoxReply.decode(r).toJSON()}throw t}}}let DCError$1=class extends Error{constructor(e){super(e),this.name="DCError"}};const Errors$4={ErrNoDcPeerConnected:new DCError$1("no dc peer connected"),ErrGetUserInfoError:new DCError$1("get user info error"),ErrNoAccountPeerConnected:new DCError$1("no account peer connected"),ErrNoReceiverPeerConnected:new DCError$1("no receiver peer connected")};class MessageManager{constructor(e,t,r){var n=this;Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMsgToUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{try{if(!this.context.AccountBackupDc.client)return[null,Errors$4.ErrNoAccountPeerConnected];const n=Ed25519PubKey.edPubkeyFromStr(t),i=await this.context.getPublicKey(),o=await this.generateMsqBoxReq(e,n,r);let s=await this.dc.connectToUserDcPeer(n.raw);if(!s)return[null,Errors$4.ErrNoReceiverPeerConnected];const a=await s.GetToken(e,i.string(),(e=>this.context.sign(e)));s.token=a;const c=new MessageClient(this.context.AccountBackupDc.client,this.context,s);return[await c.sendMsgToUserBox(o),null]}catch(e){throw e}}}),Object.defineProperty(this,"getMsgFromUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100;try{if(!n.context.AccountBackupDc.client)return[null,Errors$4.ErrNoAccountPeerConnected];const r=await n.context.getPublicKey(),i=r.string(),o=await n.dc.connectToUserAllDcPeers(r.raw);if(!o)return[null,Errors$4.ErrNoDcPeerConnected];let s=[];for(const r of o)if(r){const o=r.peerAddr.getPeerId()||"",a=n.context.getPublicKey().string();if(!r.token){const t=await r.GetToken(e,a,(e=>n.context.sign(e)));r.token=t}const c=new MessageClient(r,n.context);let l=await c.getMaxKeyFromUserBox(e);const u=localStorage.getItem("userBoxMaxKey_"+a)||"";let d=u?JSON.parse(u):{};if(l){(d[i]||{})[o]=l}let h=!0;for(;h;)try{const r=await c.getMsgFromUserBox(e,l,t),n=r&&r.msgs?r.msgs:[];n.map((e=>{e&&e.messageId&&s.push(e)})),n.length<t&&(l&&localStorage.setItem("userBoxMaxKey_"+a,JSON.stringify(d)),h=!1)}catch(e){}}return[s,null]}catch(e){return[null,e]}}}),Object.defineProperty(this,"generateMsqBoxReq",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{const n=`${r}${1e6*Date.now()}`,i=(new TextEncoder).encode(n),o=await sha256$3.digest(i),s=CID$1.create(1,85,o),a=(new TextEncoder).encode(s.toString()),c=(new TextEncoder).encode(e),l=await this.context.getPublicKey(),u=(new TextEncoder).encode(l.string()),d=(new TextEncoder).encode(t.string()),h=await this.chainUtil.getBlockHeight()||0,p=uint32ToLittleEndianBytes(h),f=(new TextEncoder).encode(r),y=await t.encrypt(f),g=new Uint8Array([...a,...d,...c,...p,...y]),b=await this.context.sign(g),m=new dcnet.pb.UserMsg({});return m.appId=(new TextEncoder).encode(e),m.blockheight=h,m.encryptMsg=y,m.messageId=a,m.receiverPubkey=d,m.senderPubkey=u,m.signature=b,m}}),this.dc=e,this.chainUtil=t,this.context=r}}const logger$6=createLogger("MessageModule");class MessageModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.MESSAGE}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.context=e,this.messageManager=new MessageManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$6.error("消息模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async sendMsgToUserBox(e,t){try{this.assertInitialized();const r=await this.messageManager.sendMsgToUserBox(this.context.appInfo?.appId||"",e,t);return logger$6.info(`发送消息到用户 ${e} 成功`),r}catch(t){return logger$6.error(`发送消息到用户 ${e} 失败:`,t),[null,t]}}async getMsgFromUserBox(e){try{this.assertInitialized();const t=await this.messageManager.getMsgFromUserBox(this.context.appInfo?.appId||"",e);return logger$6.info("获取用户消息成功"),t}catch(e){return logger$6.error("获取用户消息失败:",e),[null,e]}}assertInitialized(){if(!this.initialized)throw new Error("消息模块未初始化")}}class KeyValueClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e,this.context=t}async configThemeObjAuth(e,t,r,n,i,o,s,a,c,l,u){const d=new dcnet.pb.ConfigThemeObjAuthRequest({});d.appId=(new TextEncoder).encode(t),d.themeAuthor=(new TextEncoder).encode(r),d.theme=(new TextEncoder).encode(e),d.blockheight=n,d.content=(new TextEncoder).encode(s),d.contentCid=(new TextEncoder).encode(o),d.contentSize=a,d.signature=l,d.type=c,d.userPubkey=(new TextEncoder).encode(i),u&&(d.vaccount=(new TextEncoder).encode(u));const h=dcnet.pb.ConfigThemeObjAuthRequest.encode(d).finish(),p=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await p.unaryCall("/dcnet.pb.Service/ConfigThemeObjAuth",h,3e4);return dcnet.pb.ConfigThemeObjAuthReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await p.unaryCall("/dcnet.pb.Service/ConfigThemeObjAuth",h,3e4);return dcnet.pb.GetUserCommentsReply.decode(e).flag}throw e}}async setKeyValue(e,t,r,n,i,o,s,a,c,l,u){const d=new dcnet.pb.SetKeyValueRequest({});d.appId=(new TextEncoder).encode(t),d.themeAuthor=(new TextEncoder).encode(r),d.theme=(new TextEncoder).encode(e),d.blockheight=n,d.content=(new TextEncoder).encode(s),d.contentCid=(new TextEncoder).encode(o),d.contentSize=a,d.signature=l,d.type=c,d.userPubkey=(new TextEncoder).encode(i),u&&(d.vaccount=(new TextEncoder).encode(u));const h=dcnet.pb.SetKeyValueRequest.encode(d).finish(),p=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await p.unaryCall("/dcnet.pb.Service/SetKeyValue",h,3e4);return dcnet.pb.SetKeyValueReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await p.unaryCall("/dcnet.pb.Service/SetKeyValue",h,3e4);return dcnet.pb.GetUserCommentsReply.decode(e).flag}throw e}}async getValueWithKey(e,t,r,n,i,o){const s=new dcnet.pb.GetValueWithKeyRequest({});s.appId=(new TextEncoder).encode(t),s.themeAuthor=(new TextEncoder).encode(r),s.theme=(new TextEncoder).encode(e),s.UserPubkey=(new TextEncoder).encode(n),s.Key=(new TextEncoder).encode(i),o&&(s.vaccount=(new TextEncoder).encode(o));const a=dcnet.pb.GetValueWithKeyRequest.encode(s).finish(),c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await c.unaryCall("/dcnet.pb.Service/GetValueWithKey",a,3e4),t=dcnet.pb.GetValueWithKeyReply.decode(e);return 0==t.flag?t.value:null}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await c.unaryCall("/dcnet.pb.Service/GetValueWithKey",a,3e4),r=dcnet.pb.GetValueWithKeyReply.decode(e);return 0==r.flag?r.value:null}throw e}}async getValuesWithKeys(e,t,r,n,i,o){const s=new dcnet.pb.GetValuesWithKeysRequest({});s.appId=(new TextEncoder).encode(t),s.themeAuthor=(new TextEncoder).encode(r),s.theme=(new TextEncoder).encode(e),s.UserPubkey=(new TextEncoder).encode(n),s.Keys=(new TextEncoder).encode(i),o&&(s.vaccount=(new TextEncoder).encode(o));const a=dcnet.pb.GetValuesWithKeysRequest.encode(s).finish(),c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await c.unaryCall("/dcnet.pb.Service/GetValuesWithKeys",a,3e4),t=dcnet.pb.GetValuesWithKeysReply.decode(e);return 0==t.flag?t.keyValues:null}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await c.unaryCall("/dcnet.pb.Service/GetValuesWithKeys",a,3e4),r=dcnet.pb.GetValuesWithKeysReply.decode(e);return 0==r.flag?r.keyValues:null}throw e}}async getValuesWithIndex(e,t,r,n,i,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:exports.Direction.Forward,a=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0;const u=new dcnet.pb.GetValuesWithIndexRequest({});u.appId=(new TextEncoder).encode(e),u.themeAuthor=(new TextEncoder).encode(t),u.theme=(new TextEncoder).encode(r),u.indexKey=(new TextEncoder).encode(n),u.indexValue=(new TextEncoder).encode(i),u.seekKey=(new TextEncoder).encode(o),u.direction=s,u.offset=a,u.limit=c,l&&(u.vaccount=(new TextEncoder).encode(l));const d=dcnet.pb.GetValuesWithIndexRequest.encode(u).finish(),h=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await h.unaryCall("/dcnet.pb.Service/GetValuesWithIndex",d,3e4),t=dcnet.pb.GetValuesWithIndexReply.decode(e);return 0==t.flag?t.keyValues:null}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=await h.unaryCall("/dcnet.pb.Service/GetValuesWithIndex",d,3e4),r=dcnet.pb.GetValuesWithIndexReply.decode(t);return 0==r.flag?r.keyValues:null}throw t}}}var KeyValueStoreType;!function(e){e[e.Auth=1]="Auth",e[e.Public=2]="Public"}(KeyValueStoreType||(KeyValueStoreType={}));class KeyValueError extends Error{constructor(e){super(e),this.name="KeyValueError"}}const Errors$3={ErrNoDcPeerConnected:new KeyValueError("no dc peer connected"),ErrPublicKeyIsNull:new KeyValueError("publickey is null")};class KeyValueDB{constructor(e,t,r,n){Object.defineProperty(this,"appId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbname",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"themeAuthor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.appId=e,this.dbname=t,this.themeAuthor=r,this.manager=n}async set(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";return this.manager.setKeyValue(this.appId,this.themeAuthor,this.dbname,e,t,r,n)}async get(e,t,r){if(!t){const[t,r]=await this.getWithIndex("dc_timestamp_index","",1,"",exports.Direction.Reverse,0);if(r)return[null,r];if(!t)return[null,null];const n=JSON.parse(t);if(!Array.isArray(n))return[t,null];if(0==n.length)return[null,null];let i="";try{i=n[0][e]}catch(e){return[null,e instanceof Error?e:new Error(String(e))]}return i&&0!=i.length||(i=n[0]),[i,null]}return this.manager.getValueWithKey(this.appId,this.themeAuthor,this.dbname,t,e,r)}async getBatch(e,t,r){return t||(t=this.themeAuthor),this.manager.getValuesWithKeys(this.appId,this.themeAuthor,this.dbname,t,e,r)}async getWithIndex(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:exports.Direction.Forward,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:"";return this.manager.getWithIndex(this.appId,this.themeAuthor,this.dbname,e,t,n,i,o,r,s)}async configAuth(e,t,r,n){return this.manager.doConfigAuth(this.appId,this.themeAuthor,this.dbname,e,t,r,n)}async getAuthList(e){return this.manager.getAuthList(this.appId,this.themeAuthor,this.dbname,e)}}class KeyValueManager{constructor(e,t,r){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.dc=e,this.chainUtil=t,this.context=r}async createStore(e,t,r,n){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];if(""===e&&(e="DCAPP"),r<100<<20&&(r=100<<20),t.startsWith("keyvalue_")||(t="keyvalue_"+t),n===KeyValueStoreType.Public&&!t.endsWith("_pub"))return[null,new Error("vaCreateStoreTheme failed, public theme must end with '_pub'")];try{const n=new CommentManager(this.context),i=await n.addThemeObj(e,t,OpenFlag.AUTH,r||52428800);if(0!==i[0]||null!==i[1])return[null,new Error(`vaCreateStoreTheme failed, resFlag: ${i}`)];return[new KeyValueDB(e,t,this.context.publicKey.string(),this),null]}catch(e){return[null,e]}}async getKeyValueDB(e,t,r){const n=new CommentManager(this.context);t.startsWith("keyvalue_")||(t="keyvalue_"+t);const[i,o]=await n.isThemeExist(e,t,r);if(o)return[null,o];if(!i)return[null,new Error(`Theme ${t} does not exist for appId ${e}`)];return[new KeyValueDB(e,t,r,this),null]}async doConfigAuth(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(e,this.context.publicKey.string(),this.context.sign);const l=Ed25519PubKey.edPubkeyFromStr(t);let u,d=!0,h=null;try{h=Ed25519PubKey.edPubkeyFromStr(n)}catch(e){d=!1}u=d&&null!==h?h.string():n;const p=`${u}:${i}:${o}`,f=(new TextEncoder).encode(p),y=await sha256(f),g=base32$5.encode(y);let b;try{b=await this.chainUtil.getBlockHeight()||0}catch(e){return[null,new Error("ErrGetBlockHeightFail")]}const m=f.length,w=uint32ToLittleEndianBytes(b||0),v=uint32ToLittleEndianBytes(exports.CommentType.Comment),S=(new TextEncoder).encode(r),$=(new TextEncoder).encode(e),x=(new TextEncoder).encode(l.string()),E=(new TextEncoder).encode(g);let A=new Uint8Array([...S,...$,...x,...w,...E,...v]);const P=await this.context.sign(A),k=new KeyValueClient(c,this.context);try{const n=await k.configThemeObjAuth(r,e,t,b,a,g,p,m,exports.CommentType.Comment,P,s);return 0!==n?[n,new Error(`configThemeObjAuth fail, resFlag: ${n}`)]:[0,null]}catch(e){return[null,e]}}async getAuthList(e,t,r,n){r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let i="",o=[],s=[];try{for(;;){const a=new CommentManager(this.context),c=await a.getThemeComments(e,r,t,0,exports.Direction.Forward,0,1e3,i||"",n);if(c[0]&&0==c[0].length)break;const l=c[0];if(!l||0==l.length)break;for(let e=0;e<l.length;e++){o.push(l[e]);const t=l[e].comment,r=t.split(":");if(r.length<2)continue;const n=r[0],i=parseInt(r[1]),a=t.substring(r[0].length+2);s.push({pubkey:n,permission:i,remark:a})}if(l.length<1e3)break;i=`${l[l.length-1].blockheight}/${l[l.length-1].commentCid}`}}catch(e){return[s,o,e]}return[s,o,null]}async setKeyValue(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(e,this.context.publicKey.string(),this.context.sign);let l=`${n}:${i}`;""!=o&&(l=`$$i_start$$${o}$$i_end$$${l}`);const u=(new TextEncoder).encode(l),d=await sha256(u),h=base32$5.encode(d),p=u.length,f=await this.chainUtil.getBlockHeight()||0,y=uint32ToLittleEndianBytes(f||0),g=(new TextEncoder).encode(r),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(e),w=(new TextEncoder).encode(h),v=uint32ToLittleEndianBytes(exports.CommentType.KeyValue),S=new Uint8Array([...g,...m,...b,...y,...w,...v]),$=await this.context.sign(S),x=new KeyValueClient(c,this.context);try{const n=await x.setKeyValue(r,e,t,f,a,h,l,p,exports.CommentType.KeyValue,$,s);return 0!==n?[null,new Error(`setKeyValue fail, resFlag:${n}`)]:[!0,null]}catch(e){return[null,e]}}async getValueWithKey(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let s=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(s=await this.dc.connectToUserDcPeer(e.raw),!s)return[null,Errors$3.ErrNoDcPeerConnected]}if(null===s)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===s.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==s.token&&await s.GetToken(e,this.context.publicKey.string(),this.context.sign);const a=new KeyValueClient(s,this.context);try{const s=await a.getValueWithKey(r,e,t,n,i,o);if(null==s)return[null,new Error(`vaGetValueWithKeyForVAccount fail, resFlag:${s}`)];return[(new TextDecoder).decode(s),null]}catch(e){return[null,e]}}async getValuesWithKeys(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let s=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(s=await this.dc.connectToUserDcPeer(e.raw),!s)return[null,Errors$3.ErrNoDcPeerConnected]}if(null===s)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===s.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==s.token&&await s.GetToken(e,this.context.publicKey.string(),this.context.sign);const a=new KeyValueClient(s,this.context);try{const s=await a.getValuesWithKeys(r,e,t,n,i,o);if(null==s)return[null,new Error(`vaGetValuesWithKeysForVAccount fail, resFlag:${s}`)];return[(new TextDecoder).decode(s),null]}catch(e){return[null,e]}}async getWithIndex(e,t,r,n,i,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:exports.Direction.Forward,a=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0;if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let u=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const r=Ed25519PubKey.edPubkeyFromStr(t);if(u=await this.dc.connectToUserDcPeer(r.raw),!u)return[null,Errors$3.ErrNoDcPeerConnected];await u.GetToken(e,this.context.publicKey.string(),this.context.sign)}if(null===u)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===u.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==u.token&&await u.GetToken(e,this.context.publicKey.string(),this.context.sign);const d=new KeyValueClient(u,this.context);try{const u=await d.getValuesWithIndex(e,t,r,n,i,o,s,a,c,l);if(null==u)return[null,new Error(`vaGetValuesWithKeysForVAccount fail, resFlag:${u}`)];return[(new TextDecoder).decode(u),null]}catch(e){return[null,e]}}}const logger$5=createLogger("KeyValueModule"),indexkey_dckv="indexkey_dckv";class KeyValueModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.KEYVALUE}),Object.defineProperty(this,"keyValueManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.keyValueManager=new KeyValueManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$5.error("键值存储模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async createStore(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];try{const[i,o]=await this.keyValueManager.createStore(e,t,r,n);return[i,o]}catch(e){return logger$5.error(`创建存储主题 ${t} 失败:`,e),[null,e instanceof Error?e:new Error(String(e))]}}async getStore(e,t,r){const n=this.assertInitialized();if(n)return[null,n];try{const[n,i]=await this.keyValueManager.getKeyValueDB(e,t,r);return[n,i]}catch(e){return logger$5.error(`获取存储主题 ${t} 失败:`,e),[null,e instanceof Error?e:new Error(String(e))]}}async configAuth(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];try{return await e.configAuth(t,r,n,i)}catch(e){return logger$5.error("配置权限失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getAuthList(e,t){const r=this.assertInitialized();if(r)return[null,null,r];try{return await e.getAuthList(t)}catch(e){return logger$5.error("获取权限列表失败:",e),[null,null,e instanceof Error?e:new Error(String(e))]}}async set(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];try{let o="";try{if(n&&""!=n){const e=JSON.parse(n);for(const t of e){let e="";e="number"===t.type?padPositiveInt30(t.value):t.value,o+=`${t.key}:${e}$$$`}}}catch(e){logger$5.error("设置索引,解析失败:",e)}const s=Date.now();o+=`dc_timestamp_index:${padPositiveInt30(s)}`;return await e.set(t,r,o,i)}catch(e){return logger$5.error("设置set-value失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async get(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];try{return await e.get(t,r,n)}catch(e){return logger$5.error("获取key-value失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getValues(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];const o=r.limit?r.limit:10,s=r.seekKey?r.seekKey:"",a=r.direction?r.direction:exports.Direction.Forward,c=r.offset?r.offset:0;try{return await e.getWithIndex(indexkey_dckv,t,o,s,a,c,n)}catch(e){return logger$5.error("getValues失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getBatch(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";const i=this.assertInitialized();if(i)return[null,i];try{return await e.getBatch(t,r,n)}catch(e){return logger$5.error("getBatch失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getWithIndex(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];const s=n.limit?n.limit:10,a=n.seekKey?n.seekKey:"",c=n.direction?n.direction:exports.Direction.Forward,l=n.offset?n.offset:0;let u="";"number"===n.type&&(u=padPositiveInt30(r));try{return await e.getWithIndex(t,u,s,a,c,l,i)}catch(e){return logger$5.error("getWithIndex失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)return Error("键值存储模块未初始化")}}class DCClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e}async getHostID(e){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");e||(e=this.client.peerAddr);const t=new dcnet.pb.GetHostIDRequest({}),r=dcnet.pb.GetHostIDRequest.encode(t).finish(),n=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,e||this.client.peerAddr,this.client.token,this.client.protocol),i=await n.unaryCall("/dcnet.pb.Service/GetHostID",r,3e4),o=dcnet.pb.GetHostIDReply.decode(i),s=base58btc$4.encode(o.peerID),a=toString$9(o.reqAddr);return{peerID:s,reqAddr:a}}catch(e){throw e}}}class DCError extends Error{constructor(e){super(e),this.name="DCError"}}const Errors$2={ErrNoDcPeerConnected:new DCError("no dc peer connected")};class DCManager{constructor(e){Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.connectedDc=e}async getHostID(e){if(!this.connectedDc?.client)return[null,Errors$2.ErrNoDcPeerConnected];const t=new DCClient(this.connectedDc.client);return[await t.getHostID(e),null]}}const logger$4=createLogger("ClientModule");class ClientModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.CLIENT}),Object.defineProperty(this,"clientManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.clientManager=new DCManager(e.connectedDc),this.initialized=!0,!0}catch(e){return logger$4.error("消息模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async getHostID(){try{this.assertInitialized();const e=await this.clientManager.getHostID();return e[0]?logger$4.info(`获取hostID成功: ${e[0].peerID}, 公网地址: ${e[0].reqAddr}`):logger$4.error("获取hostID失败:",e[1]),e}catch(e){return logger$4.error("获取hostID时发生错误:",e),[null,e]}}assertInitialized(){if(!this.initialized)throw new Error("消息模块未初始化")}}class CacheClient{constructor(e,t,r){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=r,this.context=e,this.dc=t}async getCacheValue(e,t){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");e?e.equals(this.client.peerAddr)||(await this.dc.connectToPeer(e.toString()),this.client=new Client(this.client.p2pNode,this.client.blockstore,e,this.client.protocol),await this.client.GetToken(this.context.appInfo.appId,this.context.publicKey.string(),this.context.sign,e)):e=this.client.peerAddr;const r=new dcnet.pb.GetCacheValueRequest({});r.key=(new TextEncoder).encode(t);const n=dcnet.pb.GetCacheValueRequest.encode(r).finish(),i=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,e||this.client.peerAddr,this.client.token,this.client.protocol),o=await i.unaryCall("/dcnet.pb.Service/GetCacheValue",n,3e4),s=dcnet.pb.GetCacheValueReply.decode(o);return toString$9(s.value)}catch(e){throw e}}async setCacheKey(e,t,r,n,i){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");i||(i=this.client.peerAddr);const o=new dcnet.pb.SetCacheKeyRequest({});o.value=(new TextEncoder).encode(e),o.blockheight=t,o.expire=r,o.signature=n;const s=dcnet.pb.SetCacheKeyRequest.encode(o).finish(),a=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,i||this.client.peerAddr,this.client.token,this.client.protocol),c=await a.unaryCall("/dcnet.pb.Service/SetCacheKey",s,3e4),l=dcnet.pb.SetCacheKeyReply.decode(c);if(l.cacheKey){return toString$9(l.cacheKey)}throw new Error("SetCacheKey failed,flag: "+l.flag)}catch(e){throw e}}}class CacheError extends Error{constructor(e){super(e),this.name="CacheError"}}const Errors$1={ErrNoDcPeerConnected:new CacheError("no dc peer connected"),ErrKeyNotValid:new CacheError("key not valid"),ErrNodeAddrIsNull:new CacheError("nodeAddr is null"),ErrChainUtilIsNull:new CacheError("chainUtil is null"),ErrAccountPrivateSignIsNull:new CacheError("account privatekey sign is null")};class CacheManager{constructor(e,t,r){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{if(!this.context?.AccountBackupDc.client)return[null,Errors$1.ErrNoDcPeerConnected];if(!this.chainUtil)return[null,Errors$1.ErrChainUtilIsNull];if(!this.context)return[null,Errors$1.ErrAccountPrivateSignIsNull];const n=await this.chainUtil.getBlockHeight(),i=(new TextEncoder).encode(e),o=await sha256(i),s=uint32ToLittleEndianBytes(n||0),a=uint32ToLittleEndianBytes(t),c=new Uint8Array(a.length+s.length);c.set(a,0),c.set(s,a.length);const l=new Uint8Array(c.length+o.length);l.set(c,0),l.set(o,c.length);const u=await this.context.sign(l),d=new CacheClient(this.context,this.dc,this.context?.AccountBackupDc.client);return[await d.setCacheKey(e,n||0,t,u),null]}}),this.dc=e,this.chainUtil=t,this.context=r}async getCacheValue(e,t){if(!this.context?.connectedDc?.client)return[null,Errors$1.ErrNoDcPeerConnected];const r=e.split("/");if(2!=r.length)return[null,Errors$1.ErrKeyNotValid];if(!this.context?.connectedDc.client)return[null,Errors$1.ErrNoDcPeerConnected];const n=r[0],i=r[1];try{let e;if(this.context?.connectedDc.nodeAddr){const t=this.context.connectedDc.nodeAddr.getPeerId()||"";e=t&&t===n?this.context.connectedDc.nodeAddr:await(this.dc?._getNodeAddr(n))}else e=await(this.dc?._getNodeAddr(n));if(!e)return[null,Errors$1.ErrNodeAddrIsNull];const t=new CacheClient(this.context,this.dc,this.context.connectedDc.client);return[await t.getCacheValue(e,i),null]}catch(e){return[null,e]}}}const logger$3=createLogger("CacheModule");class CacheModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.CACHE}),Object.defineProperty(this,"cacheManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.cacheManager=new CacheManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$3.error("键值存储模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async getCacheValue(e){try{this.assertInitialized();const t=await this.cacheManager.getCacheValue(e);return t[0]?(logger$3.info(`获取缓存键 ${e} 成功`),[t[0],null]):(logger$3.info(`缓存键 ${e} 不存在`),[null,null])}catch(t){return logger$3.error(`获取缓存键 ${e} 失败:`,t),[null,t instanceof Error?t:new Error(String(t))]}}async setCacheKey(e,t){try{this.assertInitialized();const r=t||keyExpire,n=await this.cacheManager.setCacheKey(e,r);return logger$3.info(`设置缓存值成功,过期时间: ${r}秒`),n}catch(e){return logger$3.error("设置缓存值失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)throw new Error("键值存储模块未初始化")}}class AIProxyClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e,this.context=t}async GetAIProxyConfig(e,t,r){const n=new dcnet.pb.GetAIProxyConfigRequest({});n.appId=(new TextEncoder).encode(e),n.themeAuthor=(new TextEncoder).encode(t),n.theme=(new TextEncoder).encode(r);const i=dcnet.pb.GetAIProxyConfigRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/GetAIProxyConfig",i,3e4),t=dcnet.pb.GetAIProxyConfigReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);const r=(new TextDecoder).decode(t.proxyConfigCid);return[r,(new TextDecoder).decode(t.aeskey),null]}catch(e){if("object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message&&-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/GetAIProxyConfig",i,3e4),t=dcnet.pb.GetAIProxyConfigReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);return[(new TextDecoder).decode(t.proxyConfigCid),(new TextDecoder).decode(t.aeskey),null]}throw e}}async GetUserOwnAIProxyAuth(e,t,r){const n=new dcnet.pb.GetUserOwnAIProxyAuthRequest({});n.appId=(new TextEncoder).encode(e),n.themeAuthor=(new TextEncoder).encode(t),n.theme=(new TextEncoder).encode(r);const i=dcnet.pb.GetUserOwnAIProxyAuthRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/GetUserOwnAIProxyAuth",i,3e4),t=dcnet.pb.GetUserOwnAIProxyAuthReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);return[(new TextDecoder).decode(t.authInfo),null]}catch(e){if("object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message&&-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/GetUserOwnAIProxyAuth",i,3e4),t=dcnet.pb.GetUserOwnAIProxyAuthReply.decode(e);if(0!=t.flag)return["",new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag)];return[(new TextDecoder).decode(t.authInfo),null]}return["",e instanceof Error?e:new Error(String(e))]}}async DoAIProxyCall(e,t,r,n,i,o,s,a,c,l,u,d){let h=arguments.length>12&&void 0!==arguments[12]?arguments[12]:null;const p=new dcnet.pb.DoAIProxyCallRequest({});p.appId=(new TextEncoder).encode(t),p.themeAuthor=(new TextEncoder).encode(r),p.theme=(new TextEncoder).encode(n),p.configKey=(new TextEncoder).encode(i),p.path=(new TextEncoder).encode(o),p.headers=(new TextEncoder).encode(s),p.reqBody=(new TextEncoder).encode(a),p.modelConfig=(new TextEncoder).encode(c),p.forceRefresh=l,p.blockheight=u,p.signature=d;const f=dcnet.pb.DoAIProxyCallRequest.encode(p).finish(),y=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);let g=!1,b=null,m=!1,w=!1;const v=()=>{b&&(clearTimeout(b),b=null)},S=()=>{v(),b=setTimeout((()=>{m||w||!g||(w=!0,h&&h(exports.AIStreamResponseFlag.STREAM_HANG,"","数据流超时:超过30秒未收到响应数据"))}),6e4)},$=()=>!!e.signal?.aborted&&(w=!0,v(),!0),x=async e=>{if(!(w||m||$())){g=!0,S();try{const t=dcnet.pb.DoAIProxyCallReply.decode(e);t.flag==exports.AIStreamResponseFlag.CONNECTION_CLOSED&&(m=!0,v()),h&&h(t.flag,(new TextDecoder).decode(t.content),(new TextDecoder).decode(t.err))}catch(e){h&&h(exports.AIStreamResponseFlag.OTHER_ERROR,"",e instanceof Error?e.message:String(e))}}},E=async()=>{v(),w||$()||m||(m=!0,h&&h(exports.AIStreamResponseFlag.CONNECTION_CLOSED,"",""))},A=async e=>{w||$()||m||h&&h(exports.AIStreamResponseFlag.OTHER_ERROR,"",e instanceof Error?e.message:String(e))};let P=null;if(e.signal){if(e.signal.aborted)return w=!0,v(),exports.AIStreamResponseFlag.EXTERNAL_EXIT;P=()=>{w=!0,v(),h&&h(exports.AIStreamResponseFlag.EXTERNAL_EXIT,"","调用被用户中止")},e.signal.addEventListener("abort",P)}try{return S(),await y.Call("/dcnet.pb.Service/DoAIProxyCall",f,1e7,"server-streaming",x,void 0,E,A,e),0}catch(t){if(m=!0,v(),w)return exports.AIStreamResponseFlag.STREAM_HANG;if(e.signal?.aborted)return exports.AIStreamResponseFlag.EXTERNAL_EXIT;throw t}finally{v(),P&&e.signal&&e.signal.removeEventListener("abort",P)}}}class AIProxyError extends Error{constructor(e){super(e),this.name="AIProxyError"}}const Errors={ErrNoDcPeerConnected:new AIProxyError("no dc peer connected"),ErrKeyNotValid:new AIProxyError("key not valid"),ErrNodeAddrIsNull:new AIProxyError("nodeAddr is null"),ErrChainUtilIsNull:new AIProxyError("chainUtil is null"),ErrAccountPrivateSignIsNull:new AIProxyError("account privatekey sign is null"),ErrAccountPublicKeyIsNull:new AIProxyError("account publickey is null")};class AIProxyManager{constructor(e,t,r,n){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcNodeClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleAllConfig",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t)=>{const r=new BrowserLineReader(e);let n=[],i=[];if(!this.context.getPublicKey())return null;const o=SymmetricKey.fromString(t);for(;;){const{line:e,error:t}=readLine(r);if(t&&"EOF"!==t.message)break;if(e){const t=(new TextDecoder).decode(e);if(!t)break;const r=base32$5.decode(t),s=await o.decrypt(r),a=(new TextDecoder).decode(s);if(!a)continue;if(a.startsWith("$$auth$$:")){try{const e=a.split("$$auth$$:")[1];if(!e)continue;const t=e.split(":");if(t.length<2)continue;const r=t[0]||"",n=t[1]||"",o=e.substring(r.length+n.length+2),s=JSON.parse(o);i.push({UserPubkey:r,permission:parseInt(n),authConfig:s})}catch(e){}continue}const c=a.split(":");if(c.length<2)continue;const l=a.substring((c[0]||"").length+1);try{const e=JSON.parse(l);n.push(e)}catch(e){}}}return[i,n]}}),this.dc=e,this.dcNodeClient=t,this.chainUtil=r,this.context=n}async createProxyConfig(e,t){""===e&&(e="DCAPP");t.startsWith("keyvalue_")||(t="keyvalue_"+t);try{const r=new CommentManager(this.context);return await r.addThemeObj(e,t,OpenFlag.AUTH,104857600)}catch(e){return[null,e]}}async deleteProxyConfig(e,t){""===e&&(e="DCAPP"),t.startsWith("keyvalue_")||(t="keyvalue_"+t);try{const r=new CommentManager(this.context);return await r.deleteThemeObj(e,t)}catch(e){return[null,e]}}async configAIProxy(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors.ErrNoDcPeerConnected];const s=await this.chainUtil.getBlockHeight()||0;let a=this.context.getPublicKey().string();r.startsWith("keyvalue_")||(r="keyvalue_"+r);let c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),!c)return[null,Errors.ErrNoDcPeerConnected];if(await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign),null===c)return[null,Errors.ErrNoDcPeerConnected];""==c.token&&await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);let l="";const u=n;if(i){i.blockheight=s;l=`${u}:${JSON.stringify(i)}`}else l=`${u}`;const d=(new TextEncoder).encode(l),h=await sha256(d),p=base32$5.encode(h),f=d.length,y=uint32ToLittleEndianBytes(s||0),g=(new TextEncoder).encode(r),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(e),w=(new TextEncoder).encode(p),v=uint32ToLittleEndianBytes(exports.CommentType.KeyValue),S=new Uint8Array([...g,...m,...b,...y,...w,...v]),$=await this.context.sign(S),x=new KeyValueClient(c,this.context);try{const n=await x.setKeyValue(r,e,t,s,a,p,l,f,exports.CommentType.KeyValue,$,o);return 0!==n?[null,new Error(`configAIProxy fail, resFlag:${n}`)]:[!0,null]}catch(e){return[!1,e]}}async configAuth(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors.ErrAccountPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const l=Ed25519PubKey.edPubkeyFromStr(t);let u,d=!0,h=null;try{h=Ed25519PubKey.edPubkeyFromStr(n)}catch(e){d=!1}u=d&&h?h.string():n;const p=`${u}:${i}:${JSON.stringify(o)}`,f=(new TextEncoder).encode(p),y=await sha256(f),g=base32$5.encode(y);let b;try{b=await this.chainUtil.getBlockHeight()||0}catch(e){return[null,new Error("ErrGetBlockHeightFail")]}const m=f.length,w=uint32ToLittleEndianBytes(b||0),v=uint32ToLittleEndianBytes(exports.CommentType.Comment),S=(new TextEncoder).encode(r),$=(new TextEncoder).encode(e),x=(new TextEncoder).encode(l.string()),E=(new TextEncoder).encode(g);let A=new Uint8Array([...S,...$,...x,...w,...E,...v]);const P=await this.context.sign(A),k=new KeyValueClient(c,this.context);try{const n=await k.configThemeObjAuth(r,e,t,b,a,g,p,m,exports.CommentType.Comment,P);if(0!==n)return[null,new Error(`configThemeObjAuth fail, resFlag: ${n}`)]}catch(e){return[null,e]}return[0,null]}async GetAIProxyConfig(e,t,r,n){if(!this.context.publicKey)return[null,null,Errors.ErrAccountPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let i=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(i=await this.dc.connectToUserDcPeer(e.raw),!i)return[null,null,Errors.ErrNoDcPeerConnected]}if(null===i)return[null,null,new Error("ErrConnectToAccountPeersFail")];if(null===i.peerAddr)return[null,null,new Error("ErrConnectToAccountPeersFail")];""==i.token&&await i.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);try{const n=new AIProxyClient(i,this.context),[o,s,a]=await n.GetAIProxyConfig(e,t,r);if(a)return[null,null,a];const c=new FileManager(this.dc,this.context.AccountBackupDc,this.chainUtil,this.dcNodeClient,this.context),l=o,u=await c.getFileFromDc(l,"",cidNeedConnect.NOT_NEED,!1);if(!u)return[[],[],null];const d=toString$9(u),h=await this.handleAllConfig(d,s);if(!h)return[[],[],null];const[p,f]=h;return[p,f,null]}catch(e){return[null,null,e]}}async GetUserOwnAIProxyAuth(e,t,r){if(!this.context.publicKey)return[null,new Error("ErrConnectToAccountPeersFail")];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let n=this.context.AccountBackupDc?.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(n=await this.dc.connectToUserDcPeer(e.raw),!n)return[null,Errors.ErrNoDcPeerConnected]}if(null===n)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===n.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==n.token&&await n.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const i=new AIProxyClient(n,this.context),[o,s]=await i.GetUserOwnAIProxyAuth(e,t,r);if(s)return[null,s];try{return[JSON.parse(o),s]}catch(s){return[null,s]}}async DoAIProxyCall(e,t,r,n,i,o,s){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0,u=arguments.length>10?arguments[10]:void 0;n.startsWith("keyvalue_")||(n="keyvalue_"+n);const d=await this.chainUtil.getBlockHeight()||0,h=uint32ToLittleEndianBytes(d||0),p=s?1:0,f=uint32ToLittleEndianBytes(p),y=(new TextEncoder).encode(r),g=(new TextEncoder).encode(n),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(i),w=(new TextEncoder).encode(l),v=(new TextEncoder).encode(c),S=(new TextEncoder).encode(o),$=(new TextEncoder).encode(u),x=new Uint8Array([...g,...b,...y,...h,...m,...w,...S,...f,...$,...v]);if(!this.context.AccountBackupDc.client)throw new Error("ErrConnectToAccountPeersFail");if(!this.context.publicKey)throw new Error("ErrConnectToAccountPeersFail");""==this.context.AccountBackupDc.client.token&&await this.context.AccountBackupDc.client.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const E=await this.context.sign(x),A=new AIProxyClient(this.context.AccountBackupDc.client,this.context);return await A.DoAIProxyCall(e,t,r,n,i,l||"",c||"",o,u||"",p,d,E,a)}}const logger$2=createLogger("KeyValueModule");class AIProxyModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.AIPROXY}),Object.defineProperty(this,"aiProxyManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"aiCallConfig",{enumerable:!0,configurable:!0,writable:!0,value:null})}async initialize(e){try{return this.aiProxyManager=new AIProxyManager(e.dcutil,e.dcNodeClient,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$2.error("AI代理模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async createProxyConfig(e,t){try{return this.assertInitialized(),this.aiProxyManager.createProxyConfig(e,t)}catch(e){return Promise.resolve([null,e])}}async deleteProxyConfig(e,t){try{return this.assertInitialized(),this.aiProxyManager.deleteProxyConfig(e,t)}catch(e){return Promise.resolve([null,e])}}configAIProxy(e,t,r,n,i,o){try{return this.assertInitialized(),this.aiProxyManager.configAIProxy(e,t,r,n,i,o)}catch(e){return Promise.resolve([null,e])}}async configAuth(e,t,r,n,i,o,s){try{return this.assertInitialized(),this.aiProxyManager.configAuth(e,t,r,n,i,o,s)}catch(e){return Promise.resolve([null,e])}}async GetAIProxyConfig(e,t,r,n){try{return this.assertInitialized(),this.aiProxyManager.GetAIProxyConfig(e,t,r,n)}catch(e){return Promise.resolve([null,null,e])}}async GetUserOwnAIProxyAuth(e,t,r){try{return this.assertInitialized(),this.aiProxyManager.GetUserOwnAIProxyAuth(e,t,r)}catch(e){return Promise.resolve([null,e])}}async DoAIProxyCall(e,t,r,n,i,o,s,a,c,l,u){try{if(this.assertInitialized(),!(null!=this.aiCallConfig||i&&o&&s&&a))throw new Error("AI调用配置未设置");let d="";if(c?d=JSON.stringify(c):this.aiCallConfig?.headers&&(d=JSON.stringify(this.aiCallConfig.headers)),s||(s=this.aiCallConfig?.theme),!s)throw new Error("配置主题不能为空");if(i||(i=this.aiCallConfig?.appId),!i)throw new Error("应用ID不能为空");if(o||(o=this.aiCallConfig?.themeAuthor),!o)throw new Error("主题作者公钥不能为空");if(a||(a=this.aiCallConfig?.service),!a)throw new Error("服务名称不能为空");return[await this.aiProxyManager.DoAIProxyCall(e,i,o,s,a,t,r,n,d,l||this.aiCallConfig?.path,u||this.aiCallConfig?.model),null]}catch(e){return logger$2.error("AI代理调用失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async SetAICallConfig(e){try{return this.assertInitialized(),this.aiCallConfig=e,null}catch(e){return logger$2.error("设置AI调用配置失败:",e),e}}assertInitialized(){if(!this.initialized)throw new Error("键值存储模块未初始化")}}class UtilClient{constructor(e){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e}async setAppInfo(e,t,r,n,i,o,s,a){if(null==this.client.p2pNode)throw new Error("p2pNode is null");try{const c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),l=new dcnet.pb.SetAppInfoRequest;l.appId=e,l.ownerAccount=t,l.rewardAccount=r,l.domain=n,l.blockheight=i,l.peerid=(new TextEncoder).encode(o),l.fid=(new TextEncoder).encode(s),l.signature=a;const u=dcnet.pb.SetAppInfoRequest.encode(l).finish();try{return void await c.unaryCall("/dcnet.pb.Service/SetAppInfo",u,3e4)}catch(e){throw e}}catch(e){throw e}}}class UtilManager{constructor(e){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.connectedDc=e.connectedDc,this.dc=e.dcutil,this.chainUtil=e.dcChain,this.context=e}async setAppInfo(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"";if(!this.context.publicKey||!this.context.ethAddress)throw Errors$a.NO_USER_INFO;if(!this.connectedDc.client)throw Errors$a.NO_DC_PEER_CONNECTED;if(!this.connectedDc.nodeAddr)throw Errors$a.NO_DC_PEER_CONNECTED;const o=await(this.chainUtil?.getBlockHeight());if(void 0===o)throw Errors$a.FAIL_TO_GET_BLOCKHEIGHT;let s=this.context.publicKey.bytes();r&&r.length>10&&(s=Ed25519PubKey.unmarshalString(r).bytes());let a=hexToBytes(this.context.ethAddress.slice(2));if(n&&n.length>10&&(a=hexToBytes(n.slice(2))),""==this.connectedDc.client.token){if(!await this.connectedDc.client.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),(async e=>this.context.sign(e))))throw Errors$a.FAIL_TO_GET_TOKEN}const c=new UtilClient(this.connectedDc.client),l=this.connectedDc.nodeAddr.getPeerId()||"",u=(new TextEncoder).encode(l),d=(new TextEncoder).encode(e),h=(new TextEncoder).encode(t),p=uint32ToLittleEndianBytes(o),f=new Uint8Array(d.length+h.length+s.length+a.length+p.length+u.length+i.length);let y=0;f.set(d,y),y+=d.length,f.set(s,y),y+=s.length,f.set(a,y),y+=a.length,f.set(h,y),y+=h.length,f.set(p,y),y+=p.length,f.set(u,y),y+=u.length,f.set((new TextEncoder).encode(i),y);const g=await this.context.sign(f);await c.setAppInfo(d,s,a,h,o,l,i,g)}async getAppInfo(e){if(!this.connectedDc.client)throw Errors$a.NO_DC_PEER_CONNECTED;if(!this.chainUtil)throw Errors$a.NO_CHAIN_UTIL;return await this.chainUtil.getAPPInfo(e)}}const logger$1=createLogger("UtilModule");class UtilModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.UTIL}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"utilManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async initialize(e){try{return this.context=e,this.utilManager=new UtilManager(e),this.initialized=!0,!0}catch(e){return logger$1.error("工具模块初始化失败:",e),!1}}createSymmetricKey(){return SymmetricKey.new()}createThreadKey(){return new Key(SymmetricKey.new(),SymmetricKey.new())}async setAppInfo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;if(!this.initialized)return[null,new Error("UtilModule not initialized")];try{if(!e)throw new Error("appId are required");if(!this.context.publicKey||!this.context.ethAddress)throw Errors$a.NO_USER_INFO;(!n||n.length<10)&&(n=this.context.publicKey.string()),(!i||i.length<10)&&(i=this.context.ethAddress);const[o,s]=await this.getAppInfo(e);return o&&!s&&o.owner==n&&o.rewarder==i&&o.domain==r&&o.fid==t||await this.utilManager.setAppInfo(e,r,n,i,t),[!0,null]}catch(e){return[null,e]}}async getAppInfo(e){if(!this.initialized)return[null,new Error("UtilModule not initialized")];try{return[await this.utilManager.getAppInfo(e),null]}catch(e){return[null,e]}}async shutdown(){this.initialized=!1}async handleIpfsRequest(e,t,r){if(this.initialized)try{await handleIpfsRequest(e,t,r)}catch(e){logger$1.error("页面处理IPFS请求失败:",e)}}}const logger=createLogger("DC");class DC{constructor(e){Object.defineProperty(this,"blockChainAddr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"backChainAddr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcNodeClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcutil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"publicKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbThreadId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"ethAddress",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"AccountBackupDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"Identity",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"Blockheight",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"grpcServer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"appInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldReturnUserInfo",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"accountInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userInfo",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"dbManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"swUrl",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"swInited",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"moduleSystem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"init",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(this.initialized)return logger.warn("DC已经初始化,跳过重复初始化"),!0;e&&await e(0);let t=!1;try{if(logger.info("尝试连接主链: "+this.blockChainAddr),t=await this.dcChain.create(this.blockChainAddr),!t&&(logger.info("主链连接失败,尝试备用链: "+this.backChainAddr),t=await this.dcChain.create(this.backChainAddr),!t))return logger.error("dcchainapi 初始化失败: 无法连接任何链"),!1;e&&await e(1),logger.info("链节点连接成功"),this.dcNodeClient=await(this.dcutil?._createHeliaNode()),logger.info("Helia节点创建成功"),this.grpcServer=new DCGrpcServer(this.dcNodeClient.libp2p,dc_protocol),this.grpcServer.start(),logger.info("GRPC服务器启动成功");let r=await(this.dcutil?.getDefaultDcNodeAddr());if(!r)return logger.error("获取DC节点地址失败"),!1;logger.info("获取DC节点地址成功: "+r.toString());try{await(this.dcNodeClient?.libp2p.dial(r,{signal:AbortSignal.timeout(5e3)}));logger.info("连接到DC节点成功"),this.connectedDc.nodeAddr=r,this.connectedDc.client=await this.newDcClient(r),e&&await e(2);return await this.moduleSystem.initializeAll()?(this.initialized=!0,e&&await e(3),this.auth&&this.auth.startDcPeerTokenKeepValidTask(),e&&await e(4),!0):(logger.error("模块初始化失败"),!1)}catch(e){return logger.error("连接到DC节点失败:",e),!1}}catch(e){return logger.error("DC初始化失败:",e),!1}}}),Object.defineProperty(this,"sign",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(!this.auth)return new Uint8Array;return this.auth.signWithWallet(e)}}),Object.defineProperty(this,"newDcClient",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(e)try{return new Client(this.dcNodeClient.libp2p,this.dcNodeClient.blockstore,e,dc_protocol)}catch(e){throw logger.error("创建DC客户端失败:",e),e}}}),this.blockChainAddr=e.wssUrl,this.backChainAddr=e.backWssUrl,this.swUrl=e.swUrl||"",this.dcChain=new ChainUtil,this.dcutil=new DcUtil(this.dcChain),this.dcutil.defaultPeerId="12D3KooWEGzh4AcbJrfZMfQb63wncBUpscMEEyiMemSWzEnjVCPf",this.appInfo=e.appInfo||{},this.accountInfo={},void 0!==e.logLevel&&configureLogger({level:e.logLevel}),this.moduleSystem=new ModuleSystem(this),this.registerCoreModules(e.names||[])}registerCoreModules(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(e&&e.length>0)for(const t of e){const e=this.moduleSystem.getModule(t);e?this.moduleSystem.registerModule(e):logger.warn(`模块 ${t} 不存在,跳过注册`)}else this.moduleSystem.registerModule(new FileModule(this.swUrl||"")),this.moduleSystem.registerModule(new AuthModule),this.moduleSystem.registerModule(new CommentModule),this.moduleSystem.registerModule(new DatabaseModule),this.moduleSystem.registerModule(new MessageModule),this.moduleSystem.registerModule(new KeyValueModule),this.moduleSystem.registerModule(new ClientModule),this.moduleSystem.registerModule(new CacheModule),this.moduleSystem.registerModule(new AIProxyModule),this.moduleSystem.registerModule(new UtilModule);logger.info("核心模块注册完成")}registerModule(e){return this.moduleSystem.registerModule(e)}setAppInfo(e){this.appInfo=e}setAccountInfo(e){this.accountInfo=e}setShouldReturnUserInfo(e){this.shouldReturnUserInfo=e}async initUserDB(e,t,r){const n="user_threaddb";let i=null;try{if(this.assertInitialized(),!this.auth)return[null,new Error("用户模块不存在")];const[o,s]=await this.auth.refreshUserInfo();if(s)return[null,s];if(!o)return[null,new Error("用户信息不存在")];if(i=o,!r&&i&&i.dbConfig)try{const[r,o]=await this.auth.decryptWithWallet(i.dbConfigRaw);if(o||!r)return[null,o];const s=(new TextDecoder).decode(r),a=s?s.split("|"):[];if(a&&a.length>=3){const r=a[0]||"",i=a[1]||"",o=a[2]||"";a[3],a[4];if(!this.db)return[null,new Error("数据库模块不存在")];const[s,c]=await this.db.getDBInfo(r);if(null!=s&&!c){if(t){if(await this.db.loadVerno(r)!=t){const n=await this.db.upgradeCollections(r,e);if(n)return[null,n];await this.db.saveVerno(r,t)}await this.db.upgradeCollections(r,e)}return this.db.refreshDBFromDC(r),setTimeout((()=>{this.db&&this.db.syncDBToDC(r)}),5e3),this.dbThreadId=s.id,[s,null]}if(""!=r){await this.db.syncDbFromDC(r,n,"",i,o,!0,e);const[t,s]=await this.db.getDBInfo(r);return null==t||s?[null,s||new Error("获取DB失败")]:(this.dbThreadId=t.id,[t,null])}}}catch(e){return[null,e]}if(!this.util)return[null,new Error("util模块不存在")];if(!this.db)return[null,new Error("数据库模块不存在")];const a=this.util.createSymmetricKey(),c=this.util.createSymmetricKey(),[l,u]=await this.db.newDB(n,a.toString(),c.toString(),e);if(u||!l)return[null,u];if(l){if(!await this.setUserDefaultDB(this,l,a.toString(),c.toString()))return[null,new Error("设置用户去中心DB失败")]}if(!this.db)return[null,new Error("数据库模块不存在")];const[d,h]=await this.db.getDBInfo(l);return null==d||h?(this.dbThreadId="",[null,h]):(this.dbThreadId=d.id,[d,null])}catch(e){return[null,e]}}async setUserDefaultDB(e,t,r,n,i){try{if(!e.auth)return!1;await e.auth.setUserDefaultDB(t,r,n,i||"")}catch(e){return!1}return await this.checkSetUserDefaultDB(e)}async checkSetUserDefaultDB(e){return new Promise((async t=>{let r=0,n=setInterval((async()=>{if(r++,r>20&&(n&&clearInterval(n),r=0,t(!1)),e.auth){const[i,o]=await e.auth.refreshUserInfo();!o&&i&&i.dbConfig&&(n&&clearInterval(n),r=0,t(!0))}}),1e3)}))}async shutdown(){logger.info("开始关闭DC..."),await this.moduleSystem.shutdownAll(),this.grpcServer&&(this.grpcServer.stop(),logger.info("GRPC服务器已停止")),this.dcNodeClient&&this.dcNodeClient.libp2p&&(await this.dcNodeClient.libp2p.stop(),logger.info("libp2p连接已关闭")),this.initialized=!1,logger.info("DC已成功关闭")}async exit(){this.AccountBackupDc={},this.publicKey=void 0,this.dbThreadId="",this.ethAddress="",this.auth&&this.auth.exitLogin(),logger.info("DC已退出并清理资源")}setPublicKey(e){this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new Error("公钥未初始化");return this.publicKey}getPubkeyRaw(){if(!this.publicKey)throw new Error("公钥未初始化");return this.publicKey.raw}isInitialized(){return this.initialized}getRegisteredModules(){return this.moduleSystem.getRegisteredModules()}getModule(e){try{this.assertInitialized();const t=this.moduleSystem.getModule(e);if(!t)throw new Error(`模块 ${e} 不存在或未注册`);return t}catch(e){return null}}assertInitialized(){if(!this.initialized)throw new Error("DC未初始化,请先调用init()方法")}get file(){return this.getModule(exports.CoreModuleName.FILE)}get auth(){return this.getModule(exports.CoreModuleName.AUTH)}get comment(){return this.getModule(exports.CoreModuleName.COMMENT)}get db(){return this.getModule(exports.CoreModuleName.DATABASE)}get message(){return this.getModule(exports.CoreModuleName.MESSAGE)}get keyValue(){return this.getModule(exports.CoreModuleName.KEYVALUE)}get client(){return this.getModule(exports.CoreModuleName.CLIENT)}get cache(){return this.getModule(exports.CoreModuleName.CACHE)}get aiproxy(){return this.getModule(exports.CoreModuleName.AIPROXY)}get util(){return this.getModule(exports.CoreModuleName.UTIL)}}"undefined"==typeof Promise||Promise.withResolvers||(Promise.withResolvers=function(){let e,t;return{promise:new Promise(((r,n)=>{e=r,t=n})),resolve:e,reject:t}}),exports.AIProxyModule=AIProxyModule,exports.AuthModule=AuthModule,exports.CacheModule=CacheModule,exports.ClientModule=ClientModule,exports.CommentModule=CommentModule,exports.DC=DC,exports.DatabaseModule=DatabaseModule,exports.Ed25519PrivKey=Ed25519PrivKey,exports.Ed25519PubKey=Ed25519PubKey,exports.Errors=Errors$a,exports.FileModule=FileModule,exports.KeyManager=KeyManager,exports.KeyValueModule=KeyValueModule,exports.MessageModule=MessageModule,exports.ModuleSystem=ModuleSystem,exports.OffChainOpTimes=OffChainOpTimes,exports.OffChainOpTimesLimit=OffChainOpTimesLimit,exports.OffChainSpaceLimit=OffChainSpaceLimit,exports.UtilModule=UtilModule,exports.configureLogger=configureLogger,exports.createLogger=createLogger,exports.dc_protocol=dc_protocol,exports.dial_timeout=dial_timeout,exports.isServiceWorkerActive=isServiceWorkerActive,exports.keyExpire=keyExpire,exports.registerServiceWorker=registerServiceWorker,exports.updateServiceWorker=updateServiceWorker,exports.walletOrigin=walletOrigin,exports.walletUrl=walletUrl,exports.walletWindowName=walletWindowName}));
7
+ deps: ${i}}`}};const i={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function(e){let{schema:t}=e;const r={},n={};for(const e in t){if("__proto__"===e)continue;(Array.isArray(t[e])?r:n)[e]=t[e]}return[r,n]}(e);o(e,t),s(e,r)}};function o(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:i,data:o,it:s}=e;if(0===Object.keys(r).length)return;const a=i.let("missing");for(const c in r){const l=r[c];if(0===l.length)continue;const u=(0,n.propertyInData)(i,o,c,s.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),s.allErrors?i.if(u,(()=>{for(const t of l)(0,n.checkReportMissingProp)(e,t)})):(i.if(t._`${u} && (${(0,n.checkMissingProp)(e,l,a)})`),(0,n.reportMissingProp)(e,a),i.else())}}function s(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:i,data:o,keyword:s,it:a}=e,c=i.name("valid");for(const l in t)(0,r.alwaysValidSchema)(a,t[l])||(i.if((0,n.propertyInData)(i,o,l,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:s,schemaProp:l},c);e.mergeValidEvaluated(t,c)}),(()=>i.var(c,!0))),e.ok(c))}e.validatePropertyDeps=o,e.validateSchemaDeps=s,e.default=i}(dependencies)),dependencies}var propertyNames={},hasRequiredPropertyNames;function requirePropertyNames(){if(hasRequiredPropertyNames)return propertyNames;hasRequiredPropertyNames=1,Object.defineProperty(propertyNames,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:t=>{let{params:r}=t;return e._`{propertyName: ${r.propertyName}}`}},code(r){const{gen:n,schema:i,data:o,it:s}=r;if((0,t.alwaysValidSchema)(s,i))return;const a=n.name("valid");n.forIn("key",o,(t=>{r.setParams({propertyName:t}),r.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},a),n.if((0,e.not)(a),(()=>{r.error(!0),s.allErrors||n.break()}))})),r.ok(a)}};return propertyNames.default=r,propertyNames}var additionalProperties={},hasRequiredAdditionalProperties;function requireAdditionalProperties(){if(hasRequiredAdditionalProperties)return additionalProperties;hasRequiredAdditionalProperties=1,Object.defineProperty(additionalProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireNames(),n=requireUtil$2(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:e=>{let{params:r}=e;return t._`{additionalProperty: ${r.additionalProperty}}`}},code(i){const{gen:o,schema:s,parentSchema:a,data:c,errsCount:l,it:u}=i;if(!l)throw new Error("ajv implementation error");const{allErrors:d,opts:h}=u;if(u.props=!0,"all"!==h.removeAdditional&&(0,n.alwaysValidSchema)(u,s))return;const p=(0,e.allSchemaProperties)(a.properties),f=(0,e.allSchemaProperties)(a.patternProperties);function y(e){o.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===h.removeAdditional||h.removeAdditional&&!1===s)y(e);else{if(!1===s)return i.setParams({additionalProperty:e}),i.error(),void(d||o.break());if("object"==typeof s&&!(0,n.alwaysValidSchema)(u,s)){const r=o.name("valid");"failing"===h.removeAdditional?(b(e,r,!1),o.if((0,t.not)(r),(()=>{i.reset(),y(e)}))):(b(e,r),d||o.if((0,t.not)(r),(()=>o.break())))}}}function b(e,t,r){const o={keyword:"additionalProperties",dataProp:e,dataPropType:n.Type.Str};!1===r&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(o,t)}o.forIn("key",c,(r=>{p.length||f.length?o.if(function(r){let s;if(p.length>8){const t=(0,n.schemaRefOrVal)(u,a.properties,"properties");s=(0,e.isOwnProperty)(o,t,r)}else s=p.length?(0,t.or)(...p.map((e=>t._`${r} === ${e}`))):t.nil;return f.length&&(s=(0,t.or)(s,...f.map((n=>t._`${(0,e.usePattern)(i,n)}.test(${r})`)))),(0,t.not)(s)}(r),(()=>g(r))):g(r)})),i.ok(t._`${l} === ${r.default.errors}`)}};return additionalProperties.default=i,additionalProperties}var properties$1={},hasRequiredProperties;function requireProperties(){if(hasRequiredProperties)return properties$1;hasRequiredProperties=1,Object.defineProperty(properties$1,"__esModule",{value:!0});const e=requireValidate(),t=requireCode(),r=requireUtil$2(),n=requireAdditionalProperties(),i={keyword:"properties",type:"object",schemaType:"object",code(i){const{gen:o,schema:s,parentSchema:a,data:c,it:l}=i;"all"===l.opts.removeAdditional&&void 0===a.additionalProperties&&n.default.code(new e.KeywordCxt(l,n.default,"additionalProperties"));const u=(0,t.allSchemaProperties)(s);for(const e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&!0!==l.props&&(l.props=r.mergeEvaluated.props(o,(0,r.toHash)(u),l.props));const d=u.filter((e=>!(0,r.alwaysValidSchema)(l,s[e])));if(0===d.length)return;const h=o.name("valid");for(const e of d)p(e)?f(e):(o.if((0,t.propertyInData)(o,c,e,l.opts.ownProperties)),f(e),l.allErrors||o.else().var(h,!0),o.endIf()),i.it.definedProperties.add(e),i.ok(h);function p(e){return l.opts.useDefaults&&!l.compositeRule&&void 0!==s[e].default}function f(e){i.subschema({keyword:"properties",schemaProp:e,dataProp:e},h)}}};return properties$1.default=i,properties$1}var patternProperties={},hasRequiredPatternProperties;function requirePatternProperties(){if(hasRequiredPatternProperties)return patternProperties;hasRequiredPatternProperties=1,Object.defineProperty(patternProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireUtil$2(),n=requireUtil$2(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(i){const{gen:o,schema:s,data:a,parentSchema:c,it:l}=i,{opts:u}=l,d=(0,e.allSchemaProperties)(s),h=d.filter((e=>(0,r.alwaysValidSchema)(l,s[e])));if(0===d.length||h.length===d.length&&(!l.opts.unevaluated||!0===l.props))return;const p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,f=o.name("valid");!0===l.props||l.props instanceof t.Name||(l.props=(0,n.evaluatedPropsToName)(o,l.props));const{props:y}=l;function g(e){for(const t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function b(r){o.forIn("key",a,(s=>{o.if(t._`${(0,e.usePattern)(i,r)}.test(${s})`,(()=>{const e=h.includes(r);e||i.subschema({keyword:"patternProperties",schemaProp:r,dataProp:s,dataPropType:n.Type.Str},f),l.opts.unevaluated&&!0!==y?o.assign(t._`${y}[${s}]`,!0):e||l.allErrors||o.if((0,t.not)(f),(()=>o.break()))}))}))}!function(){for(const e of d)p&&g(e),l.allErrors?b(e):(o.var(f,!0),b(e),o.if(f))}()}};return patternProperties.default=i,patternProperties}var not={},hasRequiredNot;function requireNot(){if(hasRequiredNot)return not;hasRequiredNot=1,Object.defineProperty(not,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:r,schema:n,it:i}=t;if((0,e.alwaysValidSchema)(i,n))return void t.fail();const o=r.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,(()=>t.reset()),(()=>t.error()))},error:{message:"must NOT be valid"}};return not.default=t,not}var anyOf={},hasRequiredAnyOf;function requireAnyOf(){if(hasRequiredAnyOf)return anyOf;hasRequiredAnyOf=1,Object.defineProperty(anyOf,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:requireCode().validateUnion,error:{message:"must match a schema in anyOf"}};return anyOf.default=e,anyOf}var oneOf={},hasRequiredOneOf;function requireOneOf(){if(hasRequiredOneOf)return oneOf;hasRequiredOneOf=1,Object.defineProperty(oneOf,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:t=>{let{params:r}=t;return e._`{passingSchemas: ${r.passing}}`}},code(r){const{gen:n,schema:i,parentSchema:o,it:s}=r;if(!Array.isArray(i))throw new Error("ajv implementation error");if(s.opts.discriminator&&o.discriminator)return;const a=i,c=n.let("valid",!1),l=n.let("passing",null),u=n.name("_valid");r.setParams({passing:l}),n.block((function(){a.forEach(((i,o)=>{let a;(0,t.alwaysValidSchema)(s,i)?n.var(u,!0):a=r.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},u),o>0&&n.if(e._`${u} && ${c}`).assign(c,!1).assign(l,e._`[${l}, ${o}]`).else(),n.if(u,(()=>{n.assign(c,!0),n.assign(l,o),a&&r.mergeEvaluated(a,e.Name)}))}))})),r.result(c,(()=>r.reset()),(()=>r.error(!0)))}};return oneOf.default=r,oneOf}var allOf={},hasRequiredAllOf;function requireAllOf(){if(hasRequiredAllOf)return allOf;hasRequiredAllOf=1,Object.defineProperty(allOf,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:r,schema:n,it:i}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=r.name("valid");n.forEach(((r,n)=>{if((0,e.alwaysValidSchema)(i,r))return;const s=t.subschema({keyword:"allOf",schemaProp:n},o);t.ok(o),t.mergeEvaluated(s)}))}};return allOf.default=t,allOf}var _if={},hasRequired_if;function require_if(){if(hasRequired_if)return _if;hasRequired_if=1,Object.defineProperty(_if,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil$2(),r={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:t=>{let{params:r}=t;return e.str`must match "${r.ifClause}" schema`},params:t=>{let{params:r}=t;return e._`{failingKeyword: ${r.ifClause}}`}},code(r){const{gen:i,parentSchema:o,it:s}=r;void 0===o.then&&void 0===o.else&&(0,t.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const a=n(s,"then"),c=n(s,"else");if(!a&&!c)return;const l=i.let("valid",!0),u=i.name("_valid");if(function(){const e=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);r.mergeEvaluated(e)}(),r.reset(),a&&c){const e=i.let("ifClause");r.setParams({ifClause:e}),i.if(u,d("then",e),d("else",e))}else a?i.if(u,d("then")):i.if((0,e.not)(u),d("else"));function d(t,n){return()=>{const o=r.subschema({keyword:t},u);i.assign(l,u),r.mergeValidEvaluated(o,l),n?i.assign(n,e._`${t}`):r.setParams({ifClause:t})}}r.pass(l,(()=>r.error(!0)))}};function n(e,r){const n=e.schema[r];return void 0!==n&&!(0,t.alwaysValidSchema)(e,n)}return _if.default=r,_if}var thenElse={},hasRequiredThenElse,hasRequiredApplicator;function requireThenElse(){if(hasRequiredThenElse)return thenElse;hasRequiredThenElse=1,Object.defineProperty(thenElse,"__esModule",{value:!0});const e=requireUtil$2(),t={keyword:["then","else"],schemaType:["object","boolean"],code(t){let{keyword:r,parentSchema:n,it:i}=t;void 0===n.if&&(0,e.checkStrictMode)(i,`"${r}" without "if" is ignored`)}};return thenElse.default=t,thenElse}function requireApplicator(){if(hasRequiredApplicator)return applicator;hasRequiredApplicator=1,Object.defineProperty(applicator,"__esModule",{value:!0});const e=requireAdditionalItems(),t=requirePrefixItems(),r=requireItems(),n=requireItems2020(),i=requireContains(),o=requireDependencies(),s=requirePropertyNames(),a=requireAdditionalProperties(),c=requireProperties(),l=requirePatternProperties(),u=requireNot(),d=requireAnyOf(),h=requireOneOf(),p=requireAllOf(),f=require_if(),y=requireThenElse();return applicator.default=function(){let g=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const b=[u.default,d.default,h.default,p.default,f.default,y.default,s.default,a.default,o.default,c.default,l.default];return g?b.push(t.default,n.default):b.push(e.default,r.default),b.push(i.default),b},applicator}var format$1={},format={},hasRequiredFormat$1,hasRequiredFormat;function requireFormat$1(){if(hasRequiredFormat$1)return format;hasRequiredFormat$1=1,Object.defineProperty(format,"__esModule",{value:!0});const e=requireCodegen(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:t=>{let{schemaCode:r}=t;return e.str`must match format "${r}"`},params:t=>{let{schemaCode:r}=t;return e._`{format: ${r}}`}},code(t,r){const{gen:n,data:i,$data:o,schema:s,schemaCode:a,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:h}=c;l.validateFormats&&(o?function(){const o=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),s=n.const("fDef",e._`${o}[${a}]`),c=n.let("fType"),u=n.let("format");n.if(e._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,(()=>n.assign(c,e._`${s}.type || "string"`).assign(u,e._`${s}.validate`)),(()=>n.assign(c,e._`"string"`).assign(u,s))),t.fail$data((0,e.or)(!1===l.strictSchema?e.nil:e._`${a} && !${u}`,function(){const t=d.$async?e._`(${s}.async ? await ${u}(${i}) : ${u}(${i}))`:e._`${u}(${i})`,n=e._`(typeof ${u} == "function" ? ${t} : ${u}.test(${i}))`;return e._`${u} && ${u} !== true && ${c} === ${r} && !${n}`}()))}():function(){const o=h.formats[s];if(!o)return void function(){if(!1===l.strictSchema)return void h.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===o)return;const[a,c,p]=function(t){const r=t instanceof RegExp?(0,e.regexpCode)(t):l.code.formats?e._`${l.code.formats}${(0,e.getProperty)(s)}`:void 0,i=n.scopeValue("formats",{key:s,ref:t,code:r});if("object"==typeof t&&!(t instanceof RegExp))return[t.type||"string",t.validate,e._`${i}.validate`];return["string",t,i]}(o);a===r&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!d.$async)throw new Error("async format in sync schema");return e._`await ${p}(${i})`}return"function"==typeof c?e._`${p}(${i})`:e._`${p}.test(${i})`}())}())}};return format.default=t,format}function requireFormat(){if(hasRequiredFormat)return format$1;hasRequiredFormat=1,Object.defineProperty(format$1,"__esModule",{value:!0});const e=[requireFormat$1().default];return format$1.default=e,format$1}var metadata={},hasRequiredMetadata,hasRequiredDraft7;function requireMetadata(){return hasRequiredMetadata||(hasRequiredMetadata=1,Object.defineProperty(metadata,"__esModule",{value:!0}),metadata.contentVocabulary=metadata.metadataVocabulary=void 0,metadata.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],metadata.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),metadata}function requireDraft7(){if(hasRequiredDraft7)return draft7;hasRequiredDraft7=1,Object.defineProperty(draft7,"__esModule",{value:!0});const e=requireCore(),t=requireValidation(),r=requireApplicator(),n=requireFormat(),i=requireMetadata(),o=[e.default,t.default,(0,r.default)(),n.default,i.metadataVocabulary,i.contentVocabulary];return draft7.default=o,draft7}var discriminator={},types$1={},hasRequiredTypes$1,hasRequiredDiscriminator;function requireTypes$1(){return hasRequiredTypes$1||(hasRequiredTypes$1=1,Object.defineProperty(types$1,"__esModule",{value:!0}),types$1.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(e||(types$1.DiscrError=e={}))),types$1;var e}function requireDiscriminator(){if(hasRequiredDiscriminator)return discriminator;hasRequiredDiscriminator=1,Object.defineProperty(discriminator,"__esModule",{value:!0});const e=requireCodegen(),t=requireTypes$1(),r=requireCompile(),n=requireRef_error(),i=requireUtil$2(),o={message:e=>{let{params:{discrError:r,tagName:n}}=e;return r===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`},params:t=>{let{params:{discrError:r,tag:n,tagName:i}}=t;return e._`{error: ${r}, tag: ${i}, tagValue: ${n}}`}},s={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(o){const{gen:s,data:a,schema:c,parentSchema:l,it:u}=o,{oneOf:d}=l;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const p=s.let("valid",!1),f=s.const("tag",e._`${a}${(0,e.getProperty)(h)}`);function y(t){const r=s.name("valid"),n=o.subschema({keyword:"oneOf",schemaProp:t},r);return o.mergeEvaluated(n,e.Name),r}s.if(e._`typeof ${f} == "string"`,(()=>function(){const a=function(){var e;const t={},o=a(l);let s=!0;for(let t=0;t<d.length;t++){let l=d[t];if((null==l?void 0:l.$ref)&&!(0,i.schemaHasRulesButRef)(l,u.self.RULES)){const e=l.$ref;if(l=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),l instanceof r.SchemaEnv&&(l=l.schema),void 0===l)throw new n.default(u.opts.uriResolver,u.baseId,e)}const p=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[h];if("object"!=typeof p)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(o||a(l)),c(p,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function a(e){let{required:t}=e;return Array.isArray(t)&&t.includes(h)}function c(e,t){if(e.const)p(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const r of e.enum)p(r,t)}}function p(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=r}}();s.if(!1);for(const t in a)s.elseIf(e._`${f} === ${t}`),s.assign(p,y(a[t]));s.else(),o.error(!1,{discrError:t.DiscrError.Mapping,tag:f,tagName:h}),s.endIf()}()),(()=>o.error(!1,{discrError:t.DiscrError.Tag,tag:f,tagName:h}))),o.ok(p)}};return discriminator.default=s,discriminator}var $schema="http://json-schema.org/draft-07/schema#",$id="http://json-schema.org/draft-07/schema#",title="Core schema meta-schema",definitions={schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type$1=["object","boolean"],properties={$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},require$$3={$schema:$schema,$id:$id,title:title,definitions:definitions,type:type$1,properties:properties,default:!0},hasRequiredAjv;function requireAjv(){return hasRequiredAjv||(hasRequiredAjv=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=requireCore$1(),n=requireDraft7(),i=requireDiscriminator(),o=require$$3,s=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach((e=>this.addVocabulary(e))),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(o,s):o;this.addMetaSchema(e,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var l=requireValidate();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=requireCodegen();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=requireValidation_error();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=requireRef_error();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(ajv,ajv.exports)),ajv.exports}var ajvExports=requireAjv(),Ajv=getDefaultExportFromCjs(ajvExports);const{Buffer:Buffer$2}=buffer$1,dsDispatcherPrefix=DBPrefix.dsPrefix.child(new Key$1("dispatcher"));class Dispatcher{constructor(e){Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reducers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.store=e,this.reducers=[],this.lock={lock:()=>{},unlock:()=>{}},this.lastID=0}getStore(){return this.store}register(e){this.lock.lock(),this.lastID++,this.reducers.push(e),this.lock.unlock()}async dispatch(e){this.lock.lock();const t=await this.store.newTransactionExtended(!1);try{for(const r of e){const e=this.getKey(r),n=Buffer$2.from(jsonStringify(r));await t.put(e,n)}await t.commit()}catch(e){throw t.discard(),e}finally{this.lock.unlock()}this.reducers.map((async t=>{await t.reduce(e)}))}async*query(e){return this.store.query(e)}getKey(e){const t=e.timestamp,r=e.collection,n=e.instanceID;return dsDispatcherPrefix.child(new Key$1(t.toString())).child(new Key$1(r.toString())).child(new Key$1(n.toString()))}}class Query{constructor(){Object.defineProperty(this,"ands",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"ors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,writable:!0,value:new Sort}),Object.defineProperty(this,"seek",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"limit",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"skip",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:""}),this.ands=[],this.ors=[],this.sort=new Sort,this.seek="",this.limit=0,this.skip=0,this.index=""}validate(){if(!this)return null;for(const e of this.ands){const t=e.validate();if(t)return t}for(const e of this.ors){const t=e.validate();if(t)return t}return null}and(e){return new Criterion(e)}or(e){return this.ors.push(e),this}useIndex(e){return this.index=e,this}orderBy(e){return this.sort.fieldPath=e,this.sort.desc=!1,this}orderByDesc(e){return this.sort.fieldPath=e,this.sort.desc=!0,this}orderById(){return this.sort.fieldPath="_id",this.sort.desc=!1,this}orderByIdDesc(){return this.sort.fieldPath="_id",this.sort.desc=!0,this}seekId(e){return this.seek=e,this}limitTo(e){return this.limit=e,this}skipNum(e){return this.skip=e,this}match(e){if(!this)throw new Error("query can't be null");let t=!0;for(const r of this.ands)try{const n=traverseFieldPathMap(e,r.fieldPath),i=r.match(n);if(t=t&&i,!t)break}catch(e){return!1}if(t)return!0;for(const t of this.ors)try{if(t.match(e))return!0}catch(e){return!1}return!1}}class Criterion{constructor(e,t,r){Object.defineProperty(this,"fieldPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:Operation.eq}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:new Value}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.fieldPath=e,this.operation=t,this.value=r}validate(){if(!this)return null;let e=0;return null!==this.value.bool&&e++,null!==this.value.string&&e++,null!==this.value.float&&e++,1!==e?new Error("value type should describe exactly one type"):null}eq(e){return this.createCriterion(Operation.eq,e)}ne(e){return this.createCriterion(Operation.ne,e)}gt(e){return this.createCriterion(Operation.gt,e)}lt(e){return this.createCriterion(Operation.lt,e)}ge(e){return this.createCriterion(Operation.ge,e)}le(e){return this.createCriterion(Operation.le,e)}createCriterion(e,t){return this.operation=e,this.value=createValue(t),this.query||(this.query=new Query),this.query.ands.push(this),this.query}match(e){try{const t=compareValue(e,this.value);switch(this.operation){case Operation.eq:return 0===t;case Operation.ne:return 0!==t;case Operation.gt:return t>0;case Operation.lt:return t<0;case Operation.le:return t<=0;case Operation.ge:return t>=0;default:throw new Error("invalid operation")}}catch(e){return!1}}}class Value{constructor(){Object.defineProperty(this,"string",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"bool",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"float",{enumerable:!0,configurable:!0,writable:!0,value:null})}}class Sort{constructor(){Object.defineProperty(this,"fieldPath",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"desc",{enumerable:!0,configurable:!0,writable:!0,value:!1})}}var Operation;function createValue(e){const t=new Value;return"string"==typeof e?t.string=e:"boolean"==typeof e?t.bool=e:"number"==typeof e&&(t.float=e),t}function compareValue(e,t){if(null!==t.string){return("string"==typeof e?e:"").localeCompare(t.string)}if(null!==t.bool){return("boolean"==typeof e&&e)===t.bool?0:-1}if(null!==t.float){const r="number"==typeof e?e:0;return r===t.float?0:r<t.float?-1:1}throw new Error("no underlying value for criterion was provided")}function traverseFieldPathMap(e,t){const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n)return;n=n[e]}return n}function compare(e,t){if(e===t)return 0;if(typeof e!=typeof t)throw new Error("Cannot compare different types");if("string"==typeof e)return e.localeCompare(t);if("number"==typeof e)return e-t;if("boolean"==typeof e)return e===t?0:e?1:-1;throw new Error("Cannot compare values of type "+typeof e)}!function(e){e[e.eq=0]="eq",e[e.ne=1]="ne",e[e.gt=2]="gt",e[e.lt=3]="lt",e[e.ge=4]="ge",e[e.le=5]="le",e[e.fn=6]="fn"}(Operation||(Operation={}));const iteratorKeyMinCacheSize=100;class IndexError extends Error{constructor(e){super(e),this.name="IndexError"}}new IndexError("unique constraint violation");const ErrNotIndexable=new IndexError("value not indexable"),ErrCantCreateUniqueIndex=new IndexError("can't create unique index (duplicate instances exist)"),ErrIndexNotFound=new IndexError("index not found"),indexPrefix=new Key$1("_index"),indexTypes=["string","number","integer","boolean"];class InvalidSortingFieldError extends Error{constructor(){super("sorting field doesn't correspond to instance type"),this.name="InvalidSortingFieldError"}}new InvalidSortingFieldError;class ThreadDBError extends Error{constructor(e){super(e),this.name="ThreadDBError"}}const ErrInvalidCollectionSchemaPath=new ThreadDBError("collection schema does not contain path"),ErrCollectionNotFound=new ThreadDBError("collection not found");new ThreadDBError("collection already registered");const ErrInstanceNotFound=new ThreadDBError("instance not found"),ErrReadonlyTx=new ThreadDBError("read only transaction"),ErrInvalidSchemaInstance=new ThreadDBError("instance doesn't correspond to schema");new ThreadDBError("invalid collection schema"),new ThreadDBError("invalid collection name");const errMissingInstanceID=new ThreadDBError("invalid instance: missing _id attribute"),errAlreadyDiscardedCommitedTxn=new ThreadDBError("can't commit discarded/committed txn"),errCantCreateExistingInstance=new ThreadDBError("can't create already existing instance"),baseKey$1=dsPrefix.child(new Key$1("collection")),vmTimeout=200,writeValidatorFn="_validate",readFilterFn="_filter",EmptyInstanceID="";function NewInstanceID(){return nanoid$1()}class BrowserJSRuntime{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:vmTimeout;Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"functions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:null})}runScript(e){try{const t=new Function("context",`\n with(context) { \n ${e}; \n return context; \n }\n `);let r=!1;return this.timeoutId=window.setTimeout((()=>{}),this.timeout),this.context=t(this.context)||this.context,r=!0,this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),!0}catch(e){throw this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),new Error(`Script execution error: ${e instanceof Error?e.message:String(e)}`)}}getGlobal(e){return this.context[e]}call(e){const t=this.context[e];if("function"!=typeof t)throw new Error(`${e} is not a function`);try{let e=!1;this.timeoutId=window.setTimeout((()=>{}),this.timeout);for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];const o=t.apply(this.context,n);return e=!0,this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),o}catch(e){throw this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),new Error(`Function execution error: ${e instanceof Error?e.message:String(e)}`)}}}class Collection{constructor(e,t,r,n,i){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"db",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"rawWriteValidator",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"rawReadFilter",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"schemaValidator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"vm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writeValidator",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"readFilter",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"indexes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.schemaValidator=new Ajv({allErrors:!0}),this.vm=new BrowserJSRuntime(vmTimeout),n&&this.compileAndLoadValidator(n,writeValidatorFn,["writer","event","instance"]),i&&this.compileAndLoadValidator(i,readFilterFn,["reader","instance"])}compileAndLoadValidator(e,t,r){try{const n=`function ${t}(${r.join(",")}) {${e}}`;this.vm.runScript(n);if("function"!=typeof this.vm.getGlobal(t))throw new Error(`${t} is not a function`);t===writeValidatorFn?this.writeValidator=(e,t,r)=>this.vm.call(writeValidatorFn,e,t,r):t===readFilterFn&&(this.readFilter=(e,t)=>this.vm.call(readFilterFn,e,t))}catch(e){throw new Error(`Failed to compile ${t}: ${e instanceof Error?e.message:String(e)}`)}}baseKey(){return baseKey$1.child(new Key$1(this.name))}getName(){return this.name}getSchema(){return(new TextEncoder).encode(JSON.stringify(this.schema))}getWriteValidator(){return(new TextEncoder).encode(this.rawWriteValidator||"")}getReadFilter(){return(new TextEncoder).encode(this.rawReadFilter||"")}async readTxn(e,t){return this.db.readTxn(this,e,t)}async writeTxn(e,t){return this.db.writeTxn(this,e,t)}async findByID(e,t){let r=null;return await this.readTxn((async t=>{r=await t.findByID(e)}),t),r}async create(e,t){let r="";return await this.writeTxn((async t=>{const n=await t.create(e);n.length>0&&(r=n[0])}),t),r}async createMany(e,t){let r=[];return await this.writeTxn((async t=>{r=await t.create(...e)}),t),r}async delete(e,t){await this.writeTxn((async t=>{await t.delete(e)}),t)}async deleteMany(e,t){await this.writeTxn((async t=>{await t.delete(...e)}),t)}async save(e,t){await this.writeTxn((async t=>{await t.save(e)}),t)}async saveMany(e,t){await this.writeTxn((async t=>{await t.save(...e)}),t)}async verify(e,t){await this.writeTxn((async t=>{await t.verify(e)}),t)}async verifyMany(e,t){await this.writeTxn((async t=>{await t.verify(...e)}),t)}async has(e,t){let r=!1;return await this.readTxn((async t=>{r=await t.has(e)}),t),r}async hasMany(e,t){let r=!1;return await this.readTxn((async t=>{r=await t.has(...e)}),t),r}async find(e,t){let r=[];return await this.readTxn((async t=>{r=await t.find(e)}),t),r}async modifiedSince(e,t){let r=[];return await this.readTxn((async t=>{r=await t.modifiedSince(e)}),t),r}validInstance(e){try{const t=JSON.parse((new TextDecoder).decode(e)),r=this.schemaValidator.compile(this.schema);if(!r(t)&&r.errors&&r.errors.length>0){let e="";for(let t=0;t<r.errors.length;t++){const n=r.errors[t];e+=`${n?.schemaPath}: ${n?.message}`,t!==r.errors.length-1&&(e+="; ")}throw new Error(`${ErrInvalidSchemaInstance.message}: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(ErrInvalidSchemaInstance.message))throw e;throw new Error(`Error validating instance: ${e instanceof Error?e.message:String(e)}`)}}async validWrite(e,t){if(this.writeValidator)try{const r=e?e.toString():null,n=await t.marshal(),i=JSON.parse((new TextDecoder).decode(n));let o=null;try{const e=this.baseKey().child(new Key$1(t.instanceID)),r=await this.db.datastore.get(e);r&&(o=JSON.parse((new TextDecoder).decode(r)))}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(!0!==this.writeValidator(r,i,o))throw new Error("Write validation failed")}catch(e){throw new Error(`Write validation error: ${e instanceof Error?e.message:String(e)}`)}}async filterRead(e,t){if(!this.readFilter)return t;try{const r=e?e.toString():null,n=JSON.parse((new TextDecoder).decode(t)),i=this.readFilter(r,n);return null===i?null:(new TextEncoder).encode(jsonStringify(i))}catch(e){throw new Error(`Read filter error: ${e instanceof Error?e.message:String(e)}`)}}getIndexes(){if(0===this.indexes.size)return[];const e=[];return this.indexes.forEach(((t,r)=>{r!==idFieldName&&e.push(t)})),e}async addIndex(e,t){if(e.path!==idFieldName||!this.indexes.has(idFieldName))try{const r=getSchemaTypeAtPath(this.schema,e.path);let n=!1;for(const e of indexTypes)if(r?.type===e){n=!0;break}if(!n)throw ErrNotIndexable;const i=this.indexes.get(e.path);if(i&&i.unique===e.unique)return;if(e.unique&&e.path!==idFieldName){const r=new Map,n=await this.find(new Query,t);for(const t of n){const n=traverseFieldPathMap(t,e.path);if(void 0!==n){if(r.has(n))throw ErrCantCreateUniqueIndex;r.set(n,!0)}}}this.indexes.set(e.path,e),await this.saveIndexes()}catch(e){throw e}}async dropIndex(e){if(e===idFieldName)throw new Error(`${idFieldName} index cannot be dropped`);this.indexes.delete(e),await this.saveIndexes()}async saveIndexes(){try{const e={};this.indexes.forEach(((t,r)=>{e[r]=t}));const t=(new TextEncoder).encode(JSON.stringify(e));await this.db.datastore.put(DBPrefix.dsIndexes.child(new Key$1(this.name)),t)}catch(e){throw new Error(`Failed to save indexes: ${e instanceof Error?e.message:String(e)}`)}}async indexAdd(e,t,r){for(const[n,i]of this.indexes.entries())try{const o=decode$e(r);await this.indexUpdate(n,i,e,t,o,!1)}catch(e){throw e}}async indexDelete(e,t,r){for(const[n,i]of this.indexes.entries())try{await this.indexUpdate(n,i,e,t,r,!0)}catch(e){throw e}}async indexUpdate(e,t,r,n,i,o){try{const s=getIndexValue(e,i),a=indexPrefix.child(this.baseKey()).child(new Key$1(e)).child(new Key$1(s.toString().substring(1)));let c=null;try{c=await r.get(a)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}const l=new KeyList;if(c){const e=JSON.parse((new TextDecoder).decode(c));l.fromArray(e)}if(o?l.remove(n):(t.unique&&l.remove(n),l.add(n)),0===l.size())await r.delete(a);else{const e=(new TextEncoder).encode(JSON.stringify(l.toArray()));await r.put(a,e)}}catch(e){if(e===ErrNotIndexable)return;throw e}}}function getIndexValue(e,t){const r=traverseFieldPathMap(JSON.parse((new TextDecoder).decode(t)),e);if(void 0===r)throw ErrNotIndexable;return new Key$1(String(r))}class KeyList{constructor(){Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:[]})}add(e){const t=e.uint8Array();let r=this.binarySearch(t);r<this.keys.length&&this.bytesEqual(this.keys[r],t)||this.keys.splice(r,0,t)}remove(e){const t=e.uint8Array();let r=this.binarySearch(t);r<this.keys.length&&this.keys[r]&&this.bytesEqual(this.keys[r],t)&&this.keys.splice(r,1)}in(e){const t=e.uint8Array(),r=this.binarySearch(t);return r<this.keys.length&&void 0!==this.keys[r]&&this.bytesEqual(this.keys[r],t)}size(){return this.keys.length}toArray(){return[...this.keys]}fromArray(e){this.keys=[...e]}binarySearch(e){let t=0,r=this.keys.length-1;for(;t<=r;){const n=Math.floor((t+r)/2),i=this.bytesCompare(this.keys[n],e);if(i<0)t=n+1;else{if(!(i>0))return n;r=n-1}}return t}bytesCompare(e,t){const r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return e.length<t.length?-1:e.length>t.length?1:0}bytesEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}}class Txn{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];Object.defineProperty(this,"collection",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"readonly",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"actions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"discarded",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"committed",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async create(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=new Array(t.length);for(let e=0;e<t.length;e++){if(this.readonly)throw ErrReadonlyTx;const r=t[e].slice(0);let i=await getInstanceID(r);if(i===EmptyInstanceID){const t=setNewInstanceID(r);i=t.id;const o=t.data;this.collection.validInstance(o),n[e]=i;const s=this.collection.baseKey().child(new Key$1(i));try{if(await this.collection.db.datastore.has(s))throw errCantCreateExistingInstance}catch(e){if(e!==errCantCreateExistingInstance)throw new Error(`Error checking if instance exists: ${e instanceof Error?e.message:String(e)}`);throw e}const{data:a}=setModifiedTag(o);this.actions.push({type:CoreActionType.Create,instanceID:i,collectionName:this.collection.name,current:a})}}return n}async verify(){try{const n=await(this.token?.pubKey());if(!n)throw new Error("Identity not found");for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const i=await this.createSaveActions(n,...t),{events:o}=await this.createEvents(i);if(0===o.length)return;for(const e of o)await this.collection.validWrite(n,e)}catch(e){throw new Error(`Verification failed: ${e instanceof Error?e.message:String(e)}`)}}async save(){try{const n=await(this.token?.pubKey())||null;for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const i=await this.createSaveActions(n,...t);this.actions.push(...i)}catch(e){throw new Error(`Save failed: ${e instanceof Error?e.message:String(e)}`)}}async createSaveActions(e){const t=[];for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];for(let r=0;r<n.length;r++){if(this.readonly)throw ErrReadonlyTx;const i=n[r].slice(0);this.collection.validInstance(i);const{data:o}=setModifiedTag(i),s=await getInstanceID(o);if(s===EmptyInstanceID)throw errMissingInstanceID;const a=this.collection.baseKey().child(new Key$1(s));let c;try{c=await this.collection.db.datastore.get(a)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e;c=(new TextEncoder).encode("{}")}if(c.length>0&&null!==e){c=await this.collection.filterRead(e,c)||c}t.push({type:CoreActionType.Save,instanceID:s,collectionName:this.collection.name,previous:c,current:o})}return t}async delete(){for(let e=0;e<arguments.length;e++){if(this.readonly)throw ErrReadonlyTx;const t=this.collection.baseKey().child(new Key$1(e<0||arguments.length<=e?void 0:arguments[e]));await this.collection.db.datastore.has(t)&&this.actions.push({type:CoreActionType.Delete,instanceID:e<0||arguments.length<=e?void 0:arguments[e],collectionName:this.collection.name})}}async has(){const e=await(this.collection.db.connector?.validate(this.token));if(e)throw e;const t=await(this.token?.pubKey());for(let e=0;e<arguments.length;e++){const r=this.collection.baseKey().child(new Key$1(e<0||arguments.length<=e?void 0:arguments[e]));if(!await this.collection.db.datastore.has(r))return!1;{if(!this.collection.readFilter)continue;const e=await this.collection.db.datastore.get(r);if(!await this.collection.filterRead(t,e))return!1}}return!0}async findByID(e){const t=await(this.collection.db.connector?.validate(this.token));if(t)throw t;const r=this.collection.baseKey().child(new Key$1(e));let n;try{n=await this.collection.db.datastore.get(r)}catch(e){if("ERR_NOT_FOUND"===e.code)throw ErrInstanceNotFound;throw e}const i=await(this.token?.pubKey()),o=await this.collection.filterRead(i,n);if(!o)throw ErrInstanceNotFound;let s;try{s=JSON.parse((new TextDecoder).decode(o))}catch(e){s={}}return s}async find(e){try{const t=await(this.collection.db.connector?.validate(this.token));if(t)throw t;e||(e=new Query);const r=e.validate();if(r)throw new Error(`Invalid query: ${r.message}`);const n=await this.collection.db.datastore.newTransactionExtended(!0);try{const t=await this.newIterator(n,this.collection.baseKey(),e);try{const r=await(this.token?.pubKey()),n=[];let i=0;for(;;){const o=await t.next();if(!o||!1==!o.done)break;let s=null;try{s=await this.collection.filterRead(r,o.value)}catch(e){throw new Error(`Filter read error: ${e instanceof Error?e.message:String(e)}`)}if(s&&(i++,i>e.skip)){let e;try{e=JSON.parse((new TextDecoder).decode(s))}catch(t){e={}}n.push({instanceID:o.instanceID,key:o.key,value:s,marshaledValue:e})}if(e.limit>0&&n.length===e.limit)break}e.sort.fieldPath&&e.sort.fieldPath!==idFieldName&&n.sort(((t,r)=>{const n=traverseFieldPathMap(t.marshaledValue||{},e.sort.fieldPath),i=traverseFieldPathMap(r.marshaledValue||{},e.sort.fieldPath);if(void 0===n||void 0===i)return void 0===n&&void 0===i?0:void 0===n?-1:1;try{let t=compare(n,i);return e.sort.desc&&(t*=-1),t}catch(e){return 0}}));const o=n.map((e=>e.marshaledValue));return o}finally{t&&"function"==typeof t.close&&await t.close()}}finally{n.discard()}}catch(e){throw new Error(`Find operation failed: ${e instanceof Error?e.message:String(e)}`)}}async newIterator(e,t,r){const n={prefix:t.toString()};r.index&&(n.index=r.index),r.seek&&(n.start=t.child(new Key$1(r.seek)).toString());const i=await e.query(n);return{async next(){const e=await i.next();if(e.done)return{done:!0};if(e.value&&r&&e.value.value)try{const t=JSON.parse((new TextDecoder).decode(e.value.value));if(!r.match(t))return this.next()}catch(e){}return{done:!1,key:e.value.key,instanceID:new Key$1(e.value.key).name(),value:e.value.value}},async close(){i&&"function"==typeof i.return&&await i.return()}}}async modifiedSince(e){const t=await this.collection.db.datastore.newTransactionExtended(!0);try{const r=e=>{const t=e.key.toString();return new Key$1(t).type()===this.collection.name},n=e.toString(),i=t.queryExtended({prefix:dsDispatcherPrefix.toString(),filters:[r],seekPrefix:dsDispatcherPrefix.child(new Key$1(n)).toString()}),o=new Set;for await(const e of i){const t=new Key$1(e.key).name();o.add(t)}return Array.from(o)}finally{t.discard()}}async commit(){try{const{events:e,node:t}=await this.createEvents(this.actions);if(!t)return;await(this.collection.db.connector?.createNetRecord(t,this.token)),await(this.collection.db.dispatcher?.dispatch(e)),this.committed=!0}catch(e){throw new Error(`Commit failed: ${e instanceof Error?e.message:String(e)}`)}}discard(){this.discarded=!0}refreshCollection(){const e=this.collection.db.collections.get(this.collection.name);if(!e)throw ErrCollectionNotFound;this.collection=e}async createEvents(e){if(this.discarded||this.committed)throw errAlreadyDiscardedCommitedTxn;try{const[t,r]=await this.collection.db.eventcodec.create(e);return 0===t.length&&r?{events:[],node:null}:{events:t,node:r}}catch(e){throw new Error(`Error creating events: ${e instanceof Error?e.message:String(e)}`)}}}function getSchemaTypeAtPath(e,t){const r=t.split(".");let n=e;for(const t of r){if(n=getSchemaTypeProperties(n,e.definitions)[t],!n)throw ErrInvalidCollectionSchemaPath}return n}function getSchemaTypeProperties(e,t){if(!e)return{};let r=e.properties||{};if(e.$ref){const n=e.$ref.split("/");if(n.length>0){const e=n[n.length-1],i=t?.[e];i&&(r=i.properties||{})}}return r}async function getInstanceID(e){try{const t=JSON.parse((new TextDecoder).decode(e));return t._id?t._id:EmptyInstanceID}catch(e){throw new Error(`Error getting instance ID: ${e instanceof Error?e.message:String(e)}`)}}function setNewInstanceID(e){const t=NewInstanceID();try{const r=JSON.parse((new TextDecoder).decode(e));return r._id=t,{id:t,data:(new TextEncoder).encode(JSON.stringify(r))}}catch(e){throw new Error(`Error setting instance ID: ${e instanceof Error?e.message:String(e)}`)}}function setModifiedTag(e){const t=1000000n*BigInt(Date.now())+BigInt(Math.floor(1e6*Math.random()));try{const r=JSON.parse((new TextDecoder).decode(e));r["_mod"]=t;return{time:t,data:(new TextEncoder).encode(jsonStringify(r))}}catch(e){throw new Error(`设置 _mod 字段失败: ${e instanceof Error?e.message:String(e)}`)}}let Iterator$1=class{constructor(e,t){Object.defineProperty(this,"nextKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"txn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyCache",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"iter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.txn=e,this.query=t,this.nextKeys=async()=>[]}async nextSync(){if(""===this.query.index){const e={result:{entry:{},error:null}};let t=!1;for await(const r of this.iter.next())try{const n=JSON.parse((new TextDecoder).decode(r.value));if(t=this.query.match(n),e.result.error)break;if(t)return{result:r,marshaledValue:n}}catch(t){e.result.error=t;break}return t?e:null}if(0===this.keyCache.length)try{const e=await this.nextKeys();if(0===e.length)return{result:{entry:{},error:null}};this.keyCache=[...this.keyCache,...e]}catch(e){return{result:{entry:{},error:e}}}const e=this.keyCache[0];this.keyCache=this.keyCache.slice(1);try{const t=await this.txn.get(e);return{result:{entry:{key:e.toString(),value:t},error:null}}}catch(e){return{result:{entry:{},error:e}}}}async close(){this.iter&&"function"==typeof this.iter.close&&await this.iter.close()}};async function newIterator(e,t,r){const n=new Iterator$1(e,r);let i;i=r.index?indexPrefix.child(t).child(new Key$1(r.index)):t;const o={query:{prefix:i.toString()}};r.sort.fieldPath===idFieldName&&(r.sort.desc?o.orders=[{orderByKeyDescending:!0}]:o.orders=[{orderByKey:!0}]),r.seek&&(o.seekPrefix=i.child(new Key$1(r.seek)).toString());try{const t=await e.queryExtended(o);if(n.iter=t,!r.index)return n.nextKeys=async()=>[],n;let s=!0;return n.nextKeys=async()=>{const e=[];for(;e.length<iteratorKeyMinCacheSize;){const t=await n.iter.nextSync();if(!t){if(s)throw ErrIndexNotFound;return e}s=!1;const o=new Key$1(t.result.entry.key),a=i.name(),c=o.name();let l=c;if(isValidJSON(c)){const e=JSON.parse(c);l=null!==e?e:c}else l=c;try{const n=JSON.stringify({[a]:l}),i=JSON.parse(n);if(r.match(i)){const r=decodeKeyList(t.result.entry.value);for(const t of r)e.push(new Key$1((new TextDecoder).decode(t)))}}catch(e){continue}}return e},n}catch(e){throw e}}function isValidJSON(e){try{return JSON.parse(e),!0}catch{return!1}}function decodeKeyList(e){if(!e)return[];try{return JSON.parse((new TextDecoder).decode(e))}catch{return[]}}const DAG_CBOR_CODEC={name:name$4,code:code$4,encode:encode$b,decode:decode$e};class JsonPatcher{async create(e){const t=this.convertActions(e),r={patches:t},n=await wrapObject(r);return[this.wrapEvents(t),n]}async reduce(e,t,r,n){const i=await t.newTransactionExtended(!1);try{const t=[];for(const o of this.sortEvents(e)){const e=await this.parseEvent(o);await this.processEvent(e,r,i,n),t.push({type:e.patch.type,collection:e.collectionName||"default",instanceID:e.iD})}return await i.commit(),t}catch(e){throw i.discard(),this.wrapError(e)}}async eventsFromBytes(e){let t=await decode$e(e);if(t&&"object"==typeof t&&"patches"in t&&Array.isArray(t.patches))return this.wrapEvents(t.patches);throw new Error("Invalid block format: expected RecordEvents with patches array")}convertActions(e){const t=BigInt(1e6*Date.now()+Math.floor(1e6*Math.random()));return e.map((e=>({timestamp:t,iD:e.instanceID,collectionName:e.collectionName||"default",patch:e.current?{type:e.type,instanceID:e.instanceID,jSONPatch:e.current}:{type:e.type,instanceID:e.instanceID,jSONPatch:new Uint8Array}})))}wrapEvents(e){return e&&0!==e.length?e.map((e=>({collection:e.collectionName||"default",instanceID:e.iD||e.patch.instanceID,timestamp:e.timestamp,payload:e.patch.jSONPatch?e.patch.jSONPatch:new Uint8Array,marshal:async()=>this.marshalPatchEvent(e)}))):[]}async marshalPatchEvent(e){return encode$b({t:e.timestamp,i:e.iD||e.iD,c:e.collectionName,op:{type:e.patch.type,id:e.patch.instanceID,patch:e.patch.jSONPatch?e.patch.jSONPatch:new Uint8Array}})}sortEvents(e){return[...e].sort(((e,t)=>e.timestamp<t.timestamp?-1:e.timestamp>t.timestamp?1:0))}async parseEvent(e){const t=decode$e(await e.marshal());return{timestamp:t.t,iD:t.i,collectionName:t.c,patch:{type:t.op.type,instanceID:t.op.id,jSONPatch:t.op.patch?encode$b(t.op.patch):new Uint8Array}}}async processEvent(e,t,r,n){const i=t.child(new Key$1(e.collectionName||"default")).child(new Key$1(e.iD)),o=await r.get(i).catch((()=>{})),s=e.patch.type===CoreActionType.Delete?void 0:e.patch.jSONPatch;if(await n(e.collectionName||"default",i,r,o,s),e.patch.type===CoreActionType.Delete)await r.delete(i);else if(s){const e=decode$e(s);if(!e)throw new Error("Failed to decode JSON patch");await r.put(i,e)}}wrapError(e){return new Error(`JSONPATCHER_ERROR: ${e.message}`)}}Object.defineProperty(JsonPatcher,"ENCODER_SETTINGS",{enumerable:!0,configurable:!0,writable:!0,value:{codec:DAG_CBOR_CODEC,hasher:sha256$3,cidVersion:1}});const baseKey=DBPrefix.dsPrefix.child(new Key$1("collection")),getBlockInitialTimeout=500,getBlockRetries=3;class CollectionExistsError extends Error{constructor(e){super(`Collection ${e} already exists`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="CollectionExistsError"}}class DB{constructor(e,t,r,n){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connector",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"datastore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"eventcodec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"collections",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"localEventsBus",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webLock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writeQueue",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),this.datastore=e,this.name=n.name||"unnamed",this.eventcodec=n.eventCodec||new JsonPatcher,this.webLock="webLock_db_"+r}static async newDB(e,t,r,n){const i=n||new NewOptions;i.eventCodec||(i.eventCodec=new JsonPatcher);const o=new DB(e,t,r.toString(),i);o.name="",o.dispatcher=new Dispatcher(e),o.localEventsBus=new LocalEventsBus;try{await o.loadName()}catch(e){throw new Error("Failed to load DB name")}const s=o.name;i.name?o.name=i.name:""===s&&(o.name="unnamed"),await o.saveName(s),await o.reCreateCollections(),o.dispatcher.register(o);try{const e=await t.connectApp(o,r);o.connector=e}catch(e){throw new Error(`Failed to connect app: ${e instanceof Error?e.message:String(e)}`)}if(i.collections&&i.collections.length>0)for(const e of i.collections)try{await o.newCollection(e)}catch(e){throw new Error(`Failed to create collection: ${e instanceof Error?e.message:String(e)}`)}return o}async getDBInfo(e){try{const t=await(this.connector?.net.getThread(this.connector?.threadId,{token:e?.token}));return{id:this.connector?this.connector.threadId.toString():"",name:this.name,addrs:t?t.addrs.map((e=>e.toString())):[],key:t?t.key?.toString():""}}catch(e){throw new Error(`Failed to get DB info: ${e instanceof Error?e.message:String(e)}`)}}async saveName(e){if(this.name!==e){if(!this.name.match(/^[a-zA-Z0-9_-]+$/))throw new Error("Invalid name");await this.datastore.put(DBPrefix.dsName,(new TextEncoder).encode(this.name))}}async loadName(){try{const e=await this.datastore.get(DBPrefix.dsName);e&&(this.name=(new TextDecoder).decode(e))}catch(e){}}async saveVerno(e){await this.datastore.put(DBPrefix.dsVerno,(new TextEncoder).encode(e.toString()))}async loadVerno(){try{const e=await this.datastore.get(DBPrefix.dsVerno);if(e)return parseInt((new TextDecoder).decode(e))}catch(e){}return 0}async initCollections(e){for(const t of e)await this.newCollection(t)}async upgradeCollections(e){for(const t of e)await this.newCollection(t,!0)}async newCollection(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.collections.has(e.name)&&!t)throw new CollectionExistsError(e.name);const r=new Collection(e.name,e.schema,this);await r.addIndex({path:"_id",unique:!0});for(const t of e.indexes||[])await r.addIndex(t);return this.saveCollection(r),r}async saveCollection(e){try{await this.datastore.put(DBPrefix.dsSchemas.child(new Key$1(e.name)),e.getSchema()),e.rawWriteValidator&&await this.datastore.put(DBPrefix.dsValidators.child(new Key$1(e.name)),(new TextEncoder).encode(e.rawWriteValidator)),e.rawReadFilter&&await this.datastore.put(DBPrefix.dsFilters.child(new Key$1(e.name)),(new TextEncoder).encode(e.rawReadFilter)),this.collections.set(e.name,e)}catch(t){throw new Error(`Failed to save collection ${e.name}: ${t instanceof Error?t.message:String(t)}`)}}async reCreateCollections(){try{const e=this.datastore.query({prefix:DBPrefix.dsSchemas.toString()});try{for await(const t of e){const e=t.key.name(),r=JSON.parse((new TextDecoder).decode(t.value));let n,i;try{const t=await this.datastore.get(DBPrefix.dsValidators.child(new Key$1(e)));n=(new TextDecoder).decode(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}try{const t=await this.datastore.get(DBPrefix.dsFilters.child(new Key$1(e)));i=(new TextDecoder).decode(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}const o=new Collection(e,r,this);try{const t=await this.datastore.get(DBPrefix.dsIndexes.child(new Key$1(e))),r=JSON.parse((new TextDecoder).decode(t));for(const[e,t]of Object.entries(r))e&&o.indexes.set(e,t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}this.collections.set(o.name,o)}}catch(e){throw new Error(`Error re-creating collections: ${e instanceof Error?e.message:String(e)}`)}}catch(e){throw new Error(`Error re-creating collections: ${e instanceof Error?e.message:String(e)}`)}}getCollection(e){const t=this.collections.get(e);if(!t)throw new Error(`Collection ${e} not found`);return t}async close(){}async reduce(e){try{const t=(await this.eventcodec.reduce(e,this.datastore,baseKey,this.defaultIndexFunc())).map((e=>({collectionName:e.collection,type:e.type,instanceID:e.instanceID})));this.notifyStateChanged(t)}catch(e){throw new Error(`Error reducing events: ${e instanceof Error?e.message:String(e)}`)}}defaultIndexFunc(){return async(e,t,r,n,i)=>{const o=this.collections.get(e);if(!o)throw new Error(`collection (${e}) not found`);n&&await o.indexDelete(r,t,n),i&&await o.indexAdd(r,t,i)}}notifyStateChanged(e){this.localEventsBus}async notifyTxnEvents(e,t){try{await(this.localEventsBus?.send({node:e,token:t}))}catch(e){throw new Error(`Failed to notify transaction events: ${e instanceof Error?e.message:String(e)}`)}}async dispatch(e){for(const t of e)await this.reduce([t])}async validateNetRecordBody(e,t){try{const t=await this.eventcodec.eventsFromBytes(e.data());if(0===t.length)return;for(const e of t){if(!this.collections.get(e.collection))return Errors$6.ErrCollectionNotFound}return}catch(e){return e}}async handleNetRecord(e,t){let r;try{if(!this.connector)return new Error("no connector");r=await EventFromRecord(this.connector?.net.bstore,e.value())}catch(t){try{const t=await this.getBlockWithRetry(e.value());r=await EventFromNode(t)}catch(e){return e}}try{const e=await r.getBody(this.connector?.net,t.read()),n=await this.eventcodec.eventsFromBytes(e.rawData());await this.dispatch(n)}catch(e){return new Error(`error when processing event: ${e instanceof Error?e.message:String(e)}`)}}async getNetRecordCreateTime(e,t){let r,n,i;if(!this.connector)throw new Error("no connector");try{r=await EventFromRecord(this.connector?.net.bstore,e.value())}catch(t){try{const t=await this.getBlockWithRetry(e.value());r=await EventFromNode(t)}catch(e){throw new Error(`Error when decoding block to event: ${e instanceof Error?e.message:String(e)}`)}}try{n=await r.getBody(this.connector?.net.bstore,t.read())}catch(t){throw new Error(`Error when getting body of event on thread ${this.connector?.threadId}/${e.logID()}: ${t instanceof Error?t.message:String(t)}`)}try{i=await this.eventcodec.eventsFromBytes(n.data())}catch(e){throw new Error(`Error when unmarshaling event from bytes: ${e instanceof Error?e.message:String(e)}`)}if(0===i.length)throw new Error("No events found in record");return i[0].timestamp}async getBlockWithRetry(e){let t=getBlockInitialTimeout;if(!this.connector)throw new Error("no connector");for(let r=1;r<=getBlockRetries;r++)try{return await e.getBlock(this.connector?.net.bstore)}catch(e){await new Promise((e=>setTimeout(e,t))),t*=2}}async readTxn(e,t,r){const n=new Txn(e,r,!0);try{await t(n)}finally{n.discard()}}async writeTxn(e,t,r){const n=this.writeQueue,i=new Promise(((i,o)=>{n.catch((()=>{})).finally((async()=>{const n=new Txn(e,r,!1);try{await t(n),await n.commit(),i()}catch(e){o(e)}finally{n.discard()}}))}));return this.writeQueue=i.catch((()=>Promise.resolve())),i}}function isKeyFilter(e){return"key"===e.$type&&"string"==typeof e.key}function isPrefixFilter(e){return"prefix"===e.$type&&"string"==typeof e.prefix}function createTransformedDatastore(e,t){return new TransformedDatastore(e,t)}class TransformedDatastore extends BaseDatastore{constructor(e,t){super(),Object.defineProperty(this,"child",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"transform",{enumerable:!0,configurable:!0,writable:!0,value:t})}async put(e,t,r){return this.child.put(this.transform.convert(e),t,r)}async get(e,t){return this.child.get(this.transform.convert(e))}async has(e,t){return this.child.has(this.transform.convert(e),t)}async delete(e,t){return this.child.delete(this.transform.convert(e),t)}async beginTransaction(){const e=await this.getTransaction();return new TransformedTransaction(e,this.transform)}async newTransactionExtended(e){const t=await this.getTransaction();return new TransformedTransaction(t,this.transform)}async getTransaction(){if("function"==typeof this.child.newTransactionExtended)return this.child.newTransactionExtended(!1);throw new Error("Transactions not supported by underlying datastore")}async*query(e){const t=this.queryExtended(e);for await(const e of t)yield{key:new Key$1(e.key),value:e.value}}async*queryExtended(e){const t=this.transformQuery(e);for await(const e of this.child.query(t)){const t=this.transform.invert(new Key$1(e.key.toString()));t&&(yield{...e,key:t.toString()})}}transformQuery(e){return FilterProcessor.process(e,this.transform)}}class TransformedTransaction{constructor(e,t){Object.defineProperty(this,"txn",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"transform",{enumerable:!0,configurable:!0,writable:!0,value:t})}async put(e,t){return this.txn.put(this.transform.convert(e),t)}async delete(e){return this.txn.delete(this.transform.convert(e))}async get(e){return this.txn.get(this.transform.convert(e))}async has(e){return this.txn.has(this.transform.convert(e))}async commit(){return this.txn.commit()}discard(){this.txn.discard()}async*query(e){yield*this.queryExtended(e)}async*queryExtended(e){const t=FilterProcessor.process(e,this.transform);for await(const e of this.txn.queryExtended(t)){const t=this.transform.invert(new Key$1(e.key));t&&(yield{...e,key:t.toString()})}}}class FilterProcessor{static process(e,t){const r=structuredClone(e);return r.prefix&&(r.prefix=t.convert(new Key$1(r.prefix)).toString()),r.filters&&(r.filters=r.filters.map((e=>this.transformFilter(e,t)))),r}static transformFilter(e,t){if(isKeyFilter(e)){const r=t.convert(new Key$1(e.key)).toString(),n=function(e){return e.key.toString()===r};return Object.assign(n,{key:r,$type:"key"}),n}if(isPrefixFilter(e)){const r=t.convert(new Key$1(e.prefix)).toString(),n=function(e){return e.key.toString().startsWith(r)};return Object.assign(n,{prefix:r,$type:"prefix"}),n}throw new Error("Unsupported filter type")}static createKeyFilter(e){return t=>t.key.toString()===e}static createPrefixFilter(e){return t=>t.key.toString().startsWith(e)}}class PrefixTransform{constructor(e){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prefix=new Key$1(e)}convert(e){return new Key$1(this.prefix.toString()+e.toString())}invert(e){const t=e.toString(),r=this.prefix.toString();if(!t.startsWith(r))throw new Error("Invalid prefix");return new Key$1(t.slice(r.length))}}const encoder=new TextEncoder,decoder=new TextDecoder;function concat(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=t.reduce(((e,t)=>{let{length:r}=t;return e+r}),0),i=new Uint8Array(n);let o=0;for(const e of t)i.set(e,o),o+=e.length;return i}function encodeBase64(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}function decodeBase64(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function decode(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:decoder.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=decoder.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return decodeBase64(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function encode(e){let t=e;return"string"==typeof t&&(t=encoder.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):encodeBase64(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class JOSEError extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class JWTClaimValidationFailed extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JWTExpired extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JOSENotSupported extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class JWSInvalid extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class JWTInvalid extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class JWSSignatureVerificationFailed extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0)}}function unusable(e){return new TypeError(`CryptoKey does not support this operation, its ${arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name"} must be ${e}`)}function isAlgorithm(e,t){return e.name===t}function getHashLength(e){return parseInt(e.name.slice(4),10)}function getNamedCurve(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function checkUsage(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function checkSigCryptoKey(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!isAlgorithm(e.algorithm,"HMAC"))throw unusable("HMAC");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!isAlgorithm(e.algorithm,"RSASSA-PKCS1-v1_5"))throw unusable("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!isAlgorithm(e.algorithm,"RSA-PSS"))throw unusable("RSA-PSS");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!isAlgorithm(e.algorithm,"Ed25519"))throw unusable("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!isAlgorithm(e.algorithm,"ECDSA"))throw unusable("ECDSA");const r=getNamedCurve(t);if(e.algorithm.namedCurve!==r)throw unusable(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}checkUsage(e,r)}function message(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];if((n=n.filter(Boolean)).length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var invalidKeyInput=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return message("Key must be ",e,...r)};function withAlg(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return message(`Key for the ${e} algorithm must be `,t,...n)}function isCryptoKey(e){return"CryptoKey"===e?.[Symbol.toStringTag]}function isKeyObject(e){return"KeyObject"===e?.[Symbol.toStringTag]}var isKeyLike=e=>isCryptoKey(e)||isKeyObject(e),isDisjoint=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=t.filter(Boolean);if(0===n.length||1===n.length)return!0;let i;for(const e of n){const t=Object.keys(e);if(i&&0!==i.size)for(const e of t){if(i.has(e))return!1;i.add(e)}else i=new Set(t)}return!0};function isObjectLike(e){return"object"==typeof e&&null!==e}var isObject=e=>{if(!isObjectLike(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t},checkKeyLength=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function subtleMapping(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var importJWK=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=subtleMapping(e),n={...e};return delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!e.d,e.key_ops??r)},validateCrit=(e,t,r,n,i)=>{if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)};function isJWK(e){return isObject(e)&&"string"==typeof e.kty}function isPrivateJWK(e){return"oct"!==e.kty&&"string"==typeof e.d}function isPublicJWK(e){return"oct"!==e.kty&&void 0===e.d}function isSecretJWK(e){return"oct"===e.kty&&"string"==typeof e.k}let cache;const handleJWK=async function(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];cache||=new WeakMap;let i=cache.get(e);if(i?.[r])return i[r];const o=await importJWK({...t,alg:r});return n&&Object.freeze(e),i?i[r]=o:cache.set(e,{[r]:o}),o},handleKeyObject=(e,t)=>{cache||=new WeakMap;let r=cache.get(e);if(r?.[t])return r[t];const n="public"===e.type,i=!!n;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,i,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let r;switch(t){case"RSA-OAEP":r="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":r="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":r="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":r="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:r},i,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:r},i,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const r=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!r)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),"ES384"===t&&"P-384"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),"ES512"===t&&"P-521"===r&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:r},i,n?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[t]=o:cache.set(e,{[t]:o}),o};var normalizeKey=async(e,t)=>{if(e instanceof Uint8Array)return e;if(isCryptoKey(e))return e;if(isKeyObject(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return handleKeyObject(e,t)}catch(e){if(e instanceof TypeError)throw e}let r=e.export({format:"jwk"});return handleJWK(e,r,t)}if(isJWK(e))return e.k?decode(e.k):handleJWK(e,e,t,!0);throw new Error("unreachable")};const tag=e=>e?.[Symbol.toStringTag],jwkMatchesOp=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&!1===t.key_ops?.includes?.(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},symmetricTypeCheck=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(isJWK(t)){if(isSecretJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${tag(t)} instances for symmetric algorithms must be of type "secret"`)}},asymmetricTypeCheck=(e,t,r)=>{if(isJWK(t))switch(r){case"decrypt":case"sign":if(isPrivateJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(isPublicJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw new TypeError(`${tag(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${tag(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw new TypeError(`${tag(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${tag(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};var checkKeyType=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?symmetricTypeCheck(e,t,r):asymmetricTypeCheck(e,t,r)},subtleAlgorithm=(e,t)=>{const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};default:throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}},getSignKey=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(invalidKeyInput(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return checkSigCryptoKey(t,e,r),t},verify=async(e,t,r,n)=>{const i=await getSignKey(e,t,"verify");checkKeyLength(e,i);const o=subtleAlgorithm(e,i.algorithm);try{return await crypto.subtle.verify(o,i,r,n)}catch{return!1}};async function flattenedVerify(e,t,r){if(!isObject(e))throw new JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!isObject(e.header))throw new JWSInvalid("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=decode(e.protected);n=JSON.parse(decoder.decode(t))}catch{throw new JWSInvalid("JWS Protected Header is invalid")}if(!isDisjoint(n,e.header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header};let o=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),r?.crit,n,i).has("b64")&&(o=n.b64,"boolean"!=typeof o))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=i;if("string"!=typeof s||!s)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(o){if("string"!=typeof e.payload)throw new JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let a=!1;"function"==typeof t&&(t=await t(n,e),a=!0),checkKeyType(s,t,"verify");const c=concat(encoder.encode(e.protected??""),encoder.encode("."),"string"==typeof e.payload?encoder.encode(e.payload):e.payload);let l;try{l=decode(e.signature)}catch{throw new JWSInvalid("Failed to base64url decode the signature")}const u=await normalizeKey(t,s);if(!await verify(s,u,l,c))throw new JWSSignatureVerificationFailed;let d;if(o)try{d=decode(e.payload)}catch{throw new JWSInvalid("Failed to base64url decode the payload")}else d="string"==typeof e.payload?encoder.encode(e.payload):e.payload;const h={payload:d};return void 0!==e.protected&&(h.protectedHeader=n),void 0!==e.header&&(h.unprotectedHeader=e.header),a?{...h,key:u}:h}async function compactVerify(e,t,r){if(e instanceof Uint8Array&&(e=decoder.decode(e)),"string"!=typeof e)throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(3!==s)throw new JWSInvalid("Invalid Compact JWS");const a=await flattenedVerify({payload:i,protected:n,signature:o},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}var epoch=e=>Math.floor(e.getTime()/1e3);const minute=60,hour=60*minute,day=24*hour,week=7*day,year=365.25*day,REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var secs=e=>{const t=REGEX.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*minute);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*hour);break;case"day":case"days":case"d":n=Math.round(r*day);break;case"week":case"weeks":case"w":n=Math.round(r*week);break;default:n=Math.round(r*year)}return"-"===t[1]||"ago"===t[4]?-n:n};function validateInput(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}const normalizeTyp=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,checkAudiencePresence=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));function validateClaimsSet(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{r=JSON.parse(decoder.decode(t))}catch{}if(!isObject(r))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:i}=n;if(i&&("string"!=typeof e.typ||normalizeTyp(e.typ)!==normalizeTyp(i)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:o=[],issuer:s,subject:a,audience:c,maxTokenAge:l}=n,u=[...o];void 0!==l&&u.push("iat"),void 0!==c&&u.push("aud"),void 0!==a&&u.push("sub"),void 0!==s&&u.push("iss");for(const e of new Set(u.reverse()))if(!(e in r))throw new JWTClaimValidationFailed(`missing required "${e}" claim`,r,e,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(r.iss))throw new JWTClaimValidationFailed('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new JWTClaimValidationFailed('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!checkAudiencePresence(r.aud,"string"==typeof c?[c]:c))throw new JWTClaimValidationFailed('unexpected "aud" claim value',r,"aud","check_failed");let d;switch(typeof n.clockTolerance){case"string":d=secs(n.clockTolerance);break;case"number":d=n.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=n,p=epoch(h||new Date);if((void 0!==r.iat||l)&&"number"!=typeof r.iat)throw new JWTClaimValidationFailed('"iat" claim must be a number',r,"iat","invalid");if(void 0!==r.nbf){if("number"!=typeof r.nbf)throw new JWTClaimValidationFailed('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>p+d)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(void 0!==r.exp){if("number"!=typeof r.exp)throw new JWTClaimValidationFailed('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=p-d)throw new JWTExpired('"exp" claim timestamp check failed',r,"exp","check_failed")}if(l){const e=p-r.iat;if(e-d>("number"==typeof l?l:secs(l)))throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(e<0-d)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}class JWTClaimsBuilder{#He;constructor(e){if(!isObject(e))throw new TypeError("JWT Claims Set MUST be an object");this.#He=structuredClone(e)}data(){return encoder.encode(JSON.stringify(this.#He))}get iss(){return this.#He.iss}set iss(e){this.#He.iss=e}get sub(){return this.#He.sub}set sub(e){this.#He.sub=e}get aud(){return this.#He.aud}set aud(e){this.#He.aud=e}set jti(e){this.#He.jti=e}set nbf(e){"number"==typeof e?this.#He.nbf=validateInput("setNotBefore",e):e instanceof Date?this.#He.nbf=validateInput("setNotBefore",epoch(e)):this.#He.nbf=epoch(new Date)+secs(e)}set exp(e){"number"==typeof e?this.#He.exp=validateInput("setExpirationTime",e):e instanceof Date?this.#He.exp=validateInput("setExpirationTime",epoch(e)):this.#He.exp=epoch(new Date)+secs(e)}set iat(e){void 0===e?this.#He.iat=epoch(new Date):e instanceof Date?this.#He.iat=validateInput("setIssuedAt",epoch(e)):this.#He.iat=validateInput("setIssuedAt","string"==typeof e?epoch(new Date)+secs(e):e)}}async function jwtVerify(e,t,r){const n=await compactVerify(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const i={payload:validateClaimsSet(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}var sign$1=async(e,t,r)=>{const n=await getSignKey(e,t,"sign");checkKeyLength(e,n);const i=await crypto.subtle.sign(subtleAlgorithm(e,n.algorithm),n,r);return new Uint8Array(i)};class FlattenedSign{#He;#ze;#We;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#He=e}setProtectedHeader(e){if(this.#ze)throw new TypeError("setProtectedHeader can only be called once");return this.#ze=e,this}setUnprotectedHeader(e){if(this.#We)throw new TypeError("setUnprotectedHeader can only be called once");return this.#We=e,this}async sign(e,t){if(!this.#ze&&!this.#We)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!isDisjoint(this.#ze,this.#We))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#ze,...this.#We};let n=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,this.#ze,r).has("b64")&&(n=this.#ze.b64,"boolean"!=typeof n))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');checkKeyType(i,e,"sign");let o,s=this.#He;n&&(s=encoder.encode(encode(s))),o=this.#ze?encoder.encode(encode(JSON.stringify(this.#ze))):encoder.encode("");const a=concat(o,encoder.encode("."),s),c=await normalizeKey(e,i),l={signature:encode(await sign$1(i,c,a)),payload:""};return n&&(l.payload=decoder.decode(s)),this.#We&&(l.header=this.#We),this.#ze&&(l.protected=decoder.decode(o)),l}}class CompactSign{#Ge;constructor(e){this.#Ge=new FlattenedSign(e)}setProtectedHeader(e){return this.#Ge.setProtectedHeader(e),this}async sign(e,t){const r=await this.#Ge.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}class SignJWT{#ze;#Xe;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.#Xe=new JWTClaimsBuilder(e)}setIssuer(e){return this.#Xe.iss=e,this}setSubject(e){return this.#Xe.sub=e,this}setAudience(e){return this.#Xe.aud=e,this}setJti(e){return this.#Xe.jti=e,this}setNotBefore(e){return this.#Xe.nbf=e,this}setExpirationTime(e){return this.#Xe.exp=e,this}setIssuedAt(e){return this.#Xe.iat=e,this}setProtectedHeader(e){return this.#ze=e,this}async sign(e,t){const r=new CompactSign(this.#Xe.data());if(r.setProtectedHeader(this.#ze),Array.isArray(this.#ze?.crit)&&this.#ze.crit.includes("b64")&&!1===this.#ze.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";class ThreadToken{constructor(e){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:e})}static async issue(e,t){const r=await ed25519PrivateKeyToCryptoKey(e.privateKey.raw);return new ThreadToken(await new SignJWT({sub:t.toString(),iss:e.getPublic().toString()}).setProtectedHeader({alg:"EdDSA"}).setIssuedAt().sign(r))}async pubKey(){if(this.value)try{const e=jwtDecode(this.value);if(!e.sub)throw new Error("Token subject is missing");try{return Ed25519PubKey.unmarshalString(e.sub)}catch(e){throw new Error(`Failed to unmarshal public key: ${e instanceof Error?e.message:String(e)}`)}}catch(e){throw e instanceof Error&&e.message.includes("Invalid token")?new Error("Invalid token format"):new Error("Token not found or invalid")}}async validate(e){try{const t=await ed25519PrivateKeyToCryptoKey(e.raw,"raw"),{payload:r}=await jwtVerify(this.value,t);return this.parsePubKey(r.sub)}catch{return}}parsePubKey(e){return new Ed25519PubKey(base32$5.decode(e))}get defined(){return this.value.length>0}}new Headers;const ErrInvalidQueryConditionFormat=new Error("无效的查询条件格式");function parseJsonToQuery(e){const t={condition:"",ors:[],sort:{},seek:"",limit:0,skip:0,index:""};""===e&&(e="{}");try{return Object.assign(t,JSON.parse(e)),dcQueryToDbQuery(t)}catch(e){throw new Error(`解析查询JSON失败: ${e instanceof Error?e.message:String(e)}`)}}function dcQueryToDbQuery(e){try{const t=parseCondition(e.condition),r=new Query;return r.ands=t,r.sort=e.sort,r.seek=e.seek,r.limit=e.limit,r.skip=e.skip,r.index=e.index,r.ors=[],r.ors=e.ors?.map((e=>dcQueryToDbQuery(e)))||[],0===r.limit&&(r.limit=-1),r}catch(e){throw new Error(`转换查询对象失败: ${e instanceof Error?e.message:String(e)}`)}}function parseCondition(e){if(!e)return[];const t=e.split(" and "),r=[];for(const e of t)try{const t=parseSingleCondition(e);if(!t||3!==t.length)continue;const n=parseValue(t[2]),i=new Criterion(t[0],getDbQueryOperation(t[1]),n);r.push(i)}catch(e){continue}return r}function parseValue(e){const t=new Value;if("'"===e[0]||'"'===e[0]){const r=e.substring(1,e.length-1);t.string=r}else if("true"===e||"false"===e){const r="true"===e;t.bool=r}else{const r=parseFloat(e);if(isNaN(r))throw new Error(`无效的数字格式: ${e}`);t.float=r}return t}const splitOp=["!=",">=","<=","=","<>",">","<"];function parseSingleCondition(e){for(const t of splitOp){const r=e.indexOf(t);if(r>0){const n=e.indexOf("'"),i=e.indexOf('"');if(n>0&&r>n||i>0&&r>i)continue;const o=new Array(3);return o[0]=e.substring(0,r).trim(),o[1]=t.trim(),o[2]=e.substring(r+t.length).trim(),o}}throw ErrInvalidQueryConditionFormat}function getDbQueryOperation(e){switch(e.trim()){case"=":default:return Operation.eq;case"!=":case"<>":return Operation.ne;case">":return Operation.gt;case"<":return Operation.lt;case">=":return Operation.ge;case"<=":return Operation.le}}var src$1={exports:{}},src,hasRequiredSrc$1;function requireSrc$1(){if(hasRequiredSrc$1)return src;return hasRequiredSrc$1=1,src=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),o=i.charCodeAt(0);if(255!==t[o])throw new TypeError(i+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),l=Math.log(256)/Math.log(s);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var r=0;if(" "!==e[r]){for(var n=0,i=0;e[r]===a;)n++,r++;for(var o=(e.length-r)*c+1>>>0,l=new Uint8Array(o);e[r];){var u=t[e.charCodeAt(r)];if(255===u)return;for(var d=0,h=o-1;(0!==u||d<i)&&-1!==h;h--,d++)u+=s*l[h]>>>0,l[h]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");i=d,r++}if(" "!==e[r]){for(var p=o-i;p!==o&&0===l[p];)p++;for(var f=new Uint8Array(n+(o-p)),y=n;p!==o;)f[y++]=l[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var c=(o-i)*l+1>>>0,u=new Uint8Array(c);i!==o;){for(var d=t[i],h=0,p=c-1;(0!==d||h<n)&&-1!==p;p--,h++)d+=256*u[p]>>>0,u[p]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var f=c-n;f!==c&&0===u[f];)f++;for(var y=a.repeat(r);f<c;++f)y+=e.charAt(u[f]);return y},decodeUnsafe:u,decode:function(e){var t=u(e);if(t)return t;throw new Error("Non-base"+s+" character")}}},src}var lib={},util$1={},types={},shams$1,hasRequiredShams$1,shams,hasRequiredShams,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,callBound,hasRequiredCallBound,isArguments,hasRequiredIsArguments,isRegex,hasRequiredIsRegex,safeRegexTest,hasRequiredSafeRegexTest,isGeneratorFunction,hasRequiredIsGeneratorFunction,isCallable,hasRequiredIsCallable,forEach,hasRequiredForEach,possibleTypedArrayNames,hasRequiredPossibleTypedArrayNames,availableTypedArrays,hasRequiredAvailableTypedArrays;function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0})}function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN||(hasRequired_isNaN=1,_isNaN=Number.isNaN||function(e){return e!=e}),_isNaN}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var e=require_isNaN();return sign=function(t){return e(t)||0===t?t:t<0?-1:1},sign}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var e=requireGOPD();if(e)try{e([],"length")}catch(t){e=null}return gopd=e}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return esDefineProperty=e}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var e="undefined"!=typeof Symbol&&Symbol,t=requireShams$1();return hasSymbols=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"==typeof e("foo")&&("symbol"==typeof Symbol("bar")&&t())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var o,s=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),a=t(0,i.length-s.length),c=[],l=0;l<a;l++)c[l]="$"+l;if(o=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof o){var e=i.apply(this,r(s,arguments));return Object(e)===e?e:this}return i.apply(n,r(s,arguments))})),i.prototype){var u=function(){};u.prototype=i.prototype,o.prototype=new u,u.prototype=null}return o},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireFunctionCall(),n=requireReflectApply();return actualApply=n||e.call(r,t)}function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var e=requireFunctionBind(),t=requireType(),r=requireFunctionCall(),n=requireActualApply();return callBindApplyHelpers=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var e,t=requireCallBindApplyHelpers(),r=requireGopd();try{e=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return get=n&&"function"==typeof n.get?t([n.get]):"function"==typeof o&&function(e){return o(null==e?e:i(e))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var e=requireReflect_getPrototypeOf(),t=requireObject_getPrototypeOf(),r=requireGet();return getProto=e?function(t){return e(t)}:t?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null,getProto}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;var e;hasRequiredGetIntrinsic=1;var t=requireEsObjectAtoms(),r=requireEsErrors(),n=require_eval(),i=requireRange(),o=requireRef(),s=requireSyntax(),a=requireType(),c=requireUri(),l=requireAbs(),u=requireFloor(),d=requireMax(),h=requireMin(),p=requirePow(),f=requireRound(),y=requireSign(),g=Function,b=function(e){try{return g('"use strict"; return ('+e+").constructor;")()}catch(e){}},m=requireGopd(),w=requireEsDefineProperty(),v=function(){throw new a},S=m?function(){try{return v}catch(e){try{return m(arguments,"callee").get}catch(e){return v}}}():v,$=requireHasSymbols()(),x=requireGetProto(),E=requireObject_getPrototypeOf(),A=requireReflect_getPrototypeOf(),P=requireFunctionApply(),k=requireFunctionCall(),I={},T="undefined"!=typeof Uint8Array&&x?x(Uint8Array):e,O={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":$&&x?x([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":I,"%AsyncGenerator%":I,"%AsyncGeneratorFunction%":I,"%AsyncIteratorPrototype%":I,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?e:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":I,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":$&&x?x(x([][Symbol.iterator]())):e,"%JSON%":"object"==typeof JSON?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&$&&x?x((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":m,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&$&&x?x((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":$&&x?x(""[Symbol.iterator]()):e,"%Symbol%":$?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":S,"%TypedArray%":T,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":P,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":E,"%Math.abs%":l,"%Math.floor%":u,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":y,"%Reflect.getPrototypeOf%":A};if(x)try{null.error}catch(e){var _=x(x(e));O["%Error.prototype%"]=_}var C=function e(t){var r;if("%AsyncFunction%"===t)r=b("async function () {}");else if("%GeneratorFunction%"===t)r=b("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=b("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&x&&(r=x(i.prototype))}return O[t]=r,r},R={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},B=requireFunctionBind(),D=requireHasown(),N=B.call(k,Array.prototype.concat),M=B.call(P,Array.prototype.splice),j=B.call(k,String.prototype.replace),L=B.call(k,String.prototype.slice),U=B.call(k,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,V=function(e,t){var r,n=e;if(D(R,n)&&(n="%"+(r=R[n])[0]+"%"),D(O,n)){var i=O[n];if(i===I&&(i=C(n)),void 0===i&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new s("intrinsic "+e+" does not exist!")};return getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');if(null===U(/^%?[^%]*%?$/,e))throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=L(e,0,1),r=L(e,-1);if("%"===t&&"%"!==r)throw new s("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new s("invalid intrinsic syntax, expected opening `%`");var n=[];return j(e,q,(function(e,t,r,i){n[n.length]=r?j(i,F,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",i=V("%"+n+"%",t),o=i.name,c=i.value,l=!1,u=i.alias;u&&(n=u[0],M(r,N([0,1],u)));for(var d=1,h=!0;d<r.length;d+=1){var p=r[d],f=L(p,0,1),y=L(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===y||"'"===y||"`"===y)&&f!==y)throw new s("property names with quotes must have matching quotes");if("constructor"!==p&&h||(l=!0),D(O,o="%"+(n+="."+p)+"%"))c=O[o];else if(null!=c){if(!(p in c)){if(!t)throw new a("base intrinsic for "+e+" exists, but the property is not available.");return}if(m&&d+1>=r.length){var g=m(c,p);c=(h=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:c[p]}else h=D(c,p),c=c[p];h&&!l&&(O[o]=c)}}return c},getIntrinsic}function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var e=requireGetIntrinsic(),t=requireCallBindApplyHelpers(),r=t([e("%String.prototype.indexOf%")]);return callBound=function(n,i){var o=e(n,!!i);return"function"==typeof o&&r(n,".prototype.")>-1?t([o]):o},callBound}function requireIsArguments(){if(hasRequiredIsArguments)return isArguments;hasRequiredIsArguments=1;var e=requireShams()(),t=requireCallBound()("Object.prototype.toString"),r=function(r){return!(e&&r&&"object"==typeof r&&Symbol.toStringTag in r)&&"[object Arguments]"===t(r)},n=function(e){return!!r(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==t(e)&&"callee"in e&&"[object Function]"===t(e.callee)},i=function(){return r(arguments)}();return r.isLegacyArguments=n,isArguments=i?r:n}function requireIsRegex(){if(hasRequiredIsRegex)return isRegex;hasRequiredIsRegex=1;var e,t=requireCallBound(),r=requireShams()(),n=requireHasown(),i=requireGopd();if(r){var o=t("RegExp.prototype.exec"),s={},a=function(){throw s},c={toString:a,valueOf:a};"symbol"==typeof Symbol.toPrimitive&&(c[Symbol.toPrimitive]=a),e=function(e){if(!e||"object"!=typeof e)return!1;var t=i(e,"lastIndex");if(!(t&&n(t,"value")))return!1;try{o(e,c)}catch(e){return e===s}}}else{var l=t("Object.prototype.toString");e=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&"[object RegExp]"===l(e)}}return isRegex=e}function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest;hasRequiredSafeRegexTest=1;var e=requireCallBound(),t=requireIsRegex(),r=e("RegExp.prototype.exec"),n=requireType();return safeRegexTest=function(e){if(!t(e))throw new n("`regex` must be a RegExp");return function(t){return null!==r(e,t)}},safeRegexTest}function requireIsGeneratorFunction(){if(hasRequiredIsGeneratorFunction)return isGeneratorFunction;hasRequiredIsGeneratorFunction=1;var e,t=requireCallBound(),r=requireSafeRegexTest()(/^\s*(?:function)?\*/),n=requireShams()(),i=requireGetProto(),o=t("Object.prototype.toString"),s=t("Function.prototype.toString");return isGeneratorFunction=function(t){if("function"!=typeof t)return!1;if(r(s(t)))return!0;if(!n)return"[object GeneratorFunction]"===o(t);if(!i)return!1;if(void 0===e){var a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch(e){}}();e=!!a&&i(a)}return i(t)===e}}function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;var e,t,r=Function.prototype.toString,n="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof n&&"function"==typeof Object.defineProperty)try{e=Object.defineProperty({},"length",{get:function(){throw t}}),t={},n((function(){throw 42}),null,e)}catch(e){e!==t&&(n=null)}else n=null;var i=/^\s*class\b/,o=function(e){try{var t=r.call(e);return i.test(t)}catch(e){return!1}},s=function(e){try{return!o(e)&&(r.call(e),!0)}catch(e){return!1}},a=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),u=function(){return!1};if("object"==typeof document){var d=document.all;a.call(d)===a.call(document.all)&&(u=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=a.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}return isCallable=n?function(r){if(u(r))return!0;if(!r)return!1;if("function"!=typeof r&&"object"!=typeof r)return!1;try{n(r,null,e)}catch(e){if(e!==t)return!1}return!o(r)&&s(r)}:function(e){if(u(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return s(e);if(o(e))return!1;var t=a.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)},isCallable}function requireForEach(){if(hasRequiredForEach)return forEach;hasRequiredForEach=1;var e=requireIsCallable(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty;return forEach=function(n,i,o){if(!e(i))throw new TypeError("iterator must be a function");var s;arguments.length>=3&&(s=o),function(e){return"[object Array]"===t.call(e)}(n)?function(e,t,n){for(var i=0,o=e.length;i<o;i++)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,s):"string"==typeof n?function(e,t,r){for(var n=0,i=e.length;n<i;n++)null==r?t(e.charAt(n),n,e):t.call(r,e.charAt(n),n,e)}(n,i,s):function(e,t,n){for(var i in e)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,s)},forEach}function requirePossibleTypedArrayNames(){return hasRequiredPossibleTypedArrayNames?possibleTypedArrayNames:(hasRequiredPossibleTypedArrayNames=1,possibleTypedArrayNames=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"])}function requireAvailableTypedArrays(){if(hasRequiredAvailableTypedArrays)return availableTypedArrays;hasRequiredAvailableTypedArrays=1;var e=requirePossibleTypedArrayNames(),t="undefined"==typeof globalThis?commonjsGlobal:globalThis;return availableTypedArrays=function(){for(var r=[],n=0;n<e.length;n++)"function"==typeof t[e[n]]&&(r[r.length]=e[n]);return r},availableTypedArrays}var callBind={exports:{}},defineDataProperty,hasRequiredDefineDataProperty,hasPropertyDescriptors_1,hasRequiredHasPropertyDescriptors,setFunctionLength,hasRequiredSetFunctionLength,applyBind,hasRequiredApplyBind,hasRequiredCallBind,whichTypedArray,hasRequiredWhichTypedArray,isTypedArray,hasRequiredIsTypedArray,hasRequiredTypes,isBufferBrowser,hasRequiredIsBufferBrowser;function requireDefineDataProperty(){if(hasRequiredDefineDataProperty)return defineDataProperty;hasRequiredDefineDataProperty=1;var e=requireEsDefineProperty(),t=requireSyntax(),r=requireType(),n=requireGopd();return defineDataProperty=function(i,o,s){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!n&&n(i,o);if(e)e(i,o,{configurable:null===l&&d?d.configurable:!l,enumerable:null===a&&d?d.enumerable:!a,value:s,writable:null===c&&d?d.writable:!c});else{if(!u&&(a||c||l))throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[o]=s}},defineDataProperty}function requireHasPropertyDescriptors(){if(hasRequiredHasPropertyDescriptors)return hasPropertyDescriptors_1;hasRequiredHasPropertyDescriptors=1;var e=requireEsDefineProperty(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return 1!==e([],"length",{value:1}).length}catch(e){return!0}},hasPropertyDescriptors_1=t}function requireSetFunctionLength(){if(hasRequiredSetFunctionLength)return setFunctionLength;hasRequiredSetFunctionLength=1;var e=requireGetIntrinsic(),t=requireDefineDataProperty(),r=requireHasPropertyDescriptors()(),n=requireGopd(),i=requireType(),o=e("%Math.floor%");return setFunctionLength=function(e,s){if("function"!=typeof e)throw new i("`fn` is not a function");if("number"!=typeof s||s<0||s>4294967295||o(s)!==s)throw new i("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,l=!0;if("length"in e&&n){var u=n(e,"length");u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!a)&&(r?t(e,"length",s,!0,!0):t(e,"length",s)),e},setFunctionLength}function requireApplyBind(){if(hasRequiredApplyBind)return applyBind;hasRequiredApplyBind=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireActualApply();return applyBind=function(){return r(e,t,arguments)},applyBind}function requireCallBind(){return hasRequiredCallBind||(hasRequiredCallBind=1,function(e){var t=requireSetFunctionLength(),r=requireEsDefineProperty(),n=requireCallBindApplyHelpers(),i=requireApplyBind();e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(callBind)),callBind.exports}function requireWhichTypedArray(){if(hasRequiredWhichTypedArray)return whichTypedArray;hasRequiredWhichTypedArray=1;var e=requireForEach(),t=requireAvailableTypedArrays(),r=requireCallBind(),n=requireCallBound(),i=requireGopd(),o=requireGetProto(),s=n("Object.prototype.toString"),a=requireShams()(),c="undefined"==typeof globalThis?commonjsGlobal:globalThis,l=t(),u=n("String.prototype.slice"),d=n("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r<e.length;r+=1)if(e[r]===t)return r;return-1},h={__proto__:null};e(l,a&&i&&o?function(e){var t=new c[e];if(Symbol.toStringTag in t&&o){var n=o(t),s=i(n,Symbol.toStringTag);if(!s&&n){var a=o(n);s=i(a,Symbol.toStringTag)}h["$"+e]=r(s.get)}}:function(e){var t=new c[e],n=t.slice||t.set;n&&(h["$"+e]=r(n))});return whichTypedArray=function(t){if(!t||"object"!=typeof t)return!1;if(!a){var r=u(s(t),8,-1);return d(l,r)>-1?r:"Object"===r&&function(t){var r=!1;return e(h,(function(e,n){if(!r)try{e(t),r=u(n,1)}catch(e){}})),r}(t)}return i?function(t){var r=!1;return e(h,(function(e,n){if(!r)try{"$"+e(t)===n&&(r=u(n,1))}catch(e){}})),r}(t):null},whichTypedArray}function requireIsTypedArray(){if(hasRequiredIsTypedArray)return isTypedArray;hasRequiredIsTypedArray=1;var e=requireWhichTypedArray();return isTypedArray=function(t){return!!e(t)}}function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(e){var t=requireIsArguments(),r=requireIsGeneratorFunction(),n=requireWhichTypedArray(),i=requireIsTypedArray();function o(e){return e.call.bind(e)}var s="undefined"!=typeof BigInt,a="undefined"!=typeof Symbol,c=o(Object.prototype.toString),l=o(Number.prototype.valueOf),u=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(s)var h=o(BigInt.prototype.valueOf);if(a)var p=o(Symbol.prototype.valueOf);function f(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function y(e){return"[object Map]"===c(e)}function g(e){return"[object Set]"===c(e)}function b(e){return"[object WeakMap]"===c(e)}function m(e){return"[object WeakSet]"===c(e)}function w(e){return"[object ArrayBuffer]"===c(e)}function v(e){return"undefined"!=typeof ArrayBuffer&&(w.working?w(e):e instanceof ArrayBuffer)}function S(e){return"[object DataView]"===c(e)}function $(e){return"undefined"!=typeof DataView&&(S.working?S(e):e instanceof DataView)}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i,e.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},e.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||$(e)},e.isUint8Array=function(e){return"Uint8Array"===n(e)},e.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===n(e)},e.isUint16Array=function(e){return"Uint16Array"===n(e)},e.isUint32Array=function(e){return"Uint32Array"===n(e)},e.isInt8Array=function(e){return"Int8Array"===n(e)},e.isInt16Array=function(e){return"Int16Array"===n(e)},e.isInt32Array=function(e){return"Int32Array"===n(e)},e.isFloat32Array=function(e){return"Float32Array"===n(e)},e.isFloat64Array=function(e){return"Float64Array"===n(e)},e.isBigInt64Array=function(e){return"BigInt64Array"===n(e)},e.isBigUint64Array=function(e){return"BigUint64Array"===n(e)},y.working="undefined"!=typeof Map&&y(new Map),e.isMap=function(e){return"undefined"!=typeof Map&&(y.working?y(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),e.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),e.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},m.working="undefined"!=typeof WeakSet&&m(new WeakSet),e.isWeakSet=function(e){return m(e)},w.working="undefined"!=typeof ArrayBuffer&&w(new ArrayBuffer),e.isArrayBuffer=v,S.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&S(new DataView(new ArrayBuffer(1),0,1)),e.isDataView=$;var x="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function E(e){return"[object SharedArrayBuffer]"===c(e)}function A(e){return void 0!==x&&(void 0===E.working&&(E.working=E(new x)),E.working?E(e):e instanceof x)}function P(e){return f(e,l)}function k(e){return f(e,u)}function I(e){return f(e,d)}function T(e){return s&&f(e,h)}function O(e){return a&&f(e,p)}e.isSharedArrayBuffer=A,e.isAsyncFunction=function(e){return"[object AsyncFunction]"===c(e)},e.isMapIterator=function(e){return"[object Map Iterator]"===c(e)},e.isSetIterator=function(e){return"[object Set Iterator]"===c(e)},e.isGeneratorObject=function(e){return"[object Generator]"===c(e)},e.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===c(e)},e.isNumberObject=P,e.isStringObject=k,e.isBooleanObject=I,e.isBigIntObject=T,e.isSymbolObject=O,e.isBoxedPrimitive=function(e){return P(e)||k(e)||I(e)||T(e)||O(e)},e.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(v(e)||A(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw new Error(t+" is not supported in userland")}})}))}(types)),types}function requireIsBufferBrowser(){return hasRequiredIsBufferBrowser?isBufferBrowser:(hasRequiredIsBufferBrowser=1,isBufferBrowser=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8})}var inherits_browser={exports:{}},hasRequiredInherits_browser,hasRequiredUtil$1,hasRequiredLib,util,hasRequiredUtil,base,hasRequiredBase,rfc4648_1,hasRequiredRfc4648,constants_1,hasRequiredConstants,hasRequiredSrc;function requireInherits_browser(){return hasRequiredInherits_browser||(hasRequiredInherits_browser=1,"function"==typeof Object.create?inherits_browser.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),inherits_browser.exports}function requireUtil$1(){return hasRequiredUtil$1||(hasRequiredUtil$1=1,function(e){var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},r=/%[sdj%]/g;e.format=function(e){if(!g(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(s(arguments[n]));return t.join(" ")}n=1;for(var i=arguments,o=i.length,a=String(e).replace(r,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(e){return"[Circular]"}default:return e}})),c=i[n];n<o;c=i[++n])f(c)||!w(c)?a+=" "+c:a+=" "+s(c);return a},e.deprecate=function(t,r){if("undefined"!=typeof process&&!0===process.noDeprecation)return t;if("undefined"==typeof process)return function(){return e.deprecate(t,r).apply(this,arguments)};var n=!1;return function(){if(!n){if(process.throwDeprecation)throw new Error(r);process.traceDeprecation,n=!0}return t.apply(this,arguments)}};var n={},i=/^$/;if(process.env.NODE_DEBUG){var o=process.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}function s(t,r){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(r)?n.showHidden=r:r&&e._extend(n,r),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=a),l(n,t,n.depth)}function a(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function l(t,r,n){if(t.customInspect&&r&&$(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return g(i)||(i=l(t,i,n)),i}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(f(t))return e.stylize("null","null")}(t,r);if(o)return o;var s=Object.keys(r),a=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),S(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return u(r);if(0===s.length){if($(r)){var c=r.name?": "+r.name:"";return t.stylize("[Function"+c+"]","special")}if(m(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(v(r))return t.stylize(Date.prototype.toString.call(r),"date");if(S(r))return u(r)}var w,x="",A=!1,P=["{","}"];(h(r)&&(A=!0,P=["[","]"]),$(r))&&(x=" [Function"+(r.name?": "+r.name:"")+"]");return m(r)&&(x=" "+RegExp.prototype.toString.call(r)),v(r)&&(x=" "+Date.prototype.toUTCString.call(r)),S(r)&&(x=" "+u(r)),0!==s.length||A&&0!=r.length?n<0?m(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),w=A?function(e,t,r,n,i){for(var o=[],s=0,a=t.length;s<a;++s)E(t,String(s))?o.push(d(e,t,r,n,String(s),!0)):o.push("");return i.forEach((function(i){i.match(/^\d+$/)||o.push(d(e,t,r,n,i,!0))})),o}(t,r,n,a,s):s.map((function(e){return d(t,r,n,a,e,A)})),t.seen.pop(),function(e,t,r){var n=e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(w,x,P)):P[0]+x+P[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),E(n,i)||(s="["+i+"]"),a||(e.seen.indexOf(c.value)<0?(a=f(r)?l(e,c.value,null):l(e,c.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.slice(1,-1),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function y(e){return"number"==typeof e}function g(e){return"string"==typeof e}function b(e){return void 0===e}function m(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function v(e){return w(e)&&"[object Date]"===x(e)}function S(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function $(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}e.debuglog=function(t){if(t=t.toUpperCase(),!n[t])if(i.test(t)){process.pid;n[t]=function(){e.format.apply(e,arguments)}}else n[t]=function(){};return n[t]},e.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.types=requireTypes(),e.isArray=h,e.isBoolean=p,e.isNull=f,e.isNullOrUndefined=function(e){return null==e},e.isNumber=y,e.isString=g,e.isSymbol=function(e){return"symbol"==typeof e},e.isUndefined=b,e.isRegExp=m,e.types.isRegExp=m,e.isObject=w,e.isDate=v,e.types.isDate=v,e.isError=S,e.types.isNativeError=S,e.isFunction=$,e.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},e.isBuffer=requireIsBufferBrowser();function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.log=function(){},e.inherits=requireInherits_browser(),e._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var A="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function P(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}e.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(A&&e[A]){var r;if("function"!=typeof(r=e[A]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(r,A,{value:r,enumerable:!1,writable:!1,configurable:!0}),r}function r(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push((function(e,n){e?r(e):t(n)}));try{e.apply(this,i)}catch(e){r(e)}return n}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),A&&Object.defineProperty(r,A,{value:r,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(r,t(e))},e.promisify.custom=A,e.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function r(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var n=t.pop();if("function"!=typeof n)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return n.apply(i,arguments)};e.apply(this,t).then((function(e){process.nextTick(o.bind(null,null,e))}),(function(e){process.nextTick(P.bind(null,e,o))}))}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),Object.defineProperties(r,t(e)),r}}(util$1)),util$1}function requireLib(){return hasRequiredLib||(hasRequiredLib=1,lib.TextEncoder="undefined"!=typeof TextEncoder?TextEncoder:requireUtil$1().TextEncoder,lib.TextDecoder="undefined"!=typeof TextDecoder?TextDecoder:requireUtil$1().TextDecoder),lib}function requireUtil(){if(hasRequiredUtil)return util;hasRequiredUtil=1;const{TextEncoder:e,TextDecoder:t}=requireLib(),r=new t,n=new e;return util={decodeText:e=>r.decode(e),encodeText:e=>n.encode(e),concat:function(e,t){const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}},util}function requireBase(){if(hasRequiredBase)return base;hasRequiredBase=1;const{encodeText:e}=requireUtil();return base=class{constructor(t,r,n,i){this.name=t,this.code=r,this.codeBuf=e(this.code),this.alphabet=i,this.codec=n(i)}encode(e){return this.codec.encode(e)}decode(e){for(const t of e)if(this.alphabet&&this.alphabet.indexOf(t)<0)throw new Error(`invalid character '${t}' in '${e}'`);return this.codec.decode(e)}},base}function requireRfc4648(){if(hasRequiredRfc4648)return rfc4648_1;hasRequiredRfc4648=1;return rfc4648_1={rfc4648:e=>t=>({encode:r=>((e,t,r)=>{const n="="===t[t.length-1],i=(1<<r)-1;let o="",s=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],s+=8;s>r;)s-=r,o+=t[i&a>>s];if(s&&(o+=t[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o})(r,t,e),decode:r=>((e,t,r)=>{const n={};for(let e=0;e<t.length;++e)n[t[e]]=e;let i=e.length;for(;"="===e[i-1];)--i;const o=new Uint8Array(i*r/8|0);let s=0,a=0,c=0;for(let t=0;t<i;++t){const i=n[e[t]];if(void 0===i)throw new SyntaxError("Invalid character "+e[t]);a=a<<r|i,s+=r,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=r||255&a<<8-s)throw new SyntaxError("Unexpected end of data");return o})(r,t,e)})},rfc4648_1}function requireConstants(){if(hasRequiredConstants)return constants_1;hasRequiredConstants=1;const e=requireSrc$1(),t=requireBase(),{rfc4648:r}=requireRfc4648(),{decodeText:n,encodeText:i}=requireUtil(),o=[["identity","\0",()=>({encode:n,decode:i}),""],["base2","0",r(1),"01"],["base8","7",r(3),"01234567"],["base10","9",e,"0123456789"],["base16","f",r(4),"0123456789abcdef"],["base16upper","F",r(4),"0123456789ABCDEF"],["base32hex","v",r(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",r(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",r(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",r(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",r(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",r(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",r(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",r(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",r(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",e,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",e,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",e,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",e,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",r(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],s=o.reduce(((e,r)=>(e[r[0]]=new t(r[0],r[1],r[2],r[3]),e)),{}),a=o.reduce(((e,t)=>(e[t[1]]=s[t[0]],e)),{});return constants_1={names:s,codes:a}}function requireSrc(){return hasRequiredSrc||(hasRequiredSrc=1,function(e,t){const r=requireConstants(),{encodeText:n,decodeText:i,concat:o}=requireUtil();function s(e){if(Object.prototype.hasOwnProperty.call(r.names,e))return r.names[e];if(Object.prototype.hasOwnProperty.call(r.codes,e))return r.codes[e];throw new Error(`Unsupported encoding: ${e}`)}t=e.exports=function(e,t){if(!t)throw new Error("requires an encoded Uint8Array");const{name:r,codeBuf:n}=s(e);return function(e,t){const r=s(e);r.decode(i(t))}(r,t),o([n,t],n.length+t.length)},t.encode=function(e,t){const r=s(e),i=n(r.encode(t));return o([r.codeBuf,i],r.codeBuf.length+i.length)},t.decode=function(e){e instanceof Uint8Array&&(e=i(e));const t=e[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(t)&&(e=e.toLowerCase()),s(e[0]).decode(e.substring(1))},t.isEncoded=function(e){if(e instanceof Uint8Array&&(e=i(e)),"[object String]"!==Object.prototype.toString.call(e))return!1;try{return s(e[0]).name}catch(e){return!1}},t.encoding=s,t.encodingFromData=function(e){return e instanceof Uint8Array&&(e=i(e)),s(e[0])},t.names=Object.freeze(r.names),t.codes=Object.freeze(r.codes)}(src$1,src$1.exports)),src$1.exports}var srcExports=requireSrc(),multibase=getDefaultExportFromCjs(srcExports);class LineReader{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf-8";Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"textDecoder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"isEOF",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.reader=e.getReader(),this.textDecoder=new TextDecoder(t)}async readLine(){if(this.isEOF&&0===this.buffer.length)return null;const e=this.buffer.indexOf("\n");if(-1!==e){const t=this.buffer.substring(0,e);return this.buffer=this.buffer.substring(e+1),t}if(!this.isEOF){const{value:e,done:t}=await this.reader.read();if(t){if(this.isEOF=!0,this.buffer.length>0){const e=this.buffer;return this.buffer="",e}return null}return this.buffer+=this.textDecoder.decode(e,{stream:!0}),this.readLine()}if(this.buffer.length>0){const e=this.buffer;return this.buffer="",e}return null}release(){this.reader.releaseLock()}}const{Buffer:Buffer$1}=buffer$1;Protocol.name,Protocol.version;const dsManagerBaseKey=new Key$1("/manager");function newGrpcClient(e,t){if(null==e.p2pNode||null==e.p2pNode.peerId)throw new Error("p2pNode is null or node privateKey is null");return new DBGrpcClient(e.p2pNode,e.peerAddr,e.token,t,e.protocol)}class DBManager{constructor(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=arguments.length>5?arguments[5]:void 0,s=arguments.length>6?arguments[6]:void 0,a=arguments.length>7?arguments[7]:void 0;Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"network",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"storagePrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.store=e,this.network=t,this.dc=r,this.storagePrefix=s,this.opts=i,this.dbs=new Map,this.lock=new AsyncLock,this.chainUtil=o,this.connectedDc=n,this.context=a}async loadDbs(){try{const e={prefix:dsManagerBaseKey.toString(),keysOnly:!0},t=this.store.query(e),r=new Map;for await(const e of t)try{const t=e.key.toString().split("/");if(t.length<3)continue;const n=q.fromString(t[2]||"");if(r.has(n.toString()))continue;r.set(n.toString(),!0);const[i,o,s]=await this.wrapDB(this.store,n,this.opts,"",[]);if(s)continue;const a=await DB.newDB(i,this.network,n,o);this.dbs.set(n.toString(),a)}catch(e){}}catch(e){throw e}}async getLogKey(e){const t=`${this.storagePrefix}_${e.toString()}_logkey`;try{const e=await this.store.get(new Key$1(t));if(e){return Ed25519PrivKey.fromString(Buffer$1.from(e).toString("hex"))}{const e=await this.newLogKey();return this.store.put(new Key$1(t),Buffer$1.from(e.raw)),e}}catch(e){if("ERR_NOT_FOUND"===e.code){const e=await this.newLogKey();return this.store.put(new Key$1(t),Buffer$1.from(e.raw)),e}throw new Error(`Failed to get/create log key: ${e}`)}}async newLogKey(){try{const e=await generateKeyPair("Ed25519");return new Ed25519PrivKey(e.raw)}catch(e){throw new Error(`Failed to generate log key: ${e}`)}}static fromAddr(e){try{const t=e.toString().split("/"),r=t.indexOf(Protocol.name);if(-1===r||r===t.length-1)throw new Error("thread protocol not found in multiaddr");const n=t[r+1]||"";return q.fromString(n)}catch(e){throw new Error(`Failed to extract ID from multiaddr: ${e.message}`)}}toAddr(){try{return multiaddr(`/${Protocol.name}/${this.toString()}`)}catch(e){throw new Error(`Failed to create multiaddr: ${e.message}`)}}async newDBFromAddr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=e.id;return await this.lock.acquire("dbs",(async()=>{if(this.dbs.has(n.toString()))throw Errors$6.ErrDBExists;if(r.name&&!isValidName(r.name))throw Errors$6.ErrInvalidName;if(t.defined()&&!t.canRead())throw Errors$6.ErrThreadReadKeyRequired;await this.network.addThread(e,{token:r.token,logKey:r.logKey,threadKey:t});const i=r.collections||[],o=r.name||"",[s,a,c]=await this.wrapDB(this.store,n,this.opts,o,i);if(c)throw new Error(`wrapping db: ${c.message}`);const l=await DB.newDB(s,this.network,n,a);return this.dbs.set(n.toString(),l),r.block?await this.network.pullThread(n,pullThreadBackgroundTimeout,{token:r.token}):this.pullThreadBackground(n,r.token),l}))}async pullThreadBackground(e,t){try{await this.network.pullThread(e,pullThreadBackgroundTimeout,{token:t})}catch(e){}}async preloadDBFromDC(e,t,r,n,i,o,s,a){if(!this)throw Errors$6.ErrNoDbManager;let c,l,u;try{c=await this.decodeThreadId(e)}catch(e){throw e}try{l=await this.getLogKey(c)}catch(e){throw e}try{u=peerIdFromPrivateKey(l)}catch(e){throw e}await this.dc._connectToObjNodes(c.toString()).catch((e=>{}));const d=createContext(3e4);try{await this.addLogToThreadStart(d,c,u)}catch(e){}let h,p;try{const e=SymmetricKey.fromString(o),t=SymmetricKey.fromString(i);h=new Key(e,t)}catch(e){throw e}let f=!1;if(n.length>10)try{const e=multiaddr(n);try{await(this.dc.dcNodeClient?.libp2p.dial(e,{signal:AbortSignal.timeout(3e3)}))&&(f=!0,p=multiaddr(n))}catch(e){}}catch(e){}if(f)this.dc._connectToObjNodes(c.toString()).catch((e=>{}));else try{const[e,t]=await(this.dc?._connectToObjNodes(c.toString()));if(!e&&t)throw Errors$6.ErrNoThreadOnDc;const r=this.dc.dcNodeClient?.libp2p.getConnections(undefined);if(!r||0==r.length)throw Errors$6.ErrNoThreadOnDc}catch(e){throw e}let y=[];try{y=JSON.parse(a)}catch(e){throw e}const g=y.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),b={name:r,collections:g,key:h,logKey:l,block:s};try{await this.deleteDB(c,!0)}catch(e){if(e!==Errors$6.ErrDBNotFound&&e!==Errors$6.ErrThreadNotFound)throw e}if(null==this.dc.dcNodeClient)throw Errors$6.ErrNoDcNodeClient;const m=createContext(30*PullTimeout),w=new FileManager(this.dc,this.connectedDc,this.chainUtil,this.dc.dcNodeClient,this.context),v=await w.createSeekableFileStream(t,"");if(null==v)throw Errors$6.ErrFileNotFound;const S=new ThreadMuliaddr(p,c);await this.preloadDBFromReader(m,v.createReadableStream(),S,h,b)}async preloadDBFromReader(e,t,r,n){let i,o,s,a,c=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};try{i=DBManager.fromAddr(r.addr)}catch(e){throw e}if(await this.lock.acquire("dbs",(async()=>{if(this.dbs.has(i.toString()))throw Errors$6.ErrDBExists})),c.name&&!isValidName(c.name))throw Errors$6.ErrInvalidName;if(n.defined()&&!n.canRead())throw Errors$6.ErrThreadReadKeyRequired;try{await this.network.addThread(r,{threadKey:n,logKey:c.logKey,token:c.token})}catch(e){throw e}try{const e=c.collections||[],t=c.name||"";[o,s]=await this.wrapDB(this.store,i,this.opts,t,e)}catch(e){throw e}try{a=await DB.newDB(o,this.network,i,s)}catch(e){throw e}await this.lock.acquire("dbs",(async()=>{this.dbs.set(i.toString(),a)}));const l=n.read();if(!l)throw new Error(`read key not found for thread ${i}`);const u=new LineReader(t);new TextDecoder;let d="";try{const e=await u.readLine();e&&(d=e)}catch(e){throw e}if(""==d)throw new Error(`empty state value for thread ${i}`);d=d.slice(32);const h=d.split(";"),p=[];for(const e of h)try{const t=srcExports.decode(e),r=net.pb.Log.decode(t);p.push(r)}catch(e){continue}try{await this.network.preLoadLogs(i,p)}catch(e){throw await this.deleteDB(i,!1),e}try{await this.importDBStateFromReader(i,u,l)}catch(e){throw await this.deleteDB(i,!1),e}}async exportDBToFile(e,t,r,n){let i,o,s="";[i,o]=await this.network.getPbLogs(t);for(let e=0;i&&e<i.length;e++){if(!i[e])continue;const t=i[e],r=net.pb.Log.encode(t).finish(),n=multibase.encode("base64",r);s=0===e?n.toString():`${s};${n.toString()}`}let a=s+"\n";const c=this.dbs.get(t.toString());if(!c)throw Errors$6.ErrDBNotFound;const l=await c.datastore.newTransactionExtended(!0);try{const e=new Query,i=new Key$1("/"),s=await newIterator(l,i,e);for await(const e of s.iter.next()){if(e.error)throw e.error;let t;if(n){const r=await n.encrypt(e.entry.value),i=multibase.encode("base64",r);t=`${e.entry.key}|${i.toString()}`}else{const r=multibase.encode("base64",e.entry.value);t=`${e.entry.key}|${r.toString()}`}a+=t+"\n"}s.close(),l.discard();const c=new Blob([a],{type:"text/plain"}),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=r||`db-export-${t.toString().substring(0,8)}.txt`,document.body.appendChild(d),d.click(),setTimeout((()=>{document.body.removeChild(d),URL.revokeObjectURL(u)}),100),o}catch(e){throw l.discard(),e}}async importDBStateFromReader(e,t,r){let n;if(await this.lock.acquire("dbs",(async()=>{n=this.dbs.get(e.toString())})),!n)throw Errors$6.ErrDBNotFound;const i=n.defaultIndexFunc();new TextDecoder;let o="";for(;o=await t.readLine(),o;){let e;try{e=await n.datastore.newTransactionExtended(!1)}catch(e){throw new Error(`创建事务错误: ${e instanceof Error?e.message:String(e)}`)}try{const t=o.split("|");if(2!==t.length)throw e.discard(),new Error("无效的记录格式");const n=t[0],s=t[1]||"";let a;try{a=srcExports.decode(s)}catch(t){throw await e.discard(),new Error(`multibase解码失败: ${t instanceof Error?t.message:String(t)}`)}let c=a;if(r)try{c=await r.decrypt(a)}catch(t){throw await e.discard(),new Error(`解密值失败: ${t instanceof Error?t.message:String(t)}`)}const l=new Key$1(n||"");try{if(await e.has(l)){e.discard();continue}}catch(t){throw e.discard(),new Error(`检查键存在性失败: ${t instanceof Error?t.message:String(t)}`)}try{await e.put(l,c)}catch(t){throw e.discard(),new Error(`存储值失败: ${t instanceof Error?t.message:String(t)}`)}const u=n?.split("/");if(!u||u.length<2)throw e.discard(),new Error("无效的键格式: 未找到集合名称");const d=u[u.length-2]||"";try{await i(d,l,e,c)}catch(t){throw e.discard(),new Error(`应用索引失败: ${t instanceof Error?t.message:String(t)}`)}try{await e.commit()}catch(t){throw e.discard(),new Error(`提交事务失败: ${t instanceof Error?t.message:String(t)}`)}}catch(t){try{e.discard()}catch{}throw t}}}async wrapDB(e,t,r,n,i){if(!await this.validateThreadId(t.toString()))return[null,null,new Error("Invalid Thread ID")];const o=dsManagerBaseKey.child(new Key$1(t.toString())).toString();return[createTransformedDatastore(e,new PrefixTransform(o)),{name:n,collections:[...r.collections||[],...i],eventCodec:r.eventCodec,debug:r.debug},null]}async listDBs(){const e=new Map;return await this.lock.acquire("dbs",(async()=>{for(const[t,r]of this.dbs){const n=q.fromString(t);await this.network.getThread(n),e.set(n,r)}})),e}async ifSyncDBToDCSuccess(e){try{const[t,r]=await this.chainUtil.objectState(e);return!(!t||r)&&new Promise((r=>{const n=setTimeout((()=>r(!1)),PullTimeout);(async()=>{for(const i of Object.keys(t.peers))try{const o=peerIdFromString$1(i),s=q.fromString(e),a=await this.network.getThreadFromPeer(s,o,{}),c=await this.network.getThread(s);if(this.compareThreadSync(c,a,t))return clearTimeout(n),void r(!0)}catch{continue}r(!1)})()}))}catch{return!1}}compareThreadSync(e,t,r){for(const n of e.logs){if(!r.logs.has(n.id.toString()))continue;if(!n.head)continue;const e=t.logs.find((e=>e.id===n.id));if(!e?.head)return!1;if(!e||n.head.counter>e.head.counter)return!1}return!0}async ifDbInitSuccess(e){try{const t=peerIdFromPrivateKey(await this.getLogKey(e)),[r,n]=await this.chainUtil.objectState(e.toString());if(!r||n)return!1;return!!r&&r?.logs.has(t.toString())}catch{return!1}}async syncDBFromDC(e,t,r,n,i,o,s,a){try{const c=await this.decodeThreadId(t),l=await this.getLogKey(c),u=peerIdFromPrivateKey(l);await this.dc._connectToObjNodes(t),await this.addLogToThreadStart(e,c,u);const d=SymmetricKey.fromString(o),h=SymmetricKey.fromString(i),p=new Key(d,h);let f,y,g;if(n.length>0)try{f=await(this.dc.dcNodeClient?.libp2p.dial(multiaddr(n),{signal:AbortSignal.timeout(dial_timeout)}))}catch(e){e.message}if(f)y=f?.remotePeer,g=f.remoteAddr;else{const[e,r]=await this.dc._connectToObjNodes(t);if(!e)throw new Error("connect to obj nodes failed");g=e}const b=a.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),m={name:r,collections:b,key:p,logKey:l,block:s};try{await this.deleteDB(c,!1)}catch(e){const t=e.message;if(t!=Errors$6.ErrDBNotFound.message&&t!=Errors$6.ErrThreadNotFound.message)throw e}const w=new ThreadMuliaddr(g,c);return await this.newDBFromAddr(w,p,m),null}catch(e){const t=e.message;return t==Errors$6.ErrorThreadIDValidation.message?t:e}}async getDBRecordsCount(e){let t=0;try{const r=await this.decodeThreadId(e),n=await this.network.getThread(r);if(!n)return t;for(const e of n.logs)e.head&&t<e.head.counter&&(t=e.head.counter)}catch(e){}return t}async addLogToThread(e,t,r){let n;try{n=await this.chainUtil.getBlockHeight()||0}catch(e){throw e}const i=uint32ToLittleEndianBytes(n||0),o=(new TextEncoder).encode(this.connectedDc.nodeAddr?.getPeerId()||""),s=new Uint8Array([...(new TextEncoder).encode(t.toString()),...(new TextEncoder).encode(r.toString()),...i,...o]);let a;try{a=await this.context.sign(s)}catch(e){throw e}if(!this.connectedDc?.client)throw Errors$6.ErrNoDcPeerConnected;const c={token:new ThreadToken(this.connectedDc.client.token),blockHeight:n,signature:a},l=newGrpcClient(this.connectedDc.client,this.network);await l.addLogToThread(t.toString(),r.toString(),c)}async addLogToThreadStart(e,t,r){e||(e=createContext(3e4));const n=new AbortController,i=e?.signal||n.signal,[o,s]=await this.chainUtil.objectState(t.toString());if(o&&!s){const e=this.context.getPublicKey();let t=!1;for(const r of o.users){if(r.replace("0x","")===e.toString()){t=!0;break}}if(!t)throw new Error("user not in the thread")}let a=null;if(e.deadline){const t=e.deadline.getTime()-Date.now();t>0&&(a=setTimeout((()=>{n.abort()}),t))}let c=0;let l=!1;try{await this.addLogToThread(e,t,r)}catch(e){}const u=setInterval((async()=>i.aborted?(clearInterval(u),void(a&&clearTimeout(a))):await this.ifDbInitSuccess(t)?(clearInterval(u),a&&clearTimeout(a),void(l=!0)):void(c>=6?(await this.addLogToThread(e,t,r),c=0):c++)),1e3);await new Promise((e=>{const t=setInterval((()=>{l&&(clearInterval(t),e())}),1e3);i.addEventListener("abort",(()=>{clearInterval(t),e()}))}))}async newDB(e,t,r,n){if(!this.connectedDc?.client)return["",Errors$6.ErrNoDcPeerConnected];try{const i=newGrpcClient(this.connectedDc.client,this.network),o=await i.requestThreadID(),s=await this.decodeThreadId(o),a=await this.getLogKey(s),c=(a.publicKey,peerIdFromPrivateKey(a)),l=SymmetricKey.fromString(r),u=SymmetricKey.fromString(t),d=new Key(l,u),h=await this.chainUtil.getBlockHeight()||0,p=uint32ToLittleEndianBytes(h||0);if(!this.connectedDc?.nodeAddr)return["",Errors$6.ErrNodeAddrIsNull];const f=await extractPeerIdFromMultiaddr(this.connectedDc.nodeAddr),y=(new TextEncoder).encode(f.toString()),g=uint64ToLittleEndianBytes(50<<20),b=(new TextEncoder).encode(o),m=uint32ToLittleEndianBytes(Type.Threaddbtype),w=new Uint8Array([...b,...g,...p,...m,...y]),v=await this.context.sign(w),S={threadKey:d,logKey:a,token:new ThreadToken(this.connectedDc.client.token),blockHeight:h,signature:v},$=await i.createThread(s.toString(),S),x=n.map((e=>({name:e.name,schema:e.schema,indexes:e.indexes||[]}))),E={name:e,collections:x,key:d,logKey:a,block:!0},A=[];for(const e of $.addrs)try{await this.newDBFromAddr(e,d,E);break}catch(e){A.push(e.message)}if(A.length===$.addrs.length)throw new Error(`create db failed:${A.join(",")}`);const P=createContext(3e4);return await this.addLogToThreadStart(P,s,c),[s.toString(),null]}catch(e){return["",e]}}async refreshDBFromDC(e){try{const t=await this.decodeThreadId(e);return await this.network.pullThread(t,600,{multiPeersFlag:!0}),null}catch(e){return e}}async syncDBToDC(e){if(!this.network)return Errors$6.ErrP2pNetworkNotInit;try{const t=await this.decodeThreadId(e);return await this.network.exchange(t),null}catch(e){return e}}async upgradeCollections(e,t){try{const r=await this.decodeThreadId(e),n=this.dbs.get(r.toString());return n?(await n.upgradeCollections(t),null):Errors$6.ErrDBNotFound}catch(e){return e}}async decodeThreadId(e){if(!e)throw new Error("Thread ID is empty");try{if(!/^[a-zA-Z0-9]+$/.test(e))throw Errors$6.ErrorThreadIDValidation;const t=q.fromString(e);if(t.toBytes().length<32)throw new Error("Thread ID too short");return t}catch(e){if(e.message===Errors$6.ErrorThreadIDValidation.message)throw e;throw new Error("Failed to decode thread ID: $errMsg}")}}async validateThreadId(e){try{return await this.decodeThreadId(e),!0}catch{return!1}}async close(){await this.lock.acquire("dbs",(async()=>{for(const e of this.dbs.values())await e.close();this.dbs.clear()}))}async getDB(e,t){try{await this.network.getThread(e,{token:t?.token})}catch(e){throw e}const r=this.dbs.get(e.toString());if(!r)throw Errors$6.ErrDBNotFound;return r}async getDBInfo(e,t){let r=null;try{const n=this.dbs.get(e.toString());if(!n)throw Errors$6.ErrDBNotFound;if(r=await n.getDBInfo(t),!r||null===r)throw new Error(`No info available for db ${e}`)}catch(e){return[null,e]}return[r,null]}async deleteDB(e,t,r){try{await this.network.getThread(e,{token:r?.token})}catch(e){throw e}const n=this.dbs.get(e.toString());if(!n)throw Errors$6.ErrDBNotFound;try{await n.close()}catch(e){throw e}if(t)try{await this.network.deleteThread(e,{token:r?.token,apiToken:n.connector?.token})}catch(e){throw e}try{await this.deleteThreadNamespace(e)}catch(e){throw e}this.lock.acquire("dbs",(async()=>{this.dbs.delete(e.toString())}))}async deleteThreadNamespace(e){const t={prefix:dsManagerBaseKey.child(new Key$1(e.toString())).toString(),keysOnly:!0},r=this.store.query(t);for await(const e of r)await this.store.delete(e.key)}async create(e,t,r){try{const e=JSON.parse(r);e&&"object"==typeof e&&"_mod"in e&&(delete e._mod,r=JSON.stringify(e))}catch(e){throw new Error("Invalid instance JSON format")}try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.create(Buffer$1.from(r));return o?o.toString():""}catch(e){throw e}}async delete(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");await i.delete(r)}catch(e){throw e}}async save(e,t,r){try{const n=q.fromString(e);try{const e=JSON.parse(r);e&&"object"==typeof e&&"_mod"in e&&(delete e._mod,r=JSON.stringify(e))}catch(e){throw new Error("Invalid instance JSON format")}const i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");await i.save(Buffer$1.from(r))}catch(e){throw e}}async deleteMany(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");let o=[];if(""===(r=r.trim()))return;if("["!==r[0])o=r.split(",");else try{o=JSON.parse(r)}catch(e){o=[r]}const s=o.length;for(let e=0;e<s;e+=100){const t=o.slice(e,Math.min(e+100,s));await i.deleteMany(t)}}catch(e){throw e}}async has(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);return!!i&&await i.has(r)}catch(e){return!1}}async find(e,t,r){try{r||(r="{}");const n=parseJsonToQuery(r),i=q.fromString(e),o=(await this.getDB(i)).getCollection(t);if(!o)throw new Error("Collection does not exist");const s=await o.find(n);if(Array.isArray(s))return jsonStringify(s);{const e=s,t=Buffer$1.concat([Buffer$1.from("["),Buffer$1.concat(e.map(((t,r)=>Buffer$1.concat([t,r<e.length-1?Buffer$1.from(","):Buffer$1.from("")])))),Buffer$1.from("]")]);return t.toString()}}catch(e){throw e}}async findByID(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.findByID(r);return o instanceof Buffer$1?o.toString():jsonStringify(o)}catch(e){throw e}}async modifiedSince(e,t,r){try{const n=q.fromString(e),i=(await this.getDB(n)).getCollection(t);if(!i)throw new Error("Collection does not exist");const o=await i.modifiedSince(r);return JSON.stringify(o)}catch(e){throw e}}}class AsyncLock{constructor(){Object.defineProperty(this,"locks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.locks=new Map}async acquire(e,t){for(;this.locks.has(e);)await this.locks.get(e);let r;const n=new Promise((e=>r=e));this.locks.set(e,n);try{return await t()}catch(e){throw e}finally{this.locks.delete(e),r()}}}function isValidName(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function createContext(e){const t={deadline:new Date(Date.now()+e)};return 0===e&&(t.deadline=void 0),"undefined"!=typeof AbortController&&(t.signal=(new AbortController).signal),t}const logger$7=createLogger("DatabaseModule"),storagePrefix="dc-";class DatabaseModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.DATABASE}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.context=e,this.initialized=!0,!0}catch(e){return logger$7.error("数据库模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async initDBManager(){try{if(this.assertInitialized(),this.context.dbManager)return null;const e=await createTxnDatastore(this.context.appInfo?.appName),t=await newKeyBook(e),r=await newAddrBook(e),n=newHeadBook(e),i=newLogstore(t,r,n,newThreadMetadata(e)),o=dagCbor(this.context.dcNodeClient);if(!this.context.publicKey)throw new Error("公钥未初始化");const s=new Network(this.context.dcutil,this.context.dcChain,this.context.dcNodeClient.libp2p,this.context.grpcServer,i,this.context.dcNodeClient.blockstore,o,this.context),a=new DBManager(e,s,this.context.dcutil,this.context.connectedDc,{},this.context.dcChain,storagePrefix,this.context);return await a.loadDbs(),this.context.dbManager=a,logger$7.info("数据库管理器初始化成功"),null}catch(e){return logger$7.error("初始化数据库管理器失败:",e),e}}async newDB(e,t,r,n){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const[i,o]=await this.context.dbManager.newDB(e,t,r,n);if(o)throw logger$7.error("创建数据库失败:",o),o;return logger$7.info(`创建数据库 ${e} 成功,线程ID: ${i}`),[i,null]}catch(t){return logger$7.error(`创建数据库 ${e} 失败:`,t),[null,t instanceof Error?t:new Error(String(t))]}}async loadVerno(e){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const t=q.fromString(e),r=await this.context.dbManager.getDB(t);if(!r)return logger$7.error("数据库信息为空"),0;return await r.loadVerno()}catch(e){return logger$7.error("加载数据库版本号失败:",e),0}}async saveVerno(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const r=q.fromString(e),n=await this.context.dbManager.getDB(r);return n?(await n.saveVerno(t),0):(logger$7.error("数据库信息为空"),-1)}catch(e){return logger$7.error("加载数据库版本号失败:",e),-1}}async syncDbFromDC(e,t,r,n,i,o,s){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const a=createContext(6e4);return await this.context.dbManager.syncDBFromDC(a,e,t,r,n,i,o,s),logger$7.info(`从DC同步数据库 ${t} 成功`),null}catch(e){return logger$7.error(`从DC同步数据库 ${t} 失败:`,e),e instanceof Error?e:new Error(String(e))}}async refreshDBFromDC(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.refreshDBFromDC(e),null}catch(t){return logger$7.error(`刷新数据库 ${e} 失败:`,t),t}}async syncDBToDC(e){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.syncDBToDC(e),logger$7.info(`同步数据库 ${e} 到DC成功`),null}catch(t){return logger$7.error(`同步数据库 ${e} 到DC失败:`,t),t}}async upgradeCollections(e,t){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.upgradeCollections(e,t),null}catch(e){return e}}async close(){try{if(this.assertInitialized(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.close(),logger$7.info("数据库管理器关闭成功"),null}catch(e){return logger$7.error("关闭数据库管理器失败:",e),e instanceof Error?e:new Error(String(e))}}async getDBInfo(e){try{if(!e||0==e.length)return[null,new Error("数据库ID不能为空")];if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)return[null,new Error("数据库管理器未初始化")];const t=q.fromString(e),[r,n]=await this.context.dbManager.getDBInfo(t);return[r,n]}catch(e){return logger$7.error("获取数据库信息失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async create(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");const n=await this.context.dbManager.create(e,t,r);return logger$7.info(`创建实例成功,ID: ${n}`),[n,null]}catch(e){return logger$7.error("创建实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async delete(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.delete(e,t,r),logger$7.info(`删除实例成功,ID: ${r}`),null}catch(e){return logger$7.error("删除实例失败:",e),e instanceof Error?e:new Error(String(e))}}async save(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.save(e,t,r),logger$7.info("更新实例成功"),null}catch(e){return logger$7.error("更新实例失败:",e),e instanceof Error?e:new Error(String(e))}}async deleteMany(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.deleteMany(e,t,r),logger$7.info("删除多个实例成功"),null}catch(e){return logger$7.error("删除多个实例失败:",e),e instanceof Error?e:new Error(String(e))}}async has(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return await this.context.dbManager.has(e,t,r)}catch(e){return logger$7.error("检查实例是否存在失败:",e),!1}}async find(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.find(e,t,r),null]}catch(e){return logger$7.error("查询实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async findByID(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.findByID(e,t,r),null]}catch(e){return logger$7.error("通过ID查询实例失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async modifiedSince(e,t,r){try{if(this.assertInitialized(),await this.initDBManager(),!this.context.dbManager)throw new Error("数据库管理器未初始化");return[await this.context.dbManager.modifiedSince(e,t,r),null]}catch(e){return logger$7.error("查询修改时间大于指定时间的实例ID失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)throw new Error("数据库模块未初始化")}}class MessageClient{constructor(e,t,r){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiverClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMsgToUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{const t=this.client.peerAddr.getPeerId();if(!t)throw new Error("peerId is undefined");if(!this.receiverClient)throw new Error("receiverClient is undefined");const r=await this.getToUserBoxAuth(e.signature),n=new dcnet.pb.SendMsgToUserBoxRequest({});n.msg=e,n.AuthSignature=r,n.PeerId=(new TextEncoder).encode(t.toString());const i=dcnet.pb.SendMsgToUserBoxRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.receiverClient.p2pNode,this.receiverClient.peerAddr,this.receiverClient.token,this.receiverClient.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/SendMsgToUserBox",i,3e4);return dcnet.pb.SendMsgToUserBoxReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.receiverClient.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/SendMsgToUserBox",i,3e4);return dcnet.pb.SendMsgToUserBoxReply.decode(e).flag}throw e}}}),Object.defineProperty(this,"getToUserBoxAuth",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{const t=new dcnet.pb.GetToUserBoxAuthRequest({});t.msgSignature=e;const r=dcnet.pb.GetToUserBoxAuthRequest.encode(t).finish(),n=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await n.unaryCall("/dcnet.pb.Service/GetToUserBoxAuth",r,3e4);return dcnet.pb.GetToUserBoxAuthReply.decode(e).signature}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await n.unaryCall("/dcnet.pb.Service/GetToUserBoxAuth",r,3e4);return dcnet.pb.GetToUserBoxAuthReply.decode(e).signature}throw e}}}),this.client=e,this.context=t,this.receiverClient=r}async getMaxKeyFromUserBox(e){const t=new dcnet.pb.GetMaxKeyFromUserBoxRequest;t.appId=(new TextEncoder).encode(e);const r=dcnet.pb.GetMaxKeyFromUserBoxRequest.encode(t).finish();try{const e=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),t=await e.unaryCall("/dcnet.pb.Service/GetMaxKeyFromUserBox",r,3e4),n=dcnet.pb.GetMaxKeyFromUserBoxReply.decode(t);return n.maxkey?toString$9(n.maxkey):""}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),n=await t.unaryCall("/dcnet.pb.Service/GetMaxKeyFromUserBox",r,3e4),i=dcnet.pb.GetMaxKeyFromUserBoxReply.decode(n);return i.maxkey?toString$9(i.maxkey):""}if(-1!=t.message.indexOf("datastore: key not found"))return"";throw t}}async getMsgFromUserBox(e,t,r){const n=new dcnet.pb.GetMsgFromUserBoxRequest;n.appId=(new TextEncoder).encode(e),n.blockheight=0,n.seekKey=(new TextEncoder).encode(t),n.limit=r;const i=dcnet.pb.GetMsgFromUserBoxRequest.encode(n).finish();try{const e=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),t=await e.unaryCall("/dcnet.pb.Service/GetMsgFromUserBox",i,3e4);return dcnet.pb.GetMsgFromUserBoxReply.decode(t).toJSON()}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),r=await t.unaryCall("/dcnet.pb.Service/getMsgFromUserBox",i,3e4);return dcnet.pb.GetMsgFromUserBoxReply.decode(r).toJSON()}throw t}}}let DCError$1=class extends Error{constructor(e){super(e),this.name="DCError"}};const Errors$4={ErrNoDcPeerConnected:new DCError$1("no dc peer connected"),ErrGetUserInfoError:new DCError$1("get user info error"),ErrNoAccountPeerConnected:new DCError$1("no account peer connected"),ErrNoReceiverPeerConnected:new DCError$1("no receiver peer connected")};class MessageManager{constructor(e,t,r){var n=this;Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMsgToUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{try{if(!this.context.AccountBackupDc.client)return[null,Errors$4.ErrNoAccountPeerConnected];const n=Ed25519PubKey.edPubkeyFromStr(t),i=await this.context.getPublicKey(),o=await this.generateMsqBoxReq(e,n,r);let s=await this.dc.connectToUserDcPeer(n.raw);if(!s)return[null,Errors$4.ErrNoReceiverPeerConnected];const a=await s.GetToken(e,i.string(),(e=>this.context.sign(e)));s.token=a;const c=new MessageClient(this.context.AccountBackupDc.client,this.context,s);return[await c.sendMsgToUserBox(o),null]}catch(e){throw e}}}),Object.defineProperty(this,"getMsgFromUserBox",{enumerable:!0,configurable:!0,writable:!0,value:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100;try{if(!n.context.AccountBackupDc.client)return[null,Errors$4.ErrNoAccountPeerConnected];const r=await n.context.getPublicKey(),i=r.string(),o=await n.dc.connectToUserAllDcPeers(r.raw);if(!o)return[null,Errors$4.ErrNoDcPeerConnected];let s=[];for(const r of o)if(r){const o=r.peerAddr.getPeerId()||"",a=n.context.getPublicKey().string();if(!r.token){const t=await r.GetToken(e,a,(e=>n.context.sign(e)));r.token=t}const c=new MessageClient(r,n.context);let l=await c.getMaxKeyFromUserBox(e);const u=localStorage.getItem("userBoxMaxKey_"+a)||"";let d=u?JSON.parse(u):{};if(l){(d[i]||{})[o]=l}let h=!0;for(;h;)try{const r=await c.getMsgFromUserBox(e,l,t),n=r&&r.msgs?r.msgs:[];n.map((e=>{e&&e.messageId&&s.push(e)})),n.length<t&&(l&&localStorage.setItem("userBoxMaxKey_"+a,JSON.stringify(d)),h=!1)}catch(e){}}return[s,null]}catch(e){return[null,e]}}}),Object.defineProperty(this,"generateMsqBoxReq",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{const n=`${r}${1e6*Date.now()}`,i=(new TextEncoder).encode(n),o=await sha256$3.digest(i),s=CID$1.create(1,85,o),a=(new TextEncoder).encode(s.toString()),c=(new TextEncoder).encode(e),l=await this.context.getPublicKey(),u=(new TextEncoder).encode(l.string()),d=(new TextEncoder).encode(t.string()),h=await this.chainUtil.getBlockHeight()||0,p=uint32ToLittleEndianBytes(h),f=(new TextEncoder).encode(r),y=await t.encrypt(f),g=new Uint8Array([...a,...d,...c,...p,...y]),b=await this.context.sign(g),m=new dcnet.pb.UserMsg({});return m.appId=(new TextEncoder).encode(e),m.blockheight=h,m.encryptMsg=y,m.messageId=a,m.receiverPubkey=d,m.senderPubkey=u,m.signature=b,m}}),this.dc=e,this.chainUtil=t,this.context=r}}const logger$6=createLogger("MessageModule");class MessageModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.MESSAGE}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.context=e,this.messageManager=new MessageManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$6.error("消息模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async sendMsgToUserBox(e,t){try{this.assertInitialized();const r=await this.messageManager.sendMsgToUserBox(this.context.appInfo?.appId||"",e,t);return logger$6.info(`发送消息到用户 ${e} 成功`),r}catch(t){return logger$6.error(`发送消息到用户 ${e} 失败:`,t),[null,t]}}async getMsgFromUserBox(e){try{this.assertInitialized();const t=await this.messageManager.getMsgFromUserBox(this.context.appInfo?.appId||"",e);return logger$6.info("获取用户消息成功"),t}catch(e){return logger$6.error("获取用户消息失败:",e),[null,e]}}assertInitialized(){if(!this.initialized)throw new Error("消息模块未初始化")}}class KeyValueClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e,this.context=t}async configThemeObjAuth(e,t,r,n,i,o,s,a,c,l,u){const d=new dcnet.pb.ConfigThemeObjAuthRequest({});d.appId=(new TextEncoder).encode(t),d.themeAuthor=(new TextEncoder).encode(r),d.theme=(new TextEncoder).encode(e),d.blockheight=n,d.content=(new TextEncoder).encode(s),d.contentCid=(new TextEncoder).encode(o),d.contentSize=a,d.signature=l,d.type=c,d.userPubkey=(new TextEncoder).encode(i),u&&(d.vaccount=(new TextEncoder).encode(u));const h=dcnet.pb.ConfigThemeObjAuthRequest.encode(d).finish(),p=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await p.unaryCall("/dcnet.pb.Service/ConfigThemeObjAuth",h,3e4);return dcnet.pb.ConfigThemeObjAuthReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await p.unaryCall("/dcnet.pb.Service/ConfigThemeObjAuth",h,3e4);return dcnet.pb.GetUserCommentsReply.decode(e).flag}throw e}}async setKeyValue(e,t,r,n,i,o,s,a,c,l,u){const d=new dcnet.pb.SetKeyValueRequest({});d.appId=(new TextEncoder).encode(t),d.themeAuthor=(new TextEncoder).encode(r),d.theme=(new TextEncoder).encode(e),d.blockheight=n,d.content=(new TextEncoder).encode(s),d.contentCid=(new TextEncoder).encode(o),d.contentSize=a,d.signature=l,d.type=c,d.userPubkey=(new TextEncoder).encode(i),u&&(d.vaccount=(new TextEncoder).encode(u));const h=dcnet.pb.SetKeyValueRequest.encode(d).finish(),p=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await p.unaryCall("/dcnet.pb.Service/SetKeyValue",h,3e4);return dcnet.pb.SetKeyValueReply.decode(e).flag}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await p.unaryCall("/dcnet.pb.Service/SetKeyValue",h,3e4);return dcnet.pb.GetUserCommentsReply.decode(e).flag}throw e}}async getValueWithKey(e,t,r,n,i,o){const s=new dcnet.pb.GetValueWithKeyRequest({});s.appId=(new TextEncoder).encode(t),s.themeAuthor=(new TextEncoder).encode(r),s.theme=(new TextEncoder).encode(e),s.UserPubkey=(new TextEncoder).encode(n),s.Key=(new TextEncoder).encode(i),o&&(s.vaccount=(new TextEncoder).encode(o));const a=dcnet.pb.GetValueWithKeyRequest.encode(s).finish(),c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await c.unaryCall("/dcnet.pb.Service/GetValueWithKey",a,3e4),t=dcnet.pb.GetValueWithKeyReply.decode(e);return 0==t.flag?t.value:null}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await c.unaryCall("/dcnet.pb.Service/GetValueWithKey",a,3e4),r=dcnet.pb.GetValueWithKeyReply.decode(e);return 0==r.flag?r.value:null}throw e}}async getValuesWithKeys(e,t,r,n,i,o){const s=new dcnet.pb.GetValuesWithKeysRequest({});s.appId=(new TextEncoder).encode(t),s.themeAuthor=(new TextEncoder).encode(r),s.theme=(new TextEncoder).encode(e),s.UserPubkey=(new TextEncoder).encode(n),s.Keys=(new TextEncoder).encode(i),o&&(s.vaccount=(new TextEncoder).encode(o));const a=dcnet.pb.GetValuesWithKeysRequest.encode(s).finish(),c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await c.unaryCall("/dcnet.pb.Service/GetValuesWithKeys",a,3e4),t=dcnet.pb.GetValuesWithKeysReply.decode(e);return 0==t.flag?t.keyValues:null}catch(e){if(-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(t,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await c.unaryCall("/dcnet.pb.Service/GetValuesWithKeys",a,3e4),r=dcnet.pb.GetValuesWithKeysReply.decode(e);return 0==r.flag?r.keyValues:null}throw e}}async getValuesWithIndex(e,t,r,n,i,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:exports.Direction.Forward,a=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0;const u=new dcnet.pb.GetValuesWithIndexRequest({});u.appId=(new TextEncoder).encode(e),u.themeAuthor=(new TextEncoder).encode(t),u.theme=(new TextEncoder).encode(r),u.indexKey=(new TextEncoder).encode(n),u.indexValue=(new TextEncoder).encode(i),u.seekKey=(new TextEncoder).encode(o),u.direction=s,u.offset=a,u.limit=c,l&&(u.vaccount=(new TextEncoder).encode(l));const d=dcnet.pb.GetValuesWithIndexRequest.encode(u).finish(),h=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await h.unaryCall("/dcnet.pb.Service/GetValuesWithIndex",d,3e4),t=dcnet.pb.GetValuesWithIndexReply.decode(e);return 0==t.flag?t.keyValues:null}catch(t){if(-1!=t.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(e,this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const t=await h.unaryCall("/dcnet.pb.Service/GetValuesWithIndex",d,3e4),r=dcnet.pb.GetValuesWithIndexReply.decode(t);return 0==r.flag?r.keyValues:null}throw t}}}var KeyValueStoreType;!function(e){e[e.Auth=1]="Auth",e[e.Public=2]="Public"}(KeyValueStoreType||(KeyValueStoreType={}));class KeyValueError extends Error{constructor(e){super(e),this.name="KeyValueError"}}const Errors$3={ErrNoDcPeerConnected:new KeyValueError("no dc peer connected"),ErrPublicKeyIsNull:new KeyValueError("publickey is null")};class KeyValueDB{constructor(e,t,r,n){Object.defineProperty(this,"appId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbname",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"themeAuthor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.appId=e,this.dbname=t,this.themeAuthor=r,this.manager=n}async set(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";return this.manager.setKeyValue(this.appId,this.themeAuthor,this.dbname,e,t,r,n)}async get(e,t,r){if(!t){const[t,r]=await this.getWithIndex("dc_timestamp_index","",1,"",exports.Direction.Reverse,0);if(r)return[null,r];if(!t)return[null,null];const n=JSON.parse(t);if(!Array.isArray(n))return[t,null];if(0==n.length)return[null,null];let i="";try{i=n[0][e]}catch(e){return[null,e instanceof Error?e:new Error(String(e))]}return i&&0!=i.length||(i=n[0]),[i,null]}return this.manager.getValueWithKey(this.appId,this.themeAuthor,this.dbname,t,e,r)}async getBatch(e,t,r){return t||(t=this.themeAuthor),this.manager.getValuesWithKeys(this.appId,this.themeAuthor,this.dbname,t,e,r)}async getWithIndex(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:exports.Direction.Forward,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:"";return this.manager.getWithIndex(this.appId,this.themeAuthor,this.dbname,e,t,n,i,o,r,s)}async configAuth(e,t,r,n){return this.manager.doConfigAuth(this.appId,this.themeAuthor,this.dbname,e,t,r,n)}async getAuthList(e){return this.manager.getAuthList(this.appId,this.themeAuthor,this.dbname,e)}}class KeyValueManager{constructor(e,t,r){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.dc=e,this.chainUtil=t,this.context=r}async createStore(e,t,r,n){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];if(""===e&&(e="DCAPP"),r<100<<20&&(r=100<<20),t.startsWith("keyvalue_")||(t="keyvalue_"+t),n===KeyValueStoreType.Public&&!t.endsWith("_pub"))return[null,new Error("vaCreateStoreTheme failed, public theme must end with '_pub'")];try{const n=new CommentManager(this.context),i=await n.addThemeObj(e,t,OpenFlag.AUTH,r||52428800);if(0!==i[0]||null!==i[1])return[null,new Error(`vaCreateStoreTheme failed, resFlag: ${i}`)];return[new KeyValueDB(e,t,this.context.publicKey.string(),this),null]}catch(e){return[null,e]}}async getKeyValueDB(e,t,r){const n=new CommentManager(this.context);t.startsWith("keyvalue_")||(t="keyvalue_"+t);const[i,o]=await n.isThemeExist(e,t,r);if(o)return[null,o];if(!i)return[null,new Error(`Theme ${t} does not exist for appId ${e}`)];return[new KeyValueDB(e,t,r,this),null]}async doConfigAuth(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(e,this.context.publicKey.string(),this.context.sign);const l=Ed25519PubKey.edPubkeyFromStr(t);let u,d=!0,h=null;try{h=Ed25519PubKey.edPubkeyFromStr(n)}catch(e){d=!1}u=d&&null!==h?h.string():n;const p=`${u}:${i}:${o}`,f=(new TextEncoder).encode(p),y=await sha256(f),g=base32$5.encode(y);let b;try{b=await this.chainUtil.getBlockHeight()||0}catch(e){return[null,new Error("ErrGetBlockHeightFail")]}const m=f.length,w=uint32ToLittleEndianBytes(b||0),v=uint32ToLittleEndianBytes(exports.CommentType.Comment),S=(new TextEncoder).encode(r),$=(new TextEncoder).encode(e),x=(new TextEncoder).encode(l.string()),E=(new TextEncoder).encode(g);let A=new Uint8Array([...S,...$,...x,...w,...E,...v]);const P=await this.context.sign(A),k=new KeyValueClient(c,this.context);try{const n=await k.configThemeObjAuth(r,e,t,b,a,g,p,m,exports.CommentType.Comment,P,s);return 0!==n?[n,new Error(`configThemeObjAuth fail, resFlag: ${n}`)]:[0,null]}catch(e){return[null,e]}}async getAuthList(e,t,r,n){r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let i="",o=[],s=[];try{for(;;){const a=new CommentManager(this.context),c=await a.getThemeComments(e,r,t,0,exports.Direction.Forward,0,1e3,i||"",n);if(c[0]&&0==c[0].length)break;const l=c[0];if(!l||0==l.length)break;for(let e=0;e<l.length;e++){o.push(l[e]);const t=l[e].comment,r=t.split(":");if(r.length<2)continue;const n=r[0],i=parseInt(r[1]),a=t.substring(r[0].length+2);s.push({pubkey:n,permission:i,remark:a})}if(l.length<1e3)break;i=`${l[l.length-1].blockheight}/${l[l.length-1].commentCid}`}}catch(e){return[s,o,e]}return[s,o,null]}async setKeyValue(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(e,this.context.publicKey.string(),this.context.sign);let l=`${n}:${i}`;""!=o&&(l=`$$i_start$$${o}$$i_end$$${l}`);const u=(new TextEncoder).encode(l),d=await sha256(u),h=base32$5.encode(d),p=u.length,f=await this.chainUtil.getBlockHeight()||0,y=uint32ToLittleEndianBytes(f||0),g=(new TextEncoder).encode(r),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(e),w=(new TextEncoder).encode(h),v=uint32ToLittleEndianBytes(exports.CommentType.KeyValue),S=new Uint8Array([...g,...m,...b,...y,...w,...v]),$=await this.context.sign(S),x=new KeyValueClient(c,this.context);try{const n=await x.setKeyValue(r,e,t,f,a,h,l,p,exports.CommentType.KeyValue,$,s);return 0!==n?[null,new Error(`setKeyValue fail, resFlag:${n}`)]:[!0,null]}catch(e){return[null,e]}}async getValueWithKey(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let s=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(s=await this.dc.connectToUserDcPeer(e.raw),!s)return[null,Errors$3.ErrNoDcPeerConnected]}if(null===s)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===s.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==s.token&&await s.GetToken(e,this.context.publicKey.string(),this.context.sign);const a=new KeyValueClient(s,this.context);try{const s=await a.getValueWithKey(r,e,t,n,i,o);if(null==s)return[null,new Error(`vaGetValueWithKeyForVAccount fail, resFlag:${s}`)];return[(new TextDecoder).decode(s),null]}catch(e){return[null,e]}}async getValuesWithKeys(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let s=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(s=await this.dc.connectToUserDcPeer(e.raw),!s)return[null,Errors$3.ErrNoDcPeerConnected]}if(null===s)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===s.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==s.token&&await s.GetToken(e,this.context.publicKey.string(),this.context.sign);const a=new KeyValueClient(s,this.context);try{const s=await a.getValuesWithKeys(r,e,t,n,i,o);if(null==s)return[null,new Error(`vaGetValuesWithKeysForVAccount fail, resFlag:${s}`)];return[(new TextDecoder).decode(s),null]}catch(e){return[null,e]}}async getWithIndex(e,t,r,n,i,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:exports.Direction.Forward,a=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0;if(!this.context.publicKey)return[null,Errors$3.ErrPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let u=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const r=Ed25519PubKey.edPubkeyFromStr(t);if(u=await this.dc.connectToUserDcPeer(r.raw),!u)return[null,Errors$3.ErrNoDcPeerConnected];await u.GetToken(e,this.context.publicKey.string(),this.context.sign)}if(null===u)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===u.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==u.token&&await u.GetToken(e,this.context.publicKey.string(),this.context.sign);const d=new KeyValueClient(u,this.context);try{const u=await d.getValuesWithIndex(e,t,r,n,i,o,s,a,c,l);if(null==u)return[null,new Error(`vaGetValuesWithKeysForVAccount fail, resFlag:${u}`)];return[(new TextDecoder).decode(u),null]}catch(e){return[null,e]}}}const logger$5=createLogger("KeyValueModule"),indexkey_dckv="indexkey_dckv";class KeyValueModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.KEYVALUE}),Object.defineProperty(this,"keyValueManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.keyValueManager=new KeyValueManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$5.error("键值存储模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async createStore(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];try{const[i,o]=await this.keyValueManager.createStore(e,t,r,n);return[i,o]}catch(e){return logger$5.error(`创建存储主题 ${t} 失败:`,e),[null,e instanceof Error?e:new Error(String(e))]}}async getStore(e,t,r){const n=this.assertInitialized();if(n)return[null,n];try{const[n,i]=await this.keyValueManager.getKeyValueDB(e,t,r);return[n,i]}catch(e){return logger$5.error(`获取存储主题 ${t} 失败:`,e),[null,e instanceof Error?e:new Error(String(e))]}}async configAuth(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];try{return await e.configAuth(t,r,n,i)}catch(e){return logger$5.error("配置权限失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getAuthList(e,t){const r=this.assertInitialized();if(r)return[null,null,r];try{return await e.getAuthList(t)}catch(e){return logger$5.error("获取权限列表失败:",e),[null,null,e instanceof Error?e:new Error(String(e))]}}async set(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];try{let o="";try{if(n&&""!=n){const e=JSON.parse(n);for(const t of e){let e="";e="number"===t.type?padPositiveInt30(t.value):t.value,o+=`${t.key}:${e}$$$`}}}catch(e){logger$5.error("设置索引,解析失败:",e)}const s=Date.now();o+=`dc_timestamp_index:${padPositiveInt30(s)}`;return await e.set(t,r,o,i)}catch(e){return logger$5.error("设置set-value失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async get(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];try{return await e.get(t,r,n)}catch(e){return logger$5.error("获取key-value失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getValues(e,t,r,n){const i=this.assertInitialized();if(i)return[null,i];const o=r.limit?r.limit:10,s=r.seekKey?r.seekKey:"",a=r.direction?r.direction:exports.Direction.Forward,c=r.offset?r.offset:0;try{return await e.getWithIndex(indexkey_dckv,t,o,s,a,c,n)}catch(e){return logger$5.error("getValues失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getBatch(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";const i=this.assertInitialized();if(i)return[null,i];try{return await e.getBatch(t,r,n)}catch(e){return logger$5.error("getBatch失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async getWithIndex(e,t,r,n,i){const o=this.assertInitialized();if(o)return[null,o];const s=n.limit?n.limit:10,a=n.seekKey?n.seekKey:"",c=n.direction?n.direction:exports.Direction.Forward,l=n.offset?n.offset:0;let u="";"number"===n.type&&(u=padPositiveInt30(r));try{return await e.getWithIndex(t,u,s,a,c,l,i)}catch(e){return logger$5.error("getWithIndex失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)return Error("键值存储模块未初始化")}}class DCClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e}async getHostID(e){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");e||(e=this.client.peerAddr);const t=new dcnet.pb.GetHostIDRequest({}),r=dcnet.pb.GetHostIDRequest.encode(t).finish(),n=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,e||this.client.peerAddr,this.client.token,this.client.protocol),i=await n.unaryCall("/dcnet.pb.Service/GetHostID",r,3e4),o=dcnet.pb.GetHostIDReply.decode(i),s=base58btc$4.encode(o.peerID),a=toString$9(o.reqAddr);return{peerID:s,reqAddr:a}}catch(e){throw e}}}class DCError extends Error{constructor(e){super(e),this.name="DCError"}}const Errors$2={ErrNoDcPeerConnected:new DCError("no dc peer connected")};class DCManager{constructor(e){Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.connectedDc=e}async getHostID(e){if(!this.connectedDc?.client)return[null,Errors$2.ErrNoDcPeerConnected];const t=new DCClient(this.connectedDc.client);return[await t.getHostID(e),null]}}const logger$4=createLogger("ClientModule");class ClientModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.CLIENT}),Object.defineProperty(this,"clientManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.clientManager=new DCManager(e.connectedDc),this.initialized=!0,!0}catch(e){return logger$4.error("消息模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async getHostID(){try{this.assertInitialized();const e=await this.clientManager.getHostID();return e[0]?logger$4.info(`获取hostID成功: ${e[0].peerID}, 公网地址: ${e[0].reqAddr}`):logger$4.error("获取hostID失败:",e[1]),e}catch(e){return logger$4.error("获取hostID时发生错误:",e),[null,e]}}assertInitialized(){if(!this.initialized)throw new Error("消息模块未初始化")}}class CacheClient{constructor(e,t,r){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=r,this.context=e,this.dc=t}async getCacheValue(e,t){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");e?e.equals(this.client.peerAddr)||(await this.dc.connectToPeer(e.toString()),this.client=new Client(this.client.p2pNode,this.client.blockstore,e,this.client.protocol),await this.client.GetToken(this.context.appInfo.appId,this.context.publicKey.string(),this.context.sign,e)):e=this.client.peerAddr;const r=new dcnet.pb.GetCacheValueRequest({});r.key=(new TextEncoder).encode(t);const n=dcnet.pb.GetCacheValueRequest.encode(r).finish(),i=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,e||this.client.peerAddr,this.client.token,this.client.protocol),o=await i.unaryCall("/dcnet.pb.Service/GetCacheValue",n,3e4),s=dcnet.pb.GetCacheValueReply.decode(o);return toString$9(s.value)}catch(e){throw e}}async setCacheKey(e,t,r,n,i){try{if(null==this.client.p2pNode)throw new Error("p2pNode is null");i||(i=this.client.peerAddr);const o=new dcnet.pb.SetCacheKeyRequest({});o.value=(new TextEncoder).encode(e),o.blockheight=t,o.expire=r,o.signature=n;const s=dcnet.pb.SetCacheKeyRequest.encode(o).finish(),a=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,i||this.client.peerAddr,this.client.token,this.client.protocol),c=await a.unaryCall("/dcnet.pb.Service/SetCacheKey",s,3e4),l=dcnet.pb.SetCacheKeyReply.decode(c);if(l.cacheKey){return toString$9(l.cacheKey)}throw new Error("SetCacheKey failed,flag: "+l.flag)}catch(e){throw e}}}class CacheError extends Error{constructor(e){super(e),this.name="CacheError"}}const Errors$1={ErrNoDcPeerConnected:new CacheError("no dc peer connected"),ErrKeyNotValid:new CacheError("key not valid"),ErrNodeAddrIsNull:new CacheError("nodeAddr is null"),ErrChainUtilIsNull:new CacheError("chainUtil is null"),ErrAccountPrivateSignIsNull:new CacheError("account privatekey sign is null")};class CacheManager{constructor(e,t,r){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t,r)=>{if(!this.context?.AccountBackupDc.client)return[null,Errors$1.ErrNoDcPeerConnected];if(!this.chainUtil)return[null,Errors$1.ErrChainUtilIsNull];if(!this.context)return[null,Errors$1.ErrAccountPrivateSignIsNull];const n=await this.chainUtil.getBlockHeight(),i=(new TextEncoder).encode(e),o=await sha256(i),s=uint32ToLittleEndianBytes(n||0),a=uint32ToLittleEndianBytes(t),c=new Uint8Array(a.length+s.length);c.set(a,0),c.set(s,a.length);const l=new Uint8Array(c.length+o.length);l.set(c,0),l.set(o,c.length);const u=await this.context.sign(l),d=new CacheClient(this.context,this.dc,this.context?.AccountBackupDc.client);return[await d.setCacheKey(e,n||0,t,u),null]}}),this.dc=e,this.chainUtil=t,this.context=r}async getCacheValue(e,t){if(!this.context?.connectedDc?.client)return[null,Errors$1.ErrNoDcPeerConnected];const r=e.split("/");if(2!=r.length)return[null,Errors$1.ErrKeyNotValid];if(!this.context?.connectedDc.client)return[null,Errors$1.ErrNoDcPeerConnected];const n=r[0],i=r[1];try{let e;if(this.context?.connectedDc.nodeAddr){const t=this.context.connectedDc.nodeAddr.getPeerId()||"";e=t&&t===n?this.context.connectedDc.nodeAddr:await(this.dc?._getNodeAddr(n))}else e=await(this.dc?._getNodeAddr(n));if(!e)return[null,Errors$1.ErrNodeAddrIsNull];const t=new CacheClient(this.context,this.dc,this.context.connectedDc.client);return[await t.getCacheValue(e,i),null]}catch(e){return[null,e]}}}const logger$3=createLogger("CacheModule");class CacheModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.CACHE}),Object.defineProperty(this,"cacheManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async initialize(e){try{return this.cacheManager=new CacheManager(e.dcutil,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$3.error("键值存储模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async getCacheValue(e){try{this.assertInitialized();const t=await this.cacheManager.getCacheValue(e);return t[0]?(logger$3.info(`获取缓存键 ${e} 成功`),[t[0],null]):(logger$3.info(`缓存键 ${e} 不存在`),[null,null])}catch(t){return logger$3.error(`获取缓存键 ${e} 失败:`,t),[null,t instanceof Error?t:new Error(String(t))]}}async setCacheKey(e,t){try{this.assertInitialized();const r=t||keyExpire,n=await this.cacheManager.setCacheKey(e,r);return logger$3.info(`设置缓存值成功,过期时间: ${r}秒`),n}catch(e){return logger$3.error("设置缓存值失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}assertInitialized(){if(!this.initialized)throw new Error("键值存储模块未初始化")}}class AIProxyClient{constructor(e,t){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e,this.context=t}async GetAIProxyConfig(e,t,r){const n=new dcnet.pb.GetAIProxyConfigRequest({});n.appId=(new TextEncoder).encode(e),n.themeAuthor=(new TextEncoder).encode(t),n.theme=(new TextEncoder).encode(r);const i=dcnet.pb.GetAIProxyConfigRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/GetAIProxyConfig",i,3e4),t=dcnet.pb.GetAIProxyConfigReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);const r=(new TextDecoder).decode(t.proxyConfigCid);return[r,(new TextDecoder).decode(t.aeskey),null]}catch(e){if("object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message&&-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/GetAIProxyConfig",i,3e4),t=dcnet.pb.GetAIProxyConfigReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);return[(new TextDecoder).decode(t.proxyConfigCid),(new TextDecoder).decode(t.aeskey),null]}throw e}}async GetUserOwnAIProxyAuth(e,t,r){const n=new dcnet.pb.GetUserOwnAIProxyAuthRequest({});n.appId=(new TextEncoder).encode(e),n.themeAuthor=(new TextEncoder).encode(t),n.theme=(new TextEncoder).encode(r);const i=dcnet.pb.GetUserOwnAIProxyAuthRequest.encode(n).finish(),o=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);try{const e=await o.unaryCall("/dcnet.pb.Service/GetUserOwnAIProxyAuth",i,3e4),t=dcnet.pb.GetUserOwnAIProxyAuthReply.decode(e);if(0!=t.flag)throw new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag);return[(new TextDecoder).decode(t.authInfo),null]}catch(e){if("object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message&&-1!=e.message.indexOf(Errors$a.INVALID_TOKEN.message)){if(!await this.client.GetToken(this.context.appInfo.appId||"",this.context.getPublicKey().string(),(e=>this.context.sign(e))))throw new Error(Errors$a.INVALID_TOKEN.message);const e=await o.unaryCall("/dcnet.pb.Service/GetUserOwnAIProxyAuth",i,3e4),t=dcnet.pb.GetUserOwnAIProxyAuthReply.decode(e);if(0!=t.flag)return["",new Error(Errors$a.INVALID_TOKEN.message+" flag:"+t.flag)];return[(new TextDecoder).decode(t.authInfo),null]}return["",e instanceof Error?e:new Error(String(e))]}}async DoAIProxyCall(e,t,r,n,i,o,s,a,c,l,u,d){let h=arguments.length>12&&void 0!==arguments[12]?arguments[12]:null;const p=new dcnet.pb.DoAIProxyCallRequest({});p.appId=(new TextEncoder).encode(t),p.themeAuthor=(new TextEncoder).encode(r),p.theme=(new TextEncoder).encode(n),p.configKey=(new TextEncoder).encode(i),p.path=(new TextEncoder).encode(o),p.headers=(new TextEncoder).encode(s),p.reqBody=(new TextEncoder).encode(a),p.modelConfig=(new TextEncoder).encode(c),p.forceRefresh=l,p.blockheight=u,p.signature=d;const f=dcnet.pb.DoAIProxyCallRequest.encode(p).finish(),y=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol);let g=!1,b=null,m=!1,w=!1;const v=()=>{b&&(clearTimeout(b),b=null)},S=()=>{v(),b=setTimeout((()=>{m||w||!g||(w=!0,h&&h(exports.AIStreamResponseFlag.STREAM_HANG,"","数据流超时:超过30秒未收到响应数据"))}),6e4)},$=()=>!!e.signal?.aborted&&(w=!0,v(),!0),x=async e=>{if(!(w||m||$())){g=!0,S();try{const t=dcnet.pb.DoAIProxyCallReply.decode(e);t.flag==exports.AIStreamResponseFlag.CONNECTION_CLOSED&&(m=!0,v()),h&&h(t.flag,(new TextDecoder).decode(t.content),(new TextDecoder).decode(t.err))}catch(e){h&&h(exports.AIStreamResponseFlag.OTHER_ERROR,"",e instanceof Error?e.message:String(e))}}},E=async()=>{v(),w||$()||m||(m=!0,h&&h(exports.AIStreamResponseFlag.CONNECTION_CLOSED,"",""))},A=async e=>{w||$()||m||h&&h(exports.AIStreamResponseFlag.OTHER_ERROR,"",e instanceof Error?e.message:String(e))};let P=null;if(e.signal){if(e.signal.aborted)return w=!0,v(),exports.AIStreamResponseFlag.EXTERNAL_EXIT;P=()=>{w=!0,v(),h&&h(exports.AIStreamResponseFlag.EXTERNAL_EXIT,"","调用被用户中止")},e.signal.addEventListener("abort",P)}try{return S(),await y.Call("/dcnet.pb.Service/DoAIProxyCall",f,1e7,"server-streaming",x,void 0,E,A,e),0}catch(t){if(m=!0,v(),w)return exports.AIStreamResponseFlag.STREAM_HANG;if(e.signal?.aborted)return exports.AIStreamResponseFlag.EXTERNAL_EXIT;throw t}finally{v(),P&&e.signal&&e.signal.removeEventListener("abort",P)}}}class AIProxyError extends Error{constructor(e){super(e),this.name="AIProxyError"}}const Errors={ErrNoDcPeerConnected:new AIProxyError("no dc peer connected"),ErrKeyNotValid:new AIProxyError("key not valid"),ErrNodeAddrIsNull:new AIProxyError("nodeAddr is null"),ErrChainUtilIsNull:new AIProxyError("chainUtil is null"),ErrAccountPrivateSignIsNull:new AIProxyError("account privatekey sign is null"),ErrAccountPublicKeyIsNull:new AIProxyError("account publickey is null")};class AIProxyManager{constructor(e,t,r,n){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcNodeClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleAllConfig",{enumerable:!0,configurable:!0,writable:!0,value:async(e,t)=>{const r=new BrowserLineReader(e);let n=[],i=[];if(!this.context.getPublicKey())return null;const o=SymmetricKey.fromString(t);for(;;){const{line:e,error:t}=readLine(r);if(t&&"EOF"!==t.message)break;if(e){const t=(new TextDecoder).decode(e);if(!t)break;const r=base32$5.decode(t),s=await o.decrypt(r),a=(new TextDecoder).decode(s);if(!a)continue;if(a.startsWith("$$auth$$:")){try{const e=a.split("$$auth$$:")[1];if(!e)continue;const t=e.split(":");if(t.length<2)continue;const r=t[0]||"",n=t[1]||"",o=e.substring(r.length+n.length+2),s=JSON.parse(o);i.push({UserPubkey:r,permission:parseInt(n),authConfig:s})}catch(e){}continue}const c=a.split(":");if(c.length<2)continue;const l=a.substring((c[0]||"").length+1);try{const e=JSON.parse(l);n.push(e)}catch(e){}}}return[i,n]}}),this.dc=e,this.dcNodeClient=t,this.chainUtil=r,this.context=n}async createProxyConfig(e,t){""===e&&(e="DCAPP");t.startsWith("keyvalue_")||(t="keyvalue_"+t);try{const r=new CommentManager(this.context);return await r.addThemeObj(e,t,OpenFlag.AUTH,104857600)}catch(e){return[null,e]}}async deleteProxyConfig(e,t){""===e&&(e="DCAPP"),t.startsWith("keyvalue_")||(t="keyvalue_"+t);try{const r=new CommentManager(this.context);return await r.deleteThemeObj(e,t)}catch(e){return[null,e]}}async configAIProxy(e,t,r,n,i,o){if(!this.context.publicKey)return[null,Errors.ErrNoDcPeerConnected];const s=await this.chainUtil.getBlockHeight()||0;let a=this.context.getPublicKey().string();r.startsWith("keyvalue_")||(r="keyvalue_"+r);let c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),!c)return[null,Errors.ErrNoDcPeerConnected];if(await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign),null===c)return[null,Errors.ErrNoDcPeerConnected];""==c.token&&await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);let l="";const u=n;if(i){i.blockheight=s;l=`${u}:${JSON.stringify(i)}`}else l=`${u}`;const d=(new TextEncoder).encode(l),h=await sha256(d),p=base32$5.encode(h),f=d.length,y=uint32ToLittleEndianBytes(s||0),g=(new TextEncoder).encode(r),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(e),w=(new TextEncoder).encode(p),v=uint32ToLittleEndianBytes(exports.CommentType.KeyValue),S=new Uint8Array([...g,...m,...b,...y,...w,...v]),$=await this.context.sign(S),x=new KeyValueClient(c,this.context);try{const n=await x.setKeyValue(r,e,t,s,a,p,l,f,exports.CommentType.KeyValue,$,o);return 0!==n?[null,new Error(`configAIProxy fail, resFlag:${n}`)]:[!0,null]}catch(e){return[!1,e]}}async configAuth(e,t,r,n,i,o,s){if(!this.context.publicKey)return[null,Errors.ErrAccountPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r),r.endsWith("_authlist")||(r+="_authlist");let a=this.context.getPublicKey().string(),c=this.context.AccountBackupDc?.client||null;if(c||(c=await this.dc.connectToUserDcPeer(this.context.publicKey.raw)),null===c)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===c.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==c.token&&await c.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const l=Ed25519PubKey.edPubkeyFromStr(t);let u,d=!0,h=null;try{h=Ed25519PubKey.edPubkeyFromStr(n)}catch(e){d=!1}u=d&&h?h.string():n;const p=`${u}:${i}:${JSON.stringify(o)}`,f=(new TextEncoder).encode(p),y=await sha256(f),g=base32$5.encode(y);let b;try{b=await this.chainUtil.getBlockHeight()||0}catch(e){return[null,new Error("ErrGetBlockHeightFail")]}const m=f.length,w=uint32ToLittleEndianBytes(b||0),v=uint32ToLittleEndianBytes(exports.CommentType.Comment),S=(new TextEncoder).encode(r),$=(new TextEncoder).encode(e),x=(new TextEncoder).encode(l.string()),E=(new TextEncoder).encode(g);let A=new Uint8Array([...S,...$,...x,...w,...E,...v]);const P=await this.context.sign(A),k=new KeyValueClient(c,this.context);try{const n=await k.configThemeObjAuth(r,e,t,b,a,g,p,m,exports.CommentType.Comment,P);if(0!==n)return[null,new Error(`configThemeObjAuth fail, resFlag: ${n}`)]}catch(e){return[null,e]}return[0,null]}async GetAIProxyConfig(e,t,r,n){if(!this.context.publicKey)return[null,null,Errors.ErrAccountPublicKeyIsNull];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let i=this.context.AccountBackupDc.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(i=await this.dc.connectToUserDcPeer(e.raw),!i)return[null,null,Errors.ErrNoDcPeerConnected]}if(null===i)return[null,null,new Error("ErrConnectToAccountPeersFail")];if(null===i.peerAddr)return[null,null,new Error("ErrConnectToAccountPeersFail")];""==i.token&&await i.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);try{const n=new AIProxyClient(i,this.context),[o,s,a]=await n.GetAIProxyConfig(e,t,r);if(a)return[null,null,a];const c=new FileManager(this.dc,this.context.AccountBackupDc,this.chainUtil,this.dcNodeClient,this.context),l=o,u=await c.getFileFromDc(l,"",cidNeedConnect.NOT_NEED,!1);if(!u)return[[],[],null];const d=toString$9(u),h=await this.handleAllConfig(d,s);if(!h)return[[],[],null];const[p,f]=h;return[p,f,null]}catch(e){return[null,null,e]}}async GetUserOwnAIProxyAuth(e,t,r){if(!this.context.publicKey)return[null,new Error("ErrConnectToAccountPeersFail")];r.startsWith("keyvalue_")||(r="keyvalue_"+r);let n=this.context.AccountBackupDc?.client||null;if(t!=this.context.publicKey.string()){const e=Ed25519PubKey.edPubkeyFromStr(t);if(n=await this.dc.connectToUserDcPeer(e.raw),!n)return[null,Errors.ErrNoDcPeerConnected]}if(null===n)return[null,new Error("ErrConnectToAccountPeersFail")];if(null===n.peerAddr)return[null,new Error("ErrConnectToAccountPeersFail")];""==n.token&&await n.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const i=new AIProxyClient(n,this.context),[o,s]=await i.GetUserOwnAIProxyAuth(e,t,r);if(s)return[null,s];try{return[JSON.parse(o),s]}catch(s){return[null,s]}}async DoAIProxyCall(e,t,r,n,i,o,s){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0,u=arguments.length>10?arguments[10]:void 0;n.startsWith("keyvalue_")||(n="keyvalue_"+n);const d=await this.chainUtil.getBlockHeight()||0,h=uint32ToLittleEndianBytes(d||0),p=s?1:0,f=uint32ToLittleEndianBytes(p),y=(new TextEncoder).encode(r),g=(new TextEncoder).encode(n),b=(new TextEncoder).encode(t),m=(new TextEncoder).encode(i),w=(new TextEncoder).encode(l),v=(new TextEncoder).encode(c),S=(new TextEncoder).encode(o),$=(new TextEncoder).encode(u),x=new Uint8Array([...g,...b,...y,...h,...m,...w,...S,...f,...$,...v]);if(!this.context.AccountBackupDc.client)throw new Error("ErrConnectToAccountPeersFail");if(!this.context.publicKey)throw new Error("ErrConnectToAccountPeersFail");""==this.context.AccountBackupDc.client.token&&await this.context.AccountBackupDc.client.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),this.context.sign);const E=await this.context.sign(x),A=new AIProxyClient(this.context.AccountBackupDc.client,this.context);return await A.DoAIProxyCall(e,t,r,n,i,l||"",c||"",o,u||"",p,d,E,a)}}const logger$2=createLogger("KeyValueModule");class AIProxyModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.AIPROXY}),Object.defineProperty(this,"aiProxyManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"aiCallConfig",{enumerable:!0,configurable:!0,writable:!0,value:null})}async initialize(e){try{return this.aiProxyManager=new AIProxyManager(e.dcutil,e.dcNodeClient,e.dcChain,e),this.initialized=!0,!0}catch(e){return logger$2.error("AI代理模块初始化失败:",e),!1}}async shutdown(){this.initialized=!1}async createProxyConfig(e,t){try{return this.assertInitialized(),this.aiProxyManager.createProxyConfig(e,t)}catch(e){return Promise.resolve([null,e])}}async deleteProxyConfig(e,t){try{return this.assertInitialized(),this.aiProxyManager.deleteProxyConfig(e,t)}catch(e){return Promise.resolve([null,e])}}configAIProxy(e,t,r,n,i,o){try{return this.assertInitialized(),this.aiProxyManager.configAIProxy(e,t,r,n,i,o)}catch(e){return Promise.resolve([null,e])}}async configAuth(e,t,r,n,i,o,s){try{return this.assertInitialized(),this.aiProxyManager.configAuth(e,t,r,n,i,o,s)}catch(e){return Promise.resolve([null,e])}}async GetAIProxyConfig(e,t,r,n){try{return this.assertInitialized(),this.aiProxyManager.GetAIProxyConfig(e,t,r,n)}catch(e){return Promise.resolve([null,null,e])}}async GetUserOwnAIProxyAuth(e,t,r){try{return this.assertInitialized(),this.aiProxyManager.GetUserOwnAIProxyAuth(e,t,r)}catch(e){return Promise.resolve([null,e])}}async DoAIProxyCall(e,t,r,n,i,o,s,a,c,l,u){try{if(this.assertInitialized(),!(null!=this.aiCallConfig||i&&o&&s&&a))throw new Error("AI调用配置未设置");let d="";if(c?d=JSON.stringify(c):this.aiCallConfig?.headers&&(d=JSON.stringify(this.aiCallConfig.headers)),s||(s=this.aiCallConfig?.theme),!s)throw new Error("配置主题不能为空");if(i||(i=this.aiCallConfig?.appId),!i)throw new Error("应用ID不能为空");if(o||(o=this.aiCallConfig?.themeAuthor),!o)throw new Error("主题作者公钥不能为空");if(a||(a=this.aiCallConfig?.service),!a)throw new Error("服务名称不能为空");return[await this.aiProxyManager.DoAIProxyCall(e,i,o,s,a,t,r,n,d,l||this.aiCallConfig?.path,u||this.aiCallConfig?.model),null]}catch(e){return logger$2.error("AI代理调用失败:",e),[null,e instanceof Error?e:new Error(String(e))]}}async SetAICallConfig(e){try{return this.assertInitialized(),this.aiCallConfig=e,null}catch(e){return logger$2.error("设置AI调用配置失败:",e),e}}assertInitialized(){if(!this.initialized)throw new Error("键值存储模块未初始化")}}class UtilClient{constructor(e){Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.client=e}async setAppInfo(e,t,r,n,i,o,s,a){if(null==this.client.p2pNode)throw new Error("p2pNode is null");try{const c=new grpcLibp2pClient.Libp2pGrpcClient(this.client.p2pNode,this.client.peerAddr,this.client.token,this.client.protocol),l=new dcnet.pb.SetAppInfoRequest;l.appId=e,l.ownerAccount=t,l.rewardAccount=r,l.domain=n,l.blockheight=i,l.peerid=(new TextEncoder).encode(o),l.fid=(new TextEncoder).encode(s),l.signature=a;const u=dcnet.pb.SetAppInfoRequest.encode(l).finish();try{return void await c.unaryCall("/dcnet.pb.Service/SetAppInfo",u,3e4)}catch(e){throw e}}catch(e){throw e}}}class UtilManager{constructor(e){Object.defineProperty(this,"dc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chainUtil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.connectedDc=e.connectedDc,this.dc=e.dcutil,this.chainUtil=e.dcChain,this.context=e}async setAppInfo(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"";if(!this.context.publicKey||!this.context.ethAddress)throw Errors$a.NO_USER_INFO;if(!this.connectedDc.client)throw Errors$a.NO_DC_PEER_CONNECTED;if(!this.connectedDc.nodeAddr)throw Errors$a.NO_DC_PEER_CONNECTED;const o=await(this.chainUtil?.getBlockHeight());if(void 0===o)throw Errors$a.FAIL_TO_GET_BLOCKHEIGHT;let s=this.context.publicKey.bytes();r&&r.length>10&&(s=Ed25519PubKey.unmarshalString(r).bytes());let a=hexToBytes(this.context.ethAddress.slice(2));if(n&&n.length>10&&(a=hexToBytes(n.slice(2))),""==this.connectedDc.client.token){if(!await this.connectedDc.client.GetToken(this.context.appInfo.appId||"",this.context.publicKey.string(),(async e=>this.context.sign(e))))throw Errors$a.FAIL_TO_GET_TOKEN}const c=new UtilClient(this.connectedDc.client),l=this.connectedDc.nodeAddr.getPeerId()||"",u=(new TextEncoder).encode(l),d=(new TextEncoder).encode(e),h=(new TextEncoder).encode(t),p=uint32ToLittleEndianBytes(o),f=new Uint8Array(d.length+h.length+s.length+a.length+p.length+u.length+i.length);let y=0;f.set(d,y),y+=d.length,f.set(s,y),y+=s.length,f.set(a,y),y+=a.length,f.set(h,y),y+=h.length,f.set(p,y),y+=p.length,f.set(u,y),y+=u.length,f.set((new TextEncoder).encode(i),y);const g=await this.context.sign(f);await c.setAppInfo(d,s,a,h,o,l,i,g)}async getAppInfo(e){if(!this.connectedDc.client)throw Errors$a.NO_DC_PEER_CONNECTED;if(!this.chainUtil)throw Errors$a.NO_CHAIN_UTIL;return await this.chainUtil.getAPPInfo(e)}}const logger$1=createLogger("UtilModule");class UtilModule{constructor(){Object.defineProperty(this,"moduleName",{enumerable:!0,configurable:!0,writable:!0,value:exports.CoreModuleName.UTIL}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"utilManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async initialize(e){try{return this.context=e,this.utilManager=new UtilManager(e),this.initialized=!0,!0}catch(e){return logger$1.error("工具模块初始化失败:",e),!1}}createSymmetricKey(){return SymmetricKey.new()}createThreadKey(){return new Key(SymmetricKey.new(),SymmetricKey.new())}async setAppInfo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;if(!this.initialized)return[null,new Error("UtilModule not initialized")];try{if(!e)throw new Error("appId are required");if(!this.context.publicKey||!this.context.ethAddress)throw Errors$a.NO_USER_INFO;(!n||n.length<10)&&(n=this.context.publicKey.string()),(!i||i.length<10)&&(i=this.context.ethAddress);const[o,s]=await this.getAppInfo(e);return o&&!s&&o.owner==n&&o.rewarder==i&&o.domain==r&&o.fid==t||await this.utilManager.setAppInfo(e,r,n,i,t),[!0,null]}catch(e){return[null,e]}}async getAppInfo(e){if(!this.initialized)return[null,new Error("UtilModule not initialized")];try{return[await this.utilManager.getAppInfo(e),null]}catch(e){return[null,e]}}async shutdown(){this.initialized=!1}async handleIpfsRequest(e,t,r){if(this.initialized)try{await handleIpfsRequest(e,t,r)}catch(e){logger$1.error("页面处理IPFS请求失败:",e)}}}const logger=createLogger("DC");class DC{constructor(e){Object.defineProperty(this,"blockChainAddr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"backChainAddr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcNodeClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dcutil",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"publicKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dbThreadId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"ethAddress",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"connectedDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"AccountBackupDc",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"Identity",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"Blockheight",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"grpcServer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"appInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldReturnUserInfo",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"accountInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userInfo",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"dbManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"swUrl",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"swInited",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"moduleSystem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"init",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(this.initialized)return logger.warn("DC已经初始化,跳过重复初始化"),!0;e&&await e(0);let t=!1;try{if(logger.info("尝试连接主链: "+this.blockChainAddr),t=await this.dcChain.create(this.blockChainAddr),!t&&(logger.info("主链连接失败,尝试备用链: "+this.backChainAddr),t=await this.dcChain.create(this.backChainAddr),!t))return logger.error("dcchainapi 初始化失败: 无法连接任何链"),!1;e&&await e(1),logger.info("链节点连接成功"),this.dcNodeClient=await(this.dcutil?._createHeliaNode()),logger.info("Helia节点创建成功"),this.grpcServer=new DCGrpcServer(this.dcNodeClient.libp2p,dc_protocol),this.grpcServer.start(),logger.info("GRPC服务器启动成功");let r=await(this.dcutil?.getDefaultDcNodeAddr());if(!r)return logger.error("获取DC节点地址失败"),!1;logger.info("获取DC节点地址成功: "+r.toString());try{await(this.dcNodeClient?.libp2p.dial(r,{signal:AbortSignal.timeout(5e3)}));logger.info("连接到DC节点成功"),this.connectedDc.nodeAddr=r,this.connectedDc.client=await this.newDcClient(r),e&&await e(2);return await this.moduleSystem.initializeAll()?(this.initialized=!0,e&&await e(3),this.auth&&this.auth.startDcPeerTokenKeepValidTask(),e&&await e(4),!0):(logger.error("模块初始化失败"),!1)}catch(e){return logger.error("连接到DC节点失败:",e),!1}}catch(e){return logger.error("DC初始化失败:",e),!1}}}),Object.defineProperty(this,"sign",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(!this.auth)return new Uint8Array;return this.auth.signWithWallet(e)}}),Object.defineProperty(this,"newDcClient",{enumerable:!0,configurable:!0,writable:!0,value:async e=>{if(e)try{return new Client(this.dcNodeClient.libp2p,this.dcNodeClient.blockstore,e,dc_protocol)}catch(e){throw logger.error("创建DC客户端失败:",e),e}}}),this.blockChainAddr=e.wssUrl,this.backChainAddr=e.backWssUrl,this.swUrl=e.swUrl||"",this.dcChain=new ChainUtil,this.dcutil=new DcUtil(this.dcChain),this.appInfo=e.appInfo||{},this.accountInfo={},void 0!==e.logLevel&&configureLogger({level:e.logLevel}),this.moduleSystem=new ModuleSystem(this),this.registerCoreModules(e.names||[])}registerCoreModules(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(e&&e.length>0)for(const t of e){const e=this.moduleSystem.getModule(t);e?this.moduleSystem.registerModule(e):logger.warn(`模块 ${t} 不存在,跳过注册`)}else this.moduleSystem.registerModule(new FileModule(this.swUrl||"")),this.moduleSystem.registerModule(new AuthModule),this.moduleSystem.registerModule(new CommentModule),this.moduleSystem.registerModule(new DatabaseModule),this.moduleSystem.registerModule(new MessageModule),this.moduleSystem.registerModule(new KeyValueModule),this.moduleSystem.registerModule(new ClientModule),this.moduleSystem.registerModule(new CacheModule),this.moduleSystem.registerModule(new AIProxyModule),this.moduleSystem.registerModule(new UtilModule);logger.info("核心模块注册完成")}registerModule(e){return this.moduleSystem.registerModule(e)}setAppInfo(e){this.appInfo=e}setAccountInfo(e){this.accountInfo=e}setShouldReturnUserInfo(e){this.shouldReturnUserInfo=e}async initUserDB(e,t,r){const n="user_threaddb";let i=null;try{if(this.assertInitialized(),!this.auth)return[null,new Error("用户模块不存在")];const[o,s]=await this.auth.refreshUserInfo();if(s)return[null,s];if(!o)return[null,new Error("用户信息不存在")];if(i=o,!r&&i&&i.dbConfig)try{const[r,o]=await this.auth.decryptWithWallet(i.dbConfigRaw);if(o||!r)return[null,o];const s=(new TextDecoder).decode(r),a=s?s.split("|"):[];if(a&&a.length>=3){const r=a[0]||"",i=a[1]||"",o=a[2]||"";a[3],a[4];if(!this.db)return[null,new Error("数据库模块不存在")];const[s,c]=await this.db.getDBInfo(r);if(null!=s&&!c){if(t){if(await this.db.loadVerno(r)!=t){const n=await this.db.upgradeCollections(r,e);if(n)return[null,n];await this.db.saveVerno(r,t)}await this.db.upgradeCollections(r,e)}return this.db.refreshDBFromDC(r),setTimeout((()=>{this.db&&this.db.syncDBToDC(r)}),5e3),this.dbThreadId=s.id,[s,null]}if(""!=r){await this.db.syncDbFromDC(r,n,"",i,o,!0,e);const[t,s]=await this.db.getDBInfo(r);return null==t||s?[null,s||new Error("获取DB失败")]:(this.dbThreadId=t.id,[t,null])}}}catch(e){return[null,e]}if(!this.util)return[null,new Error("util模块不存在")];if(!this.db)return[null,new Error("数据库模块不存在")];const a=this.util.createSymmetricKey(),c=this.util.createSymmetricKey(),[l,u]=await this.db.newDB(n,a.toString(),c.toString(),e);if(u||!l)return[null,u];if(l){if(!await this.setUserDefaultDB(this,l,a.toString(),c.toString()))return[null,new Error("设置用户去中心DB失败")]}if(!this.db)return[null,new Error("数据库模块不存在")];const[d,h]=await this.db.getDBInfo(l);return null==d||h?(this.dbThreadId="",[null,h]):(this.dbThreadId=d.id,[d,null])}catch(e){return[null,e]}}async setUserDefaultDB(e,t,r,n,i){try{if(!e.auth)return!1;await e.auth.setUserDefaultDB(t,r,n,i||"")}catch(e){return!1}return await this.checkSetUserDefaultDB(e)}async checkSetUserDefaultDB(e){return new Promise((async t=>{let r=0,n=setInterval((async()=>{if(r++,r>20&&(n&&clearInterval(n),r=0,t(!1)),e.auth){const[i,o]=await e.auth.refreshUserInfo();!o&&i&&i.dbConfig&&(n&&clearInterval(n),r=0,t(!0))}}),1e3)}))}async shutdown(){logger.info("开始关闭DC..."),await this.moduleSystem.shutdownAll(),this.grpcServer&&(this.grpcServer.stop(),logger.info("GRPC服务器已停止")),this.dcNodeClient&&this.dcNodeClient.libp2p&&(await this.dcNodeClient.libp2p.stop(),logger.info("libp2p连接已关闭")),this.initialized=!1,logger.info("DC已成功关闭")}async exit(){this.AccountBackupDc={},this.publicKey=void 0,this.dbThreadId="",this.ethAddress="",this.auth&&this.auth.exitLogin(),logger.info("DC已退出并清理资源")}setPublicKey(e){this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new Error("公钥未初始化");return this.publicKey}getPubkeyRaw(){if(!this.publicKey)throw new Error("公钥未初始化");return this.publicKey.raw}isInitialized(){return this.initialized}getRegisteredModules(){return this.moduleSystem.getRegisteredModules()}getModule(e){try{this.assertInitialized();const t=this.moduleSystem.getModule(e);if(!t)throw new Error(`模块 ${e} 不存在或未注册`);return t}catch(e){return null}}assertInitialized(){if(!this.initialized)throw new Error("DC未初始化,请先调用init()方法")}get file(){return this.getModule(exports.CoreModuleName.FILE)}get auth(){return this.getModule(exports.CoreModuleName.AUTH)}get comment(){return this.getModule(exports.CoreModuleName.COMMENT)}get db(){return this.getModule(exports.CoreModuleName.DATABASE)}get message(){return this.getModule(exports.CoreModuleName.MESSAGE)}get keyValue(){return this.getModule(exports.CoreModuleName.KEYVALUE)}get client(){return this.getModule(exports.CoreModuleName.CLIENT)}get cache(){return this.getModule(exports.CoreModuleName.CACHE)}get aiproxy(){return this.getModule(exports.CoreModuleName.AIPROXY)}get util(){return this.getModule(exports.CoreModuleName.UTIL)}}"undefined"==typeof Promise||Promise.withResolvers||(Promise.withResolvers=function(){let e,t;return{promise:new Promise(((r,n)=>{e=r,t=n})),resolve:e,reject:t}}),exports.AIProxyModule=AIProxyModule,exports.AuthModule=AuthModule,exports.CacheModule=CacheModule,exports.ClientModule=ClientModule,exports.CommentModule=CommentModule,exports.DC=DC,exports.DatabaseModule=DatabaseModule,exports.Ed25519PrivKey=Ed25519PrivKey,exports.Ed25519PubKey=Ed25519PubKey,exports.Errors=Errors$a,exports.FileModule=FileModule,exports.KeyManager=KeyManager,exports.KeyValueModule=KeyValueModule,exports.MessageModule=MessageModule,exports.ModuleSystem=ModuleSystem,exports.OffChainOpTimes=OffChainOpTimes,exports.OffChainOpTimesLimit=OffChainOpTimesLimit,exports.OffChainSpaceLimit=OffChainSpaceLimit,exports.UtilModule=UtilModule,exports.configureLogger=configureLogger,exports.createLogger=createLogger,exports.dc_protocol=dc_protocol,exports.dial_timeout=dial_timeout,exports.isServiceWorkerActive=isServiceWorkerActive,exports.keyExpire=keyExpire,exports.registerServiceWorker=registerServiceWorker,exports.updateServiceWorker=updateServiceWorker,exports.walletOrigin=walletOrigin,exports.walletUrl=walletUrl,exports.walletWindowName=walletWindowName}));