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