@xyo-network/module-abstract 2.107.3 → 2.107.5

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.
@@ -1,2 +1,1042 @@
1
- var k=Object.defineProperty;var ee=(o,e,t)=>e in o?k(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var u=(o,e)=>k(o,"name",{value:e,configurable:!0});var h=(o,e,t)=>ee(o,typeof e!="symbol"?e+"":e,t);import{assertEx as f}from"@xylabs/assert";import{handleError as ce,handleErrorAsync as le}from"@xylabs/error";import{exists as j}from"@xylabs/exists";import{forget as he}from"@xylabs/forget";import{compact as F}from"@xylabs/lodash";import{ConsoleLogger as W,IdLogger as me,LogLevel as fe}from"@xylabs/logger";import{Base as we,globallyUnique as ye}from"@xylabs/object";import{PromiseEx as U}from"@xylabs/promise";import{Account as ge}from"@xyo-network/account";import{asArchivistInstance as pe}from"@xyo-network/archivist-model";import{BoundWitnessBuilder as V,QueryBoundWitnessBuilder as ve}from"@xyo-network/boundwitness-builder";import{QueryBoundWitnessWrapper as z}from"@xyo-network/boundwitness-wrapper";import{ConfigSchema as be}from"@xyo-network/config-payload-plugin";import{AddressPreviousHashSchema as _e,AddressSchema as p,DeadModuleError as Re,isModuleName as Ae,ModuleAddressQuerySchema as J,ModuleConfigSchema as K,ModuleDescriptionSchema as Qe,ModuleFactory as Se,ModuleManifestQuerySchema as G,ModuleStateQuerySchema as X,ModuleSubscribeQuerySchema as Y,ObjectResolverPriority as Pe,serializableField as xe}from"@xyo-network/module-model";import{PayloadBuilder as w}from"@xyo-network/payload-builder";import{QuerySchema as He}from"@xyo-network/query-payload-plugin";import{LRUCache as Ce}from"lru-cache";import{Base as te}from"@xylabs/object";import{Events as se}from"@xyo-network/module-events";var P=class P extends te{eventData={};events;constructor(e){super(e),this.events=new se}clearListeners(e){return this.events.clearListeners(e)}emit(e,t){return this.events.emit(e,t)}emitSerial(e,t){return this.events.emitSerial(e,t)}listenerCount(e){return this.events.listenerCount(e)}off(e,t){return this.events.off(e,t)}offAny(e){return this.events.offAny(e)}on(e,t){return this.events.on(e,t)}onAny(e){return this.events.onAny(e)}once(e,t){return this.events.once(e,t)}};u(P,"BaseEmitter");var A=P;import{assertEx as x}from"@xylabs/assert";import{Account as T}from"@xyo-network/account";var re=u(o=>(x(!o.accountPath,()=>"accountPath may not be provided when account is provided"),!!o.account),"isDetermineAccountFromAccountParams"),ie=u(o=>!!o.wallet,"isDetermineAccountFromWalletParams");async function O(o,e=!0){return re(o)?o.account==="random"?(x(e,()=>"Random address not allowed"),T.randomSync()):o.account:ie(o)?x(o.accountPath?await o.wallet.derivePath(o.accountPath):o.wallet,()=>"Failed to derive account from path"):(console.warn("AbstractModule.determineAccount: No account or wallet provided - Creating Random account"),T.randomSync())}u(O,"determineAccount");import{PayloadBuilder as ae}from"@xyo-network/payload-builder";import{ModuleErrorSchema as B}from"@xyo-network/payload-model";var H=class H extends ae{_details;_message;_name;_query;_sources;constructor(){super({schema:B})}build(){return this.fields({details:this._details,message:this._message,name:this._name,query:this._query,schema:B,sources:this._sources}),super.build()}details(e){return this._details=e,this}message(e){return this._message=e,this}name(e){return this._name=e,this}query(e){return this._query=e,this}sources(e){return this._sources=e,this}};u(H,"ModuleErrorBuilder");var Q=H;import{QueryBoundWitnessWrapper as ne}from"@xyo-network/boundwitness-wrapper";var oe="",q=class q{allowed={};disallowed={};hasAllowedRules;hasDisallowedRules;hasRules;constructor(e){var t,s,r,i;if((t=e==null?void 0:e.security)!=null&&t.allowed)for(let[a,n]of Object.entries((s=e.security)==null?void 0:s.allowed))this.allowed[a]=n.map(C);if((r=e==null?void 0:e.security)!=null&&r.disallowed)for(let[a,n]of Object.entries((i=e.security)==null?void 0:i.disallowed))this.disallowed[a]=n.map(C);this.hasAllowedRules=Object.keys(this.allowed).length>0,this.hasDisallowedRules=Object.keys(this.disallowed).length>0,this.hasRules=this.hasAllowedRules||this.hasDisallowedRules}queryable=u(async(e,t)=>{if(!this.hasRules)return!0;let s=e.addresses;if(s.length===0)return!1;let i=(await(await ne.parseQuery(e,t)).getQuery()).schema;return this.queryAllowed(i,s)&&!this.queryDisallowed(i,s)},"queryable");queryAllowed=u((e,t)=>{var s,r;if(!this.hasAllowedRules)return!0;if(t.length>1){let i=C(t);if((r=(s=this.allowed)==null?void 0:s[e])==null?void 0:r.includes(i))return!0}return t.every(i=>{var a,n;return((n=(a=this.allowed)==null?void 0:a[e])==null?void 0:n.includes(i))||!1})},"queryAllowed");queryDisallowed=u((e,t)=>this.hasDisallowedRules?t.some(s=>{var r,i;return(i=(r=this.disallowed)==null?void 0:r[e])==null?void 0:i.includes(s)}):!1,"queryDisallowed")};u(q,"ModuleConfigQueryValidator");var g=q,C=u(o=>Array.isArray(o)?o.sort().map(e=>e.toLowerCase()).join(oe):o.toLowerCase(),"toAddressesString");import{QueryBoundWitnessWrapper as ue}from"@xyo-network/boundwitness-wrapper";var de=u(async(o,e,t)=>{let r=(await(await ue.parseQuery(e,t)).getQuery()).schema;return o.queries.includes(r)},"isQuerySupportedByModule"),$=class ${mod;constructor(e){this.mod=e,this.queryable=(t,s)=>de(this.mod,t,s)}queryable};u($,"SupportedQueryValidator");var S=$;var c=class c extends A{_account=void 0;_cachedManifests=new Ce({max:10,ttl:1e3*60*5});_lastError;_startPromise=void 0;_started=void 0;moduleConfigQueryValidator;supportedQueryValidator;_busyCount=0;_logger=void 0;_status="stopped";constructor(e,t,s){f(c.privateConstructorKey===e,()=>"Use create function instead of constructor");let r={...t};super(r),this._account=s,this.supportedQueryValidator=new S(this).queryable,this.moduleConfigQueryValidator=new g(r==null?void 0:r.config).queryable}get account(){return f(this._account,()=>"Missing account")}get additionalSigners(){return this.params.additionalSigners??[]}get address(){return this.account.address}get allowAnonymous(){var e;return!!((e=this.config.security)!=null&&e.allowAnonymous)}get allowNameResolution(){return this.params.allowNameResolution??!0}get archiving(){return this.config.archiving}get archivist(){return this.config.archivist}get config(){return this.params.config}get dead(){return this.status==="dead"}get ephemeralQueryAccountEnabled(){return!!this.params.ephemeralQueryAccountEnabled}get id(){return this.modName??this.address}get logger(){var t;let e=this.config.consoleLogger;return this._logger=this._logger??e?new W(e):((t=this.params)==null?void 0:t.logger)??c.defaultLogger??we.defaultLogger,this._logger}get modName(){return this.config.name}get priority(){return Pe.Normal}get queries(){return[J,Y,G,X]}get status(){return this._status}get timestamp(){return this.config.timestamp??!1}set status(e){this._status!=="dead"&&(this._status=e)}static _getRootFunction(e){let t=this;for(;t.__proto__[e];)t=t.__proto__;return t[e]}static _noOverride(e){let t=this[e],s=this._getRootFunction(e);f(t===s,()=>`Override not allowed for [${e}] - override ${e}Handler instead`)}static async create(e){var R,y,E,D,I,L;if(this._noOverride("create"),!this.configSchemas||this.configSchemas.length===0)throw new Error(`Missing configSchema [${(R=e==null?void 0:e.config)==null?void 0:R.schema}][${this.name}]`);if(!this.defaultConfigSchema)throw new Error(`Missing defaultConfigSchema [${(y=e==null?void 0:e.config)==null?void 0:y.schema}][${this.name}]`);f(((E=e==null?void 0:e.config)==null?void 0:E.name)===void 0||Ae(e.config.name),()=>{var M;return`Invalid module name: ${(M=e==null?void 0:e.config)==null?void 0:M.name}`});let{account:t}=e??{},s=((D=e==null?void 0:e.config)==null?void 0:D.schema)??this.defaultConfigSchema,r=this.configSchemas;f(r.includes(s),()=>`Bad Config Schema [Received ${s}] [Expected ${JSON.stringify(r)}]`);let i={...e==null?void 0:e.config,schema:s};(I=e==null?void 0:e.logger)==null||I.debug(`config: ${JSON.stringify(i,null,2)}`);let a={...e,config:i},n=(e==null?void 0:e.logger)??c.defaultLogger,d=await c.determineAccount({account:t}),l=d.address;a.logger=n?new me(n,()=>`0x${l}`):void 0;let m=new this(c.privateConstructorKey,a,d);return c.enableLazyLoad||await((L=m.start)==null?void 0:L.call(m)),m}static async determineAccount(e){return await O(e,this.allowRandomAccount)}static factory(e){return Se.withParams(this,e)}_getRootFunction(e){let t=this;for(;t.__proto__[e];)t=t.__proto__;return t[e]}async busy(e){if(this._busyCount<=0){this._busyCount=0;let t={busy:!0,module:this};await this.emit("moduleBusy",t)}this._busyCount++;try{return await e()}finally{if(this._busyCount--,this._busyCount<=0){this._busyCount=0;let t={busy:!1,module:this};await this.emit("moduleBusy",t)}}}emit(e,t){return super.emit(e,t)}previousHash(){return this._checkDead(),this.account.previousHash}async query(e,t,s){this._checkDead(),this._noOverride("query");let r=await w.build(f(z.unwrap(e),()=>"Invalid query"));return await this.busy(async()=>{let i=[],a=[],n=this.ephemeralQueryAccountEnabled?ge.randomSync():void 0;try{if(await this.started("throw"),!this.allowAnonymous&&e.addresses.length===0)throw new Error(`Anonymous Queries not allowed, but running anyway [${this.modName}], [${this.address}]`);s!=null&&s.allowedQueries&&f(s==null?void 0:s.allowedQueries.includes(r.schema),()=>`Query not allowed [${r.schema}]`),i.push(...await this.queryHandler(r,t,s))}catch(m){await le(m,async R=>{let y=R;this._lastError=y,a.push(await new Q().sources([r.$hash]).name(this.modName??"<Unknown>").query(r.schema).details(y.details).message(y.message).build())})}if(this.timestamp){let m={schema:"network.xyo.timestamp",timestamp:Date.now()};i.push(m)}let d=await this.bindQueryResult(r,i,n?[n]:[],a),l={module:this,payloads:t,query:r,result:d};return await this.emit("moduleQueried",l),d})}async queryable(e,t,s){if(this.dead||!await this.started("warn"))return!1;let r=s?new g(Object.assign({},this.config,s)).queryable:this.moduleConfigQueryValidator;return[this.supportedQueryValidator,r].every(a=>a(e,t))}start(e){this._startPromise=this._startPromise??this.startHandler();let t=this._startPromise;return this.status=t?"started":"dead",t}async started(e="log",t=!0){let s=await this._started;if(s===!0)return!0;if(s||(this._started=(async()=>{var r,i,a;if(t)try{return await this.start(),!0}catch(n){ce(n,d=>{var l;(l=this.logger)==null||l.warn(`Autostart of Module Failed: ${d.message})`),this._started=void 0})}switch(e){case"throw":throw new Error(`Module not Started [${this.address}]`);case"warn":{(r=this.logger)==null||r.warn("Module not started");break}case"error":{(i=this.logger)==null||i.error("Module not started");break}case"none":break;default:{(a=this.logger)==null||a.log("Module not started");break}}return!1})()),!this._started)throw"Failed to create start promise";return await this._started}async stop(e){return await this.busy(async()=>{let t=await this.stopHandler();return this._started=void 0,this._startPromise=void 0,this.status=t?"stopped":"dead",t})}_checkDead(){if(this.dead)throw new Re(this.id,this._lastError)}_noOverride(e){let t=this[e],s=this._getRootFunction(e);f(t===s,()=>`Override not allowed for [${e}] - override ${e}Handler instead`)}async archivistInstance(e=!1){let t=this.archivist;if(!t){if(e)throw new Error("No archivist specified");return}let s=await this.upResolver.resolve(t)??await this.downResolver.resolve(t);return e&&f(s,()=>`Unable to resolve archivist [${t}]`),s?pe(s,()=>`Specified archivist is not an Archivist [${t}]`):void 0}bindHashes(e,t,s){return new U(i=>{let a=this.bindHashesInternal(e,t,s);return i==null||i(a),a},s)}async bindHashesInternal(e,t,s=this.account){var a;let i=(await new V().hashes(e,t).signer(s).build())[0];return(a=this.logger)==null||a.debug(`result: ${JSON.stringify(i,null,2)}`),i}bindQuery(e,t,s,r){return new U(async a=>{let n=await this.bindQueryInternal(e,t,s,r);return a==null||a(n),n},s)}async bindQueryInternal(e,t,s=this.account,r=[]){let i=[s,...r].filter(j),a=await new ve().payloads(t).signers(i).query(e),n=[];this.config.certify&&(n=await this.certifyParents(),await a.additional(n));let[d,l,m]=await a.build();return[d,[...l,...n],m]}async bindQueryResult(e,t,s=[],r){var d;let i=new V().payloads(t).errors(r).sourceQuery(e.$hash),a=[this.account,...s].filter(j);i.signers(a);let n=[(await i.build())[0],await Promise.all(t.map(l=>w.build(l))),await Promise.all((d=r??[])==null?void 0:d.map(l=>w.build(l)))];return this.archiving&&this.isAllowedArchivingQuery(e.schema)&&he(this.storeToArchivists(n.flat())),n}async generateConfigAndAddress(e){let t=await w.build(this.config),s=await new w({schema:p}).fields({address:this.address}).build(),r=await Promise.all(this.queries.map(async a=>await new w({schema:He}).fields({query:a}).build())),i=await w.build({config:t.schema,schema:be});return F([t,i,s,...r])}async generateDescribe(){var s;let e={address:this.address,queries:this.queries,schema:Qe};(s=this.config)!=null&&s.name&&(e.name=this.modName);let t=await this.generateConfigAndAddress();return e.children=F((t==null?void 0:t.map(r=>{let i=r.schema===p?r.address:void 0;return i==this.address?void 0:i}))??[]),e}async getArchivist(){return await this.archivistInstance()}isAllowedArchivingQuery(e){var s;let t=(s=this.archiving)==null?void 0:s.queries;return t?t.includes(e):!0}manifestHandler(e=1,t=[]){throw new Error("Not supported")}moduleAddressHandler(){let e=this.address,t=this.modName,s=this.address;return[t?{address:e,name:t,schema:p}:{address:e,schema:p},s?{address:e,previousHash:s,schema:_e}:{address:e,schema:p}]}async queryHandler(e,t,s){await this.started("throw");let i=await(await z.parseQuery(e,t)).getQuery();f(await this.queryable(e,t,s));let a=[];switch(i.schema){case G:{a.push(await this.manifestHandler(i.maxDepth));break}case J:{a.push(...await this.moduleAddressHandler());break}case X:{a.push(...await this.stateHandler());break}case Y:{this.subscribeHandler();break}default:throw new Error(`Unsupported Query [${i.schema}]`)}return a}async startHandler(){return this.validateConfig(),await Promise.resolve(),this._started=!0,!0}async stateHandler(){return[await this.manifestHandler(),...await this.generateConfigAndAddress(),await this.generateDescribe()]}stopHandler(e){return this._started=void 0,!0}subscribeHandler(){}validateConfig(e,t=[]){return Object.entries(e??this.config??{}).reduce((s,[r,i])=>{var a,n;switch(typeof i){case"function":return(a=this.logger)==null||a.warn(`Fields of type function not allowed in config [${t==null?void 0:t.join(".")}.${r}]`),!1;case"object":return Array.isArray(i)?i.reduce((d,l)=>this.validateConfig(l,[...t,r])&&d,!0)&&s:xe(i)?i?this.validateConfig(i,[...t,r])&&s:!0:((n=this.logger)==null||n.warn(`Fields that are not serializable to JSON are not allowed in config [${t==null?void 0:t.join(".")}.${r}]`),!1);default:return s}},!0)}};u(c,"AbstractModule"),h(c,"allowRandomAccount",!0),h(c,"configSchemas",[K]),h(c,"defaultConfigSchema",K),h(c,"defaultLogger",new W(fe.warn)),h(c,"enableLazyLoad",!1),h(c,"labels",{}),h(c,"uniqueName",ye("AbstractModule",c,"xyo")),h(c,"privateConstructorKey",Date.now().toString());var v=c;import{assertEx as qe}from"@xylabs/assert";import{compact as $e}from"@xylabs/lodash";import{globallyUnique as Ne}from"@xylabs/object";import{asArchivistInstance as Ee}from"@xyo-network/archivist-model";import{ModuleManifestPayloadSchema as De}from"@xyo-network/manifest-model";import{duplicateModules as Ie,ModuleManifestQuerySchema as Le,ModuleStateQuerySchema as Me,ResolveHelper as b}from"@xyo-network/module-model";import{CompositeModuleResolver as N}from"@xyo-network/module-resolver";import{asNodeInstance as ke}from"@xyo-network/node-model";var _=class _ extends v{_downResolver;_parents=[];_privateResolver;_upResolver;constructor(e,t,s){qe(v.privateConstructorKey===e,()=>"Use create function instead of constructor");let r={...t},i=r.addToResolvers??!0;super(e,r,s),i&&(this.upResolver.add(this),this.downResolver.add(this))}get downResolver(){return this._downResolver=this._downResolver??new N({allowNameResolution:this.allowNameResolution,moduleIdentifierTransformers:this.params.moduleIdentifierTransformers,root:this}),this._downResolver}get modName(){return super.modName}get moduleIdentifierTransformers(){return this.params.moduleIdentifierTransformers??b.transformers}get privateResolver(){return this._privateResolver=this._privateResolver??new N({allowNameResolution:this.allowNameResolution,moduleIdentifierTransformers:this.params.moduleIdentifierTransformers,root:this}),this._privateResolver}get root(){return this}get upResolver(){return this._upResolver=this._upResolver??new N({allowNameResolution:this.allowNameResolution,moduleIdentifierTransformers:this.params.moduleIdentifierTransformers,root:this}),this._upResolver}addParent(e){this._parents.find(s=>s.address===e.address)||this._parents.push(ke(e,"Only NodeInstances can be parents"))}async certifyParents(){let e=await this.parents();return(await Promise.all(e.map(async t=>{let[s,r,i]=await t.certifyQuery(this.address);return i.length===0?[s,...r]:[]}))).flat()}manifest(e){return this._checkDead(),this.busy(async()=>await this.manifestHandler(e))}async manifestQuery(e,t){let s={schema:Le,...t===void 0?{}:{maxDepth:t}};return await this.sendQueryRaw(s,void 0,e)}moduleAddress(){return this._checkDead(),this.busy(async()=>await this.moduleAddressHandler())}parents(){return this._parents}privateChildren(){return[]}publicChildren(){return[]}removeParent(e){this._parents=this._parents.filter(t=>t.address!==e)}async resolve(e="*",t={}){let s={address:this.address,dead:this.dead,downResolver:this.downResolver,logger:this.logger,module:this,transformers:this.moduleIdentifierTransformers,upResolver:this.upResolver};if(e==="*")return(await b.resolve(s,e,t)).filter(r=>r.address!==this.address);switch(typeof e){case"string":return await b.resolve(s,e,t);case"object":return(await b.resolve(s,e,t)).filter(r=>r.address!==this.address);default:return(await b.resolve(s,e,t)).filter(r=>r.address!==this.address)}}resolveIdentifier(e,t){let{direction:s="all"}=t??{};switch(s){case"down":return this.downResolver.resolveIdentifier(e,t);default:{let r={...t,direction:"all"};return this.upResolver.resolveIdentifier(e,r)}}}async resolvePrivate(e="*",t={}){return await this.privateResolver.resolve(e,t)??await this.upResolver.resolve(e,t)??await this.downResolver.resolve(e,t)}async siblings(){return(await Promise.all((await this.parents()).map(e=>e.publicChildren()))).flat().filter(Ie)}state(){return this._checkDead(),this.busy(async()=>await this.stateHandler())}async stateQuery(e){let t={schema:Me};return await this.sendQueryRaw(t,void 0,e)}subscribe(e){return this._checkDead(),this.subscribeHandler()}async manifestHandler(e=1,t=[]){let s=this._cachedManifests.get(e);if(s)return s;let r=this.modName??"<Anonymous>",i=await this.publicChildren(),a={};for(let d of i)d.address!==this.address&&(a[d.address]=d.modName??null);let n={config:{name:r,...this.config},schema:De,status:{address:this.address,children:a}};return this._cachedManifests.set(e,n),n}async resolveArchivingArchivists(){var s;let e=(s=this.archiving)==null?void 0:s.archivists;if(!e)return[];let t=await Promise.all(e.map(r=>this.resolve(r)));return $e(t.map(r=>Ee(r)))}async sendQuery(e,t,s){let r=await this.sendQueryRaw(e,t,s),[,i,a]=r;if(a&&a.length>0)throw a[0];return i}async sendQueryRaw(e,t,s){let r=await this.bindQuery(e,t,s,this.additionalSigners);return await this.query(r[0],r[1])}async storeToArchivists(e){try{let t=await this.resolveArchivingArchivists();return(await Promise.all(t.map(s=>{var r;return(r=s.insert)==null?void 0:r.call(s,e)}))).map(([s])=>s)}catch(t){let s=t;return this.logger.error(`Error storing to archivists: ${s.message}`),[]}}};u(_,"AbstractModuleInstance"),h(_,"uniqueName",Ne("AbstractModuleInstance",_,"xyo"));var Z=_;export{v as AbstractModule,Z as AbstractModuleInstance,A as BaseEmitter,g as ModuleConfigQueryValidator,Q as ModuleErrorBuilder,S as SupportedQueryValidator,de as isQuerySupportedByModule};
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+
6
+ // src/AbstractModule.ts
7
+ import { assertEx as assertEx2 } from "@xylabs/assert";
8
+ import { handleError, handleErrorAsync } from "@xylabs/error";
9
+ import { exists } from "@xylabs/exists";
10
+ import { forget } from "@xylabs/forget";
11
+ import { compact } from "@xylabs/lodash";
12
+ import { ConsoleLogger, IdLogger, LogLevel } from "@xylabs/logger";
13
+ import { Base as Base2, globallyUnique } from "@xylabs/object";
14
+ import { PromiseEx } from "@xylabs/promise";
15
+ import { Account as Account2 } from "@xyo-network/account";
16
+ import { asArchivistInstance } from "@xyo-network/archivist-model";
17
+ import { BoundWitnessBuilder, QueryBoundWitnessBuilder } from "@xyo-network/boundwitness-builder";
18
+ import { QueryBoundWitnessWrapper as QueryBoundWitnessWrapper3 } from "@xyo-network/boundwitness-wrapper";
19
+ import { ConfigSchema } from "@xyo-network/config-payload-plugin";
20
+ import { AddressPreviousHashSchema, AddressSchema, DeadModuleError, isModuleName, ModuleAddressQuerySchema, ModuleConfigSchema, ModuleDescriptionSchema, ModuleFactory, ModuleManifestQuerySchema, ModuleStateQuerySchema, ModuleSubscribeQuerySchema, ObjectResolverPriority, serializableField } from "@xyo-network/module-model";
21
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
22
+ import { QuerySchema } from "@xyo-network/query-payload-plugin";
23
+ import { LRUCache } from "lru-cache";
24
+
25
+ // src/BaseEmitter.ts
26
+ import { Base } from "@xylabs/object";
27
+ import { Events } from "@xyo-network/module-events";
28
+ var _BaseEmitter = class _BaseEmitter extends Base {
29
+ //just here to query types
30
+ eventData = {};
31
+ events;
32
+ constructor(params) {
33
+ super(params);
34
+ this.events = new Events();
35
+ }
36
+ clearListeners(eventNames) {
37
+ return this.events.clearListeners(eventNames);
38
+ }
39
+ emit(eventName, eventArgs) {
40
+ return this.events.emit(eventName, eventArgs);
41
+ }
42
+ emitSerial(eventName, eventArgs) {
43
+ return this.events.emitSerial(eventName, eventArgs);
44
+ }
45
+ listenerCount(eventNames) {
46
+ return this.events.listenerCount(eventNames);
47
+ }
48
+ off(eventNames, listener) {
49
+ return this.events.off(eventNames, listener);
50
+ }
51
+ offAny(listener) {
52
+ return this.events.offAny(listener);
53
+ }
54
+ on(eventNames, listener) {
55
+ return this.events.on(eventNames, listener);
56
+ }
57
+ onAny(listener) {
58
+ return this.events.onAny(listener);
59
+ }
60
+ once(eventName, listener) {
61
+ return this.events.once(eventName, listener);
62
+ }
63
+ };
64
+ __name(_BaseEmitter, "BaseEmitter");
65
+ var BaseEmitter = _BaseEmitter;
66
+
67
+ // src/determineAccount.ts
68
+ import { assertEx } from "@xylabs/assert";
69
+ import { Account } from "@xyo-network/account";
70
+ var isDetermineAccountFromAccountParams = /* @__PURE__ */ __name((params) => {
71
+ assertEx(!params.accountPath, () => "accountPath may not be provided when account is provided");
72
+ return !!params.account;
73
+ }, "isDetermineAccountFromAccountParams");
74
+ var isDetermineAccountFromWalletParams = /* @__PURE__ */ __name((params) => {
75
+ return !!params.wallet;
76
+ }, "isDetermineAccountFromWalletParams");
77
+ async function determineAccount(params, allowRandomAccount = true) {
78
+ if (isDetermineAccountFromAccountParams(params)) {
79
+ if (params.account === "random") {
80
+ assertEx(allowRandomAccount, () => "Random address not allowed");
81
+ return Account.randomSync();
82
+ }
83
+ return params.account;
84
+ }
85
+ if (isDetermineAccountFromWalletParams(params)) {
86
+ return assertEx(params.accountPath ? await params.wallet.derivePath(params.accountPath) : params.wallet, () => "Failed to derive account from path");
87
+ }
88
+ console.warn("AbstractModule.determineAccount: No account or wallet provided - Creating Random account");
89
+ return Account.randomSync();
90
+ }
91
+ __name(determineAccount, "determineAccount");
92
+
93
+ // src/Error.ts
94
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
95
+ import { ModuleErrorSchema } from "@xyo-network/payload-model";
96
+ var _ModuleErrorBuilder = class _ModuleErrorBuilder extends PayloadBuilder {
97
+ _details;
98
+ _message;
99
+ _name;
100
+ _query;
101
+ _sources;
102
+ constructor() {
103
+ super({
104
+ schema: ModuleErrorSchema
105
+ });
106
+ }
107
+ build() {
108
+ this.fields({
109
+ details: this._details,
110
+ message: this._message,
111
+ name: this._name,
112
+ query: this._query,
113
+ schema: ModuleErrorSchema,
114
+ sources: this._sources
115
+ });
116
+ return super.build();
117
+ }
118
+ details(details) {
119
+ this._details = details;
120
+ return this;
121
+ }
122
+ message(message) {
123
+ this._message = message;
124
+ return this;
125
+ }
126
+ name(name) {
127
+ this._name = name;
128
+ return this;
129
+ }
130
+ query(query) {
131
+ this._query = query;
132
+ return this;
133
+ }
134
+ sources(sources) {
135
+ this._sources = sources;
136
+ return this;
137
+ }
138
+ };
139
+ __name(_ModuleErrorBuilder, "ModuleErrorBuilder");
140
+ var ModuleErrorBuilder = _ModuleErrorBuilder;
141
+
142
+ // src/QueryValidator/ModuleConfigQueryValidator.ts
143
+ import { QueryBoundWitnessWrapper } from "@xyo-network/boundwitness-wrapper";
144
+ var delimiter = "";
145
+ var _ModuleConfigQueryValidator = class _ModuleConfigQueryValidator {
146
+ allowed = {};
147
+ disallowed = {};
148
+ hasAllowedRules;
149
+ hasDisallowedRules;
150
+ hasRules;
151
+ constructor(config) {
152
+ var _a, _b, _c, _d;
153
+ if ((_a = config == null ? void 0 : config.security) == null ? void 0 : _a.allowed) {
154
+ for (const [schema, addresses] of Object.entries((_b = config.security) == null ? void 0 : _b.allowed)) {
155
+ this.allowed[schema] = addresses.map(toAddressesString);
156
+ }
157
+ }
158
+ if ((_c = config == null ? void 0 : config.security) == null ? void 0 : _c.disallowed) {
159
+ for (const [schema, addresses] of Object.entries((_d = config.security) == null ? void 0 : _d.disallowed)) {
160
+ this.disallowed[schema] = addresses.map(toAddressesString);
161
+ }
162
+ }
163
+ this.hasAllowedRules = Object.keys(this.allowed).length > 0;
164
+ this.hasDisallowedRules = Object.keys(this.disallowed).length > 0;
165
+ this.hasRules = this.hasAllowedRules || this.hasDisallowedRules;
166
+ }
167
+ queryable = /* @__PURE__ */ __name(async (query, payloads) => {
168
+ if (!this.hasRules) return true;
169
+ const addresses = query.addresses;
170
+ if (addresses.length === 0) return false;
171
+ const wrapper = await QueryBoundWitnessWrapper.parseQuery(query, payloads);
172
+ const schema = (await wrapper.getQuery()).schema;
173
+ return this.queryAllowed(schema, addresses) && !this.queryDisallowed(schema, addresses);
174
+ }, "queryable");
175
+ queryAllowed = /* @__PURE__ */ __name((schema, addresses) => {
176
+ var _a, _b;
177
+ if (!this.hasAllowedRules) return true;
178
+ if (addresses.length > 1) {
179
+ const signatories = toAddressesString(addresses);
180
+ const validCosigners = (_b = (_a = this.allowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(signatories);
181
+ if (validCosigners) return true;
182
+ }
183
+ return addresses.every((address) => {
184
+ var _a2, _b2;
185
+ return ((_b2 = (_a2 = this.allowed) == null ? void 0 : _a2[schema]) == null ? void 0 : _b2.includes(address)) || false;
186
+ });
187
+ }, "queryAllowed");
188
+ queryDisallowed = /* @__PURE__ */ __name((schema, addresses) => {
189
+ if (!this.hasDisallowedRules) return false;
190
+ return addresses.some((address) => {
191
+ var _a, _b;
192
+ return (_b = (_a = this.disallowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(address);
193
+ });
194
+ }, "queryDisallowed");
195
+ };
196
+ __name(_ModuleConfigQueryValidator, "ModuleConfigQueryValidator");
197
+ var ModuleConfigQueryValidator = _ModuleConfigQueryValidator;
198
+ var toAddressesString = /* @__PURE__ */ __name((addresses) => {
199
+ return Array.isArray(addresses) ? addresses.sort().map((address) => address.toLowerCase()).join(delimiter) : addresses.toLowerCase();
200
+ }, "toAddressesString");
201
+
202
+ // src/QueryValidator/SupportedQueryValidator.ts
203
+ import { QueryBoundWitnessWrapper as QueryBoundWitnessWrapper2 } from "@xyo-network/boundwitness-wrapper";
204
+ var isQuerySupportedByModule = /* @__PURE__ */ __name(async (mod, query, payloads) => {
205
+ const wrapper = await QueryBoundWitnessWrapper2.parseQuery(query, payloads);
206
+ const schema = (await wrapper.getQuery()).schema;
207
+ return mod.queries.includes(schema);
208
+ }, "isQuerySupportedByModule");
209
+ var _SupportedQueryValidator = class _SupportedQueryValidator {
210
+ mod;
211
+ constructor(mod) {
212
+ this.mod = mod;
213
+ this.queryable = (query, payloads) => {
214
+ return isQuerySupportedByModule(this.mod, query, payloads);
215
+ };
216
+ }
217
+ queryable;
218
+ };
219
+ __name(_SupportedQueryValidator, "SupportedQueryValidator");
220
+ var SupportedQueryValidator = _SupportedQueryValidator;
221
+
222
+ // src/AbstractModule.ts
223
+ var _AbstractModule = class _AbstractModule extends BaseEmitter {
224
+ _account = void 0;
225
+ //cache manifest based on maxDepth
226
+ _cachedManifests = new LRUCache({
227
+ max: 10,
228
+ ttl: 1e3 * 60 * 5
229
+ });
230
+ _lastError;
231
+ _startPromise = void 0;
232
+ _started = void 0;
233
+ moduleConfigQueryValidator;
234
+ supportedQueryValidator;
235
+ _busyCount = 0;
236
+ _logger = void 0;
237
+ _status = "stopped";
238
+ constructor(privateConstructorKey, params, account) {
239
+ assertEx2(_AbstractModule.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
240
+ const mutatedParams = {
241
+ ...params
242
+ };
243
+ super(mutatedParams);
244
+ this._account = account;
245
+ this.supportedQueryValidator = new SupportedQueryValidator(this).queryable;
246
+ this.moduleConfigQueryValidator = new ModuleConfigQueryValidator(mutatedParams == null ? void 0 : mutatedParams.config).queryable;
247
+ }
248
+ get account() {
249
+ return assertEx2(this._account, () => "Missing account");
250
+ }
251
+ get additionalSigners() {
252
+ return this.params.additionalSigners ?? [];
253
+ }
254
+ get address() {
255
+ return this.account.address;
256
+ }
257
+ get allowAnonymous() {
258
+ var _a;
259
+ return !!((_a = this.config.security) == null ? void 0 : _a.allowAnonymous);
260
+ }
261
+ get allowNameResolution() {
262
+ return this.params.allowNameResolution ?? true;
263
+ }
264
+ get archiving() {
265
+ return this.config.archiving;
266
+ }
267
+ get archivist() {
268
+ return this.config.archivist;
269
+ }
270
+ get config() {
271
+ return this.params.config;
272
+ }
273
+ get dead() {
274
+ return this.status === "dead";
275
+ }
276
+ get ephemeralQueryAccountEnabled() {
277
+ return !!this.params.ephemeralQueryAccountEnabled;
278
+ }
279
+ get id() {
280
+ return this.modName ?? this.address;
281
+ }
282
+ get logger() {
283
+ var _a;
284
+ const consoleLogger = this.config.consoleLogger;
285
+ this._logger = this._logger ?? consoleLogger ? new ConsoleLogger(consoleLogger) : ((_a = this.params) == null ? void 0 : _a.logger) ?? _AbstractModule.defaultLogger ?? Base2.defaultLogger;
286
+ return this._logger;
287
+ }
288
+ get modName() {
289
+ return this.config.name;
290
+ }
291
+ get priority() {
292
+ return ObjectResolverPriority.Normal;
293
+ }
294
+ get queries() {
295
+ return [
296
+ ModuleAddressQuerySchema,
297
+ ModuleSubscribeQuerySchema,
298
+ ModuleManifestQuerySchema,
299
+ ModuleStateQuerySchema
300
+ ];
301
+ }
302
+ get status() {
303
+ return this._status;
304
+ }
305
+ get timestamp() {
306
+ return this.config.timestamp ?? false;
307
+ }
308
+ set status(value) {
309
+ if (this._status !== "dead") {
310
+ this._status = value;
311
+ }
312
+ }
313
+ static _getRootFunction(funcName) {
314
+ let anyThis = this;
315
+ while (anyThis.__proto__[funcName]) {
316
+ anyThis = anyThis.__proto__;
317
+ }
318
+ return anyThis[funcName];
319
+ }
320
+ static _noOverride(functionName) {
321
+ const thisFunc = this[functionName];
322
+ const rootFunc = this._getRootFunction(functionName);
323
+ assertEx2(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
324
+ }
325
+ static async create(params) {
326
+ var _a, _b, _c, _d, _e, _f;
327
+ this._noOverride("create");
328
+ if (!this.configSchemas || this.configSchemas.length === 0) {
329
+ throw new Error(`Missing configSchema [${(_a = params == null ? void 0 : params.config) == null ? void 0 : _a.schema}][${this.name}]`);
330
+ }
331
+ if (!this.defaultConfigSchema) {
332
+ throw new Error(`Missing defaultConfigSchema [${(_b = params == null ? void 0 : params.config) == null ? void 0 : _b.schema}][${this.name}]`);
333
+ }
334
+ assertEx2(((_c = params == null ? void 0 : params.config) == null ? void 0 : _c.name) === void 0 || isModuleName(params.config.name), () => {
335
+ var _a2;
336
+ return `Invalid module name: ${(_a2 = params == null ? void 0 : params.config) == null ? void 0 : _a2.name}`;
337
+ });
338
+ const { account } = params ?? {};
339
+ const schema = ((_d = params == null ? void 0 : params.config) == null ? void 0 : _d.schema) ?? this.defaultConfigSchema;
340
+ const allowedSchemas = this.configSchemas;
341
+ assertEx2(allowedSchemas.includes(schema), () => `Bad Config Schema [Received ${schema}] [Expected ${JSON.stringify(allowedSchemas)}]`);
342
+ const mutatedConfig = {
343
+ ...params == null ? void 0 : params.config,
344
+ schema
345
+ };
346
+ (_e = params == null ? void 0 : params.logger) == null ? void 0 : _e.debug(`config: ${JSON.stringify(mutatedConfig, null, 2)}`);
347
+ const mutatedParams = {
348
+ ...params,
349
+ config: mutatedConfig
350
+ };
351
+ const activeLogger = (params == null ? void 0 : params.logger) ?? _AbstractModule.defaultLogger;
352
+ const generatedAccount = await _AbstractModule.determineAccount({
353
+ account
354
+ });
355
+ const address = generatedAccount.address;
356
+ mutatedParams.logger = activeLogger ? new IdLogger(activeLogger, () => `0x${address}`) : void 0;
357
+ const newModule = new this(_AbstractModule.privateConstructorKey, mutatedParams, generatedAccount);
358
+ if (!_AbstractModule.enableLazyLoad) {
359
+ await ((_f = newModule.start) == null ? void 0 : _f.call(newModule));
360
+ }
361
+ return newModule;
362
+ }
363
+ static async determineAccount(params) {
364
+ return await determineAccount(params, this.allowRandomAccount);
365
+ }
366
+ static factory(params) {
367
+ return ModuleFactory.withParams(this, params);
368
+ }
369
+ _getRootFunction(funcName) {
370
+ let anyThis = this;
371
+ while (anyThis.__proto__[funcName]) {
372
+ anyThis = anyThis.__proto__;
373
+ }
374
+ return anyThis[funcName];
375
+ }
376
+ async busy(closure) {
377
+ if (this._busyCount <= 0) {
378
+ this._busyCount = 0;
379
+ const args = {
380
+ busy: true,
381
+ module: this
382
+ };
383
+ await this.emit("moduleBusy", args);
384
+ }
385
+ this._busyCount++;
386
+ try {
387
+ return await closure();
388
+ } finally {
389
+ this._busyCount--;
390
+ if (this._busyCount <= 0) {
391
+ this._busyCount = 0;
392
+ const args = {
393
+ busy: false,
394
+ module: this
395
+ };
396
+ await this.emit("moduleBusy", args);
397
+ }
398
+ }
399
+ }
400
+ emit(eventName, eventArgs) {
401
+ return super.emit(eventName, eventArgs);
402
+ }
403
+ previousHash() {
404
+ this._checkDead();
405
+ return this.account.previousHash;
406
+ }
407
+ async query(query, payloads, queryConfig) {
408
+ this._checkDead();
409
+ this._noOverride("query");
410
+ const sourceQuery = await PayloadBuilder2.build(assertEx2(QueryBoundWitnessWrapper3.unwrap(query), () => "Invalid query"));
411
+ return await this.busy(async () => {
412
+ const resultPayloads = [];
413
+ const errorPayloads = [];
414
+ const queryAccount = this.ephemeralQueryAccountEnabled ? Account2.randomSync() : void 0;
415
+ try {
416
+ await this.started("throw");
417
+ if (!this.allowAnonymous && query.addresses.length === 0) {
418
+ throw new Error(`Anonymous Queries not allowed, but running anyway [${this.modName}], [${this.address}]`);
419
+ }
420
+ if (queryConfig == null ? void 0 : queryConfig.allowedQueries) {
421
+ assertEx2(queryConfig == null ? void 0 : queryConfig.allowedQueries.includes(sourceQuery.schema), () => `Query not allowed [${sourceQuery.schema}]`);
422
+ }
423
+ resultPayloads.push(...await this.queryHandler(sourceQuery, payloads, queryConfig));
424
+ } catch (ex) {
425
+ await handleErrorAsync(ex, async (err) => {
426
+ const error = err;
427
+ this._lastError = error;
428
+ errorPayloads.push(await new ModuleErrorBuilder().sources([
429
+ sourceQuery.$hash
430
+ ]).name(this.modName ?? "<Unknown>").query(sourceQuery.schema).details(error.details).message(error.message).build());
431
+ });
432
+ }
433
+ if (this.timestamp) {
434
+ const timestamp = {
435
+ schema: "network.xyo.timestamp",
436
+ timestamp: Date.now()
437
+ };
438
+ resultPayloads.push(timestamp);
439
+ }
440
+ const result = await this.bindQueryResult(sourceQuery, resultPayloads, queryAccount ? [
441
+ queryAccount
442
+ ] : [], errorPayloads);
443
+ const args = {
444
+ module: this,
445
+ payloads,
446
+ query: sourceQuery,
447
+ result
448
+ };
449
+ await this.emit("moduleQueried", args);
450
+ return result;
451
+ });
452
+ }
453
+ async queryable(query, payloads, queryConfig) {
454
+ if (this.dead) {
455
+ return false;
456
+ }
457
+ if (!await this.started("warn")) return false;
458
+ const configValidator = queryConfig ? new ModuleConfigQueryValidator(Object.assign({}, this.config, queryConfig)).queryable : this.moduleConfigQueryValidator;
459
+ const validators = [
460
+ this.supportedQueryValidator,
461
+ configValidator
462
+ ];
463
+ return validators.every((validator) => validator(query, payloads));
464
+ }
465
+ start(_timeout) {
466
+ this._startPromise = this._startPromise ?? this.startHandler();
467
+ const result = this._startPromise;
468
+ this.status = result ? "started" : "dead";
469
+ return result;
470
+ }
471
+ async started(notStartedAction = "log", tryStart = true) {
472
+ const started = await this._started;
473
+ if (started === true) {
474
+ return true;
475
+ }
476
+ if (!started) {
477
+ this._started = (async () => {
478
+ var _a, _b, _c;
479
+ if (tryStart) {
480
+ try {
481
+ await this.start();
482
+ return true;
483
+ } catch (ex) {
484
+ handleError(ex, (error) => {
485
+ var _a2;
486
+ (_a2 = this.logger) == null ? void 0 : _a2.warn(`Autostart of Module Failed: ${error.message})`);
487
+ this._started = void 0;
488
+ });
489
+ }
490
+ }
491
+ switch (notStartedAction) {
492
+ case "throw": {
493
+ throw new Error(`Module not Started [${this.address}]`);
494
+ }
495
+ case "warn": {
496
+ (_a = this.logger) == null ? void 0 : _a.warn("Module not started");
497
+ break;
498
+ }
499
+ case "error": {
500
+ (_b = this.logger) == null ? void 0 : _b.error("Module not started");
501
+ break;
502
+ }
503
+ case "none": {
504
+ break;
505
+ }
506
+ default: {
507
+ (_c = this.logger) == null ? void 0 : _c.log("Module not started");
508
+ break;
509
+ }
510
+ }
511
+ return false;
512
+ })();
513
+ }
514
+ if (!this._started) {
515
+ throw "Failed to create start promise";
516
+ }
517
+ return await this._started;
518
+ }
519
+ async stop(_timeout) {
520
+ return await this.busy(async () => {
521
+ const result = await this.stopHandler();
522
+ this._started = void 0;
523
+ this._startPromise = void 0;
524
+ this.status = result ? "stopped" : "dead";
525
+ return result;
526
+ });
527
+ }
528
+ _checkDead() {
529
+ if (this.dead) {
530
+ throw new DeadModuleError(this.id, this._lastError);
531
+ }
532
+ }
533
+ _noOverride(functionName) {
534
+ const thisFunc = this[functionName];
535
+ const rootFunc = this._getRootFunction(functionName);
536
+ assertEx2(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
537
+ }
538
+ async archivistInstance(required = false) {
539
+ const archivist = this.archivist;
540
+ if (!archivist) {
541
+ if (required) {
542
+ throw new Error("No archivist specified");
543
+ }
544
+ return void 0;
545
+ }
546
+ const resolved = await this.upResolver.resolve(archivist) ?? await this.downResolver.resolve(archivist);
547
+ if (required) {
548
+ assertEx2(resolved, () => `Unable to resolve archivist [${archivist}]`);
549
+ }
550
+ return resolved ? asArchivistInstance(resolved, () => `Specified archivist is not an Archivist [${archivist}]`) : void 0;
551
+ }
552
+ bindHashes(hashes, schema, account) {
553
+ const promise = new PromiseEx((resolve) => {
554
+ const result = this.bindHashesInternal(hashes, schema, account);
555
+ resolve == null ? void 0 : resolve(result);
556
+ return result;
557
+ }, account);
558
+ return promise;
559
+ }
560
+ async bindHashesInternal(hashes, schema, account = this.account) {
561
+ var _a;
562
+ const builder = new BoundWitnessBuilder().hashes(hashes, schema).signer(account);
563
+ const result = (await builder.build())[0];
564
+ (_a = this.logger) == null ? void 0 : _a.debug(`result: ${JSON.stringify(result, null, 2)}`);
565
+ return result;
566
+ }
567
+ bindQuery(query, payloads, account, additionalSigners) {
568
+ const promise = new PromiseEx(async (resolve) => {
569
+ const result = await this.bindQueryInternal(query, payloads, account, additionalSigners);
570
+ resolve == null ? void 0 : resolve(result);
571
+ return result;
572
+ }, account);
573
+ return promise;
574
+ }
575
+ async bindQueryInternal(query, payloads, account = this.account, additionalSigners = []) {
576
+ const accounts = [
577
+ account,
578
+ ...additionalSigners
579
+ ].filter(exists);
580
+ const builder = await new QueryBoundWitnessBuilder().payloads(payloads).signers(accounts).query(query);
581
+ let additional = [];
582
+ if (this.config.certify) {
583
+ additional = await this.certifyParents();
584
+ await builder.additional(additional);
585
+ }
586
+ const [bw, payloadsOut, errors] = await builder.build();
587
+ return [
588
+ bw,
589
+ [
590
+ ...payloadsOut,
591
+ ...additional
592
+ ],
593
+ errors
594
+ ];
595
+ }
596
+ async bindQueryResult(query, payloads, additionalWitnesses = [], errors) {
597
+ var _a;
598
+ const builder = new BoundWitnessBuilder().payloads(payloads).errors(errors).sourceQuery(query.$hash);
599
+ const witnesses = [
600
+ this.account,
601
+ ...additionalWitnesses
602
+ ].filter(exists);
603
+ builder.signers(witnesses);
604
+ const result = [
605
+ (await builder.build())[0],
606
+ await Promise.all(payloads.map((payload) => PayloadBuilder2.build(payload))),
607
+ await Promise.all((_a = errors ?? []) == null ? void 0 : _a.map((error) => PayloadBuilder2.build(error)))
608
+ ];
609
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
610
+ forget(this.storeToArchivists(result.flat()));
611
+ }
612
+ return result;
613
+ }
614
+ async generateConfigAndAddress(_maxDepth) {
615
+ const config = await PayloadBuilder2.build(this.config);
616
+ const address = await new PayloadBuilder2({
617
+ schema: AddressSchema
618
+ }).fields({
619
+ address: this.address
620
+ }).build();
621
+ const queries = await Promise.all(this.queries.map(async (query) => {
622
+ return await new PayloadBuilder2({
623
+ schema: QuerySchema
624
+ }).fields({
625
+ query
626
+ }).build();
627
+ }));
628
+ const configSchema = await PayloadBuilder2.build({
629
+ config: config.schema,
630
+ schema: ConfigSchema
631
+ });
632
+ return compact([
633
+ config,
634
+ configSchema,
635
+ address,
636
+ ...queries
637
+ ]);
638
+ }
639
+ async generateDescribe() {
640
+ var _a;
641
+ const description = {
642
+ address: this.address,
643
+ queries: this.queries,
644
+ schema: ModuleDescriptionSchema
645
+ };
646
+ if ((_a = this.config) == null ? void 0 : _a.name) {
647
+ description.name = this.modName;
648
+ }
649
+ const discover = await this.generateConfigAndAddress();
650
+ description.children = compact((discover == null ? void 0 : discover.map((payload) => {
651
+ const address = payload.schema === AddressSchema ? payload.address : void 0;
652
+ return address == this.address ? void 0 : address;
653
+ })) ?? []);
654
+ return description;
655
+ }
656
+ /** @deprecated use archivistInstance() instead */
657
+ async getArchivist() {
658
+ return await this.archivistInstance();
659
+ }
660
+ isAllowedArchivingQuery(schema) {
661
+ var _a;
662
+ const queries = (_a = this.archiving) == null ? void 0 : _a.queries;
663
+ if (queries) {
664
+ return queries.includes(schema);
665
+ }
666
+ return true;
667
+ }
668
+ manifestHandler(_maxDepth = 1, _ignoreAddresses = []) {
669
+ throw new Error("Not supported");
670
+ }
671
+ moduleAddressHandler() {
672
+ const address = this.address;
673
+ const name = this.modName;
674
+ const previousHash = this.address;
675
+ const moduleAccount = name ? {
676
+ address,
677
+ name,
678
+ schema: AddressSchema
679
+ } : {
680
+ address,
681
+ schema: AddressSchema
682
+ };
683
+ const moduleAccountPreviousHash = previousHash ? {
684
+ address,
685
+ previousHash,
686
+ schema: AddressPreviousHashSchema
687
+ } : {
688
+ address,
689
+ schema: AddressSchema
690
+ };
691
+ return [
692
+ moduleAccount,
693
+ moduleAccountPreviousHash
694
+ ];
695
+ }
696
+ async queryHandler(query, payloads, queryConfig) {
697
+ await this.started("throw");
698
+ const wrapper = await QueryBoundWitnessWrapper3.parseQuery(query, payloads);
699
+ const queryPayload = await wrapper.getQuery();
700
+ assertEx2(await this.queryable(query, payloads, queryConfig));
701
+ const resultPayloads = [];
702
+ switch (queryPayload.schema) {
703
+ case ModuleManifestQuerySchema: {
704
+ resultPayloads.push(await this.manifestHandler(queryPayload.maxDepth));
705
+ break;
706
+ }
707
+ case ModuleAddressQuerySchema: {
708
+ resultPayloads.push(...await this.moduleAddressHandler());
709
+ break;
710
+ }
711
+ case ModuleStateQuerySchema: {
712
+ resultPayloads.push(...await this.stateHandler());
713
+ break;
714
+ }
715
+ case ModuleSubscribeQuerySchema: {
716
+ this.subscribeHandler();
717
+ break;
718
+ }
719
+ default: {
720
+ throw new Error(`Unsupported Query [${queryPayload.schema}]`);
721
+ }
722
+ }
723
+ return resultPayloads;
724
+ }
725
+ async startHandler() {
726
+ this.validateConfig();
727
+ await Promise.resolve();
728
+ this._started = true;
729
+ return true;
730
+ }
731
+ async stateHandler() {
732
+ return [
733
+ await this.manifestHandler(),
734
+ ...await this.generateConfigAndAddress(),
735
+ await this.generateDescribe()
736
+ ];
737
+ }
738
+ stopHandler(_timeout) {
739
+ this._started = void 0;
740
+ return true;
741
+ }
742
+ subscribeHandler() {
743
+ return;
744
+ }
745
+ validateConfig(config, parents = []) {
746
+ return Object.entries(config ?? this.config ?? {}).reduce((valid, [key, value]) => {
747
+ var _a, _b;
748
+ switch (typeof value) {
749
+ case "function": {
750
+ (_a = this.logger) == null ? void 0 : _a.warn(`Fields of type function not allowed in config [${parents == null ? void 0 : parents.join(".")}.${key}]`);
751
+ return false;
752
+ }
753
+ case "object": {
754
+ if (Array.isArray(value)) {
755
+ return (
756
+ // eslint-disable-next-line unicorn/no-array-reduce
757
+ value.reduce((valid2, value2) => {
758
+ return this.validateConfig(value2, [
759
+ ...parents,
760
+ key
761
+ ]) && valid2;
762
+ }, true) && valid
763
+ );
764
+ }
765
+ if (!serializableField(value)) {
766
+ (_b = this.logger) == null ? void 0 : _b.warn(`Fields that are not serializable to JSON are not allowed in config [${parents == null ? void 0 : parents.join(".")}.${key}]`);
767
+ return false;
768
+ }
769
+ return value ? this.validateConfig(value, [
770
+ ...parents,
771
+ key
772
+ ]) && valid : true;
773
+ }
774
+ default: {
775
+ return valid;
776
+ }
777
+ }
778
+ }, true);
779
+ }
780
+ };
781
+ __name(_AbstractModule, "AbstractModule");
782
+ __publicField(_AbstractModule, "allowRandomAccount", true);
783
+ __publicField(_AbstractModule, "configSchemas", [
784
+ ModuleConfigSchema
785
+ ]);
786
+ __publicField(_AbstractModule, "defaultConfigSchema", ModuleConfigSchema);
787
+ __publicField(_AbstractModule, "defaultLogger", new ConsoleLogger(LogLevel.warn));
788
+ __publicField(_AbstractModule, "enableLazyLoad", false);
789
+ __publicField(_AbstractModule, "labels", {});
790
+ __publicField(_AbstractModule, "uniqueName", globallyUnique("AbstractModule", _AbstractModule, "xyo"));
791
+ __publicField(_AbstractModule, "privateConstructorKey", Date.now().toString());
792
+ var AbstractModule = _AbstractModule;
793
+
794
+ // src/AbstractModuleInstance.ts
795
+ import { assertEx as assertEx3 } from "@xylabs/assert";
796
+ import { compact as compact2 } from "@xylabs/lodash";
797
+ import { globallyUnique as globallyUnique2 } from "@xylabs/object";
798
+ import { asArchivistInstance as asArchivistInstance2 } from "@xyo-network/archivist-model";
799
+ import { ModuleManifestPayloadSchema } from "@xyo-network/manifest-model";
800
+ import { duplicateModules, ModuleManifestQuerySchema as ModuleManifestQuerySchema2, ModuleStateQuerySchema as ModuleStateQuerySchema2, ResolveHelper } from "@xyo-network/module-model";
801
+ import { CompositeModuleResolver } from "@xyo-network/module-resolver";
802
+ import { asNodeInstance } from "@xyo-network/node-model";
803
+ var _AbstractModuleInstance = class _AbstractModuleInstance extends AbstractModule {
804
+ _downResolver;
805
+ _parents = [];
806
+ _privateResolver;
807
+ _upResolver;
808
+ constructor(privateConstructorKey, params, account) {
809
+ assertEx3(AbstractModule.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
810
+ const mutatedParams = {
811
+ ...params
812
+ };
813
+ const addToResolvers = mutatedParams.addToResolvers ?? true;
814
+ super(privateConstructorKey, mutatedParams, account);
815
+ if (addToResolvers) {
816
+ this.upResolver.add(this);
817
+ this.downResolver.add(this);
818
+ }
819
+ }
820
+ get downResolver() {
821
+ this._downResolver = this._downResolver ?? new CompositeModuleResolver({
822
+ allowNameResolution: this.allowNameResolution,
823
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
824
+ root: this
825
+ });
826
+ return this._downResolver;
827
+ }
828
+ get modName() {
829
+ return super.modName;
830
+ }
831
+ get moduleIdentifierTransformers() {
832
+ return this.params.moduleIdentifierTransformers ?? ResolveHelper.transformers;
833
+ }
834
+ get privateResolver() {
835
+ this._privateResolver = this._privateResolver ?? new CompositeModuleResolver({
836
+ allowNameResolution: this.allowNameResolution,
837
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
838
+ root: this
839
+ });
840
+ return this._privateResolver;
841
+ }
842
+ get root() {
843
+ return this;
844
+ }
845
+ get upResolver() {
846
+ this._upResolver = this._upResolver ?? new CompositeModuleResolver({
847
+ allowNameResolution: this.allowNameResolution,
848
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
849
+ root: this
850
+ });
851
+ return this._upResolver;
852
+ }
853
+ addParent(module) {
854
+ const existingEntry = this._parents.find((parent) => parent.address === module.address);
855
+ if (!existingEntry) {
856
+ this._parents.push(asNodeInstance(module, "Only NodeInstances can be parents"));
857
+ }
858
+ }
859
+ async certifyParents() {
860
+ const parents = await this.parents();
861
+ return (await Promise.all(parents.map(async (parent) => {
862
+ const [bw, payloads, errors] = await parent.certifyQuery(this.address);
863
+ return errors.length === 0 ? [
864
+ bw,
865
+ ...payloads
866
+ ] : [];
867
+ }))).flat();
868
+ }
869
+ manifest(maxDepth) {
870
+ this._checkDead();
871
+ return this.busy(async () => {
872
+ return await this.manifestHandler(maxDepth);
873
+ });
874
+ }
875
+ async manifestQuery(account, maxDepth) {
876
+ const queryPayload = {
877
+ schema: ModuleManifestQuerySchema2,
878
+ ...maxDepth === void 0 ? {} : {
879
+ maxDepth
880
+ }
881
+ };
882
+ return await this.sendQueryRaw(queryPayload, void 0, account);
883
+ }
884
+ moduleAddress() {
885
+ this._checkDead();
886
+ return this.busy(async () => {
887
+ return await this.moduleAddressHandler();
888
+ });
889
+ }
890
+ parents() {
891
+ return this._parents;
892
+ }
893
+ privateChildren() {
894
+ return [];
895
+ }
896
+ publicChildren() {
897
+ return [];
898
+ }
899
+ removeParent(address) {
900
+ this._parents = this._parents.filter((item) => item.address !== address);
901
+ }
902
+ async resolve(idOrFilter = "*", options = {}) {
903
+ const config = {
904
+ address: this.address,
905
+ dead: this.dead,
906
+ downResolver: this.downResolver,
907
+ logger: this.logger,
908
+ module: this,
909
+ transformers: this.moduleIdentifierTransformers,
910
+ upResolver: this.upResolver
911
+ };
912
+ if (idOrFilter === "*") {
913
+ return (await ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
914
+ }
915
+ switch (typeof idOrFilter) {
916
+ case "string": {
917
+ return await ResolveHelper.resolve(config, idOrFilter, options);
918
+ }
919
+ case "object": {
920
+ return (await ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
921
+ }
922
+ default: {
923
+ return (await ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
924
+ }
925
+ }
926
+ }
927
+ resolveIdentifier(id, options) {
928
+ const { direction = "all" } = options ?? {};
929
+ switch (direction) {
930
+ case "down": {
931
+ return this.downResolver.resolveIdentifier(id, options);
932
+ }
933
+ default: {
934
+ const mutatedOptions = {
935
+ ...options,
936
+ direction: "all"
937
+ };
938
+ return this.upResolver.resolveIdentifier(id, mutatedOptions);
939
+ }
940
+ }
941
+ }
942
+ async resolvePrivate(id = "*", options = {}) {
943
+ return await this.privateResolver.resolve(id, options) ?? await this.upResolver.resolve(id, options) ?? await this.downResolver.resolve(id, options);
944
+ }
945
+ async siblings() {
946
+ return (await Promise.all((await this.parents()).map((parent) => parent.publicChildren()))).flat().filter(duplicateModules);
947
+ }
948
+ /*override start(_timeout?: number): Promisable<boolean> {
949
+ if (this.parents.length === 0) {
950
+ this.logger.warn(`Module is being started without being attached to a parent: ${this.id} [${this.address}]`)
951
+ }
952
+ return super.start()
953
+ }*/
954
+ state() {
955
+ this._checkDead();
956
+ return this.busy(async () => {
957
+ return await this.stateHandler();
958
+ });
959
+ }
960
+ async stateQuery(account) {
961
+ const queryPayload = {
962
+ schema: ModuleStateQuerySchema2
963
+ };
964
+ return await this.sendQueryRaw(queryPayload, void 0, account);
965
+ }
966
+ subscribe(_queryAccount) {
967
+ this._checkDead();
968
+ return this.subscribeHandler();
969
+ }
970
+ async manifestHandler(maxDepth = 1, _ignoreAddresses = []) {
971
+ const cachedResult = this._cachedManifests.get(maxDepth);
972
+ if (cachedResult) {
973
+ return cachedResult;
974
+ }
975
+ const modName = this.modName ?? "<Anonymous>";
976
+ const children = await this.publicChildren();
977
+ const childAddressToName = {};
978
+ for (const child of children) {
979
+ if (child.address !== this.address) {
980
+ childAddressToName[child.address] = child.modName ?? null;
981
+ }
982
+ }
983
+ const result = {
984
+ config: {
985
+ name: modName,
986
+ ...this.config
987
+ },
988
+ schema: ModuleManifestPayloadSchema,
989
+ status: {
990
+ address: this.address,
991
+ children: childAddressToName
992
+ }
993
+ };
994
+ this._cachedManifests.set(maxDepth, result);
995
+ return result;
996
+ }
997
+ async resolveArchivingArchivists() {
998
+ var _a;
999
+ const archivists = (_a = this.archiving) == null ? void 0 : _a.archivists;
1000
+ if (!archivists) return [];
1001
+ const resolved = await Promise.all(archivists.map((archivist) => this.resolve(archivist)));
1002
+ return compact2(resolved.map((mod) => asArchivistInstance2(mod)));
1003
+ }
1004
+ async sendQuery(queryPayload, payloads, account) {
1005
+ const queryResults = await this.sendQueryRaw(queryPayload, payloads, account);
1006
+ const [, resultPayloads, errors] = queryResults;
1007
+ if (errors && errors.length > 0) {
1008
+ throw errors[0];
1009
+ }
1010
+ return resultPayloads;
1011
+ }
1012
+ async sendQueryRaw(queryPayload, payloads, account) {
1013
+ const query = await this.bindQuery(queryPayload, payloads, account, this.additionalSigners);
1014
+ return await this.query(query[0], query[1]);
1015
+ }
1016
+ async storeToArchivists(payloads) {
1017
+ try {
1018
+ const archivists = await this.resolveArchivingArchivists();
1019
+ return (await Promise.all(archivists.map((archivist) => {
1020
+ var _a;
1021
+ return (_a = archivist.insert) == null ? void 0 : _a.call(archivist, payloads);
1022
+ }))).map(([bw]) => bw);
1023
+ } catch (ex) {
1024
+ const error = ex;
1025
+ this.logger.error(`Error storing to archivists: ${error.message}`);
1026
+ return [];
1027
+ }
1028
+ }
1029
+ };
1030
+ __name(_AbstractModuleInstance, "AbstractModuleInstance");
1031
+ __publicField(_AbstractModuleInstance, "uniqueName", globallyUnique2("AbstractModuleInstance", _AbstractModuleInstance, "xyo"));
1032
+ var AbstractModuleInstance = _AbstractModuleInstance;
1033
+ export {
1034
+ AbstractModule,
1035
+ AbstractModuleInstance,
1036
+ BaseEmitter,
1037
+ ModuleConfigQueryValidator,
1038
+ ModuleErrorBuilder,
1039
+ SupportedQueryValidator,
1040
+ isQuerySupportedByModule
1041
+ };
2
1042
  //# sourceMappingURL=index.js.map