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