@xyo-network/module-abstract 2.75.0 → 2.75.2

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 (88) hide show
  1. package/dist/browser/AbstractModule.d.cts +84 -0
  2. package/dist/browser/AbstractModule.d.cts.map +1 -0
  3. package/dist/browser/AbstractModule.js +16 -182
  4. package/dist/browser/AbstractModule.js.map +1 -1
  5. package/dist/browser/AbstractModuleInstance.d.cts +14 -0
  6. package/dist/browser/AbstractModuleInstance.d.cts.map +1 -0
  7. package/dist/browser/AbstractModuleInstance.js +4 -738
  8. package/dist/browser/AbstractModuleInstance.js.map +1 -1
  9. package/dist/browser/BaseEmitter.d.cts +17 -0
  10. package/dist/browser/BaseEmitter.d.cts.map +1 -0
  11. package/dist/browser/BaseEmitter.js +2 -4
  12. package/dist/browser/BaseEmitter.js.map +1 -1
  13. package/dist/browser/Error.d.cts +15 -0
  14. package/dist/browser/Error.d.cts.map +1 -0
  15. package/dist/browser/Error.js +2 -4
  16. package/dist/browser/Error.js.map +1 -1
  17. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.d.cts +15 -0
  18. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.d.cts.map +1 -0
  19. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.js +4 -6
  20. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.js.map +1 -1
  21. package/dist/browser/QueryValidator/QueryValidator.d.cts +8 -0
  22. package/dist/browser/QueryValidator/QueryValidator.d.cts.map +1 -0
  23. package/dist/browser/QueryValidator/SupportedQueryValidator.d.cts +22 -0
  24. package/dist/browser/QueryValidator/SupportedQueryValidator.d.cts.map +1 -0
  25. package/dist/browser/QueryValidator/SupportedQueryValidator.js +3 -5
  26. package/dist/browser/QueryValidator/SupportedQueryValidator.js.map +1 -1
  27. package/dist/browser/QueryValidator/index.d.cts +4 -0
  28. package/dist/browser/QueryValidator/index.d.cts.map +1 -0
  29. package/dist/browser/QueryValidator/index.js +3 -86
  30. package/dist/browser/QueryValidator/index.js.map +1 -1
  31. package/dist/browser/index.d.cts +6 -0
  32. package/dist/browser/index.d.cts.map +1 -0
  33. package/dist/browser/index.js +5 -782
  34. package/dist/browser/index.js.map +1 -1
  35. package/dist/docs.json +42701 -0
  36. package/dist/node/AbstractModule.d.cts +84 -0
  37. package/dist/node/AbstractModule.d.cts.map +1 -0
  38. package/dist/node/AbstractModule.js +240 -56
  39. package/dist/node/AbstractModule.js.map +1 -1
  40. package/dist/node/AbstractModule.mjs +232 -48
  41. package/dist/node/AbstractModule.mjs.map +1 -1
  42. package/dist/node/AbstractModuleInstance.d.cts +14 -0
  43. package/dist/node/AbstractModuleInstance.d.cts.map +1 -0
  44. package/dist/node/AbstractModuleInstance.js +757 -6
  45. package/dist/node/AbstractModuleInstance.js.map +1 -1
  46. package/dist/node/AbstractModuleInstance.mjs +757 -6
  47. package/dist/node/AbstractModuleInstance.mjs.map +1 -1
  48. package/dist/node/BaseEmitter.d.cts +17 -0
  49. package/dist/node/BaseEmitter.d.cts.map +1 -0
  50. package/dist/node/BaseEmitter.js +6 -5
  51. package/dist/node/BaseEmitter.js.map +1 -1
  52. package/dist/node/BaseEmitter.mjs +6 -5
  53. package/dist/node/BaseEmitter.mjs.map +1 -1
  54. package/dist/node/Error.d.cts +15 -0
  55. package/dist/node/Error.d.cts.map +1 -0
  56. package/dist/node/Error.js +6 -5
  57. package/dist/node/Error.js.map +1 -1
  58. package/dist/node/Error.mjs +6 -5
  59. package/dist/node/Error.mjs.map +1 -1
  60. package/dist/node/QueryValidator/ModuleConfigQueryValidator.d.cts +15 -0
  61. package/dist/node/QueryValidator/ModuleConfigQueryValidator.d.cts.map +1 -0
  62. package/dist/node/QueryValidator/ModuleConfigQueryValidator.js +23 -14
  63. package/dist/node/QueryValidator/ModuleConfigQueryValidator.js.map +1 -1
  64. package/dist/node/QueryValidator/ModuleConfigQueryValidator.mjs +23 -14
  65. package/dist/node/QueryValidator/ModuleConfigQueryValidator.mjs.map +1 -1
  66. package/dist/node/QueryValidator/QueryValidator.d.cts +8 -0
  67. package/dist/node/QueryValidator/QueryValidator.d.cts.map +1 -0
  68. package/dist/node/QueryValidator/QueryValidator.js +2 -0
  69. package/dist/node/QueryValidator/QueryValidator.js.map +1 -1
  70. package/dist/node/QueryValidator/SupportedQueryValidator.d.cts +22 -0
  71. package/dist/node/QueryValidator/SupportedQueryValidator.d.cts.map +1 -0
  72. package/dist/node/QueryValidator/SupportedQueryValidator.js +7 -6
  73. package/dist/node/QueryValidator/SupportedQueryValidator.js.map +1 -1
  74. package/dist/node/QueryValidator/SupportedQueryValidator.mjs +7 -6
  75. package/dist/node/QueryValidator/SupportedQueryValidator.mjs.map +1 -1
  76. package/dist/node/QueryValidator/index.d.cts +4 -0
  77. package/dist/node/QueryValidator/index.d.cts.map +1 -0
  78. package/dist/node/QueryValidator/index.js +100 -7
  79. package/dist/node/QueryValidator/index.js.map +1 -1
  80. package/dist/node/QueryValidator/index.mjs +92 -3
  81. package/dist/node/QueryValidator/index.mjs.map +1 -1
  82. package/dist/node/index.d.cts +6 -0
  83. package/dist/node/index.d.cts.map +1 -0
  84. package/dist/node/index.js +811 -11
  85. package/dist/node/index.js.map +1 -1
  86. package/dist/node/index.mjs +799 -5
  87. package/dist/node/index.mjs.map +1 -1
  88. package/package.json +26 -26
@@ -3,6 +3,12 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
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
+ };
6
12
  var __copyProps = (to, from, except, desc) => {
7
13
  if (from && typeof from === "object" || typeof from === "function") {
8
14
  for (let key of __getOwnPropNames(from))
@@ -11,21 +17,815 @@ var __copyProps = (to, from, except, desc) => {
11
17
  }
12
18
  return to;
13
19
  };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
20
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+ var __publicField = (obj, key, value) => {
22
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
23
+ return value;
24
+ };
25
+
26
+ // src/index.ts
16
27
  var src_exports = {};
28
+ __export(src_exports, {
29
+ AbstractModule: () => AbstractModule,
30
+ AbstractModuleInstance: () => AbstractModuleInstance,
31
+ BaseEmitter: () => BaseEmitter,
32
+ ModuleConfigQueryValidator: () => ModuleConfigQueryValidator,
33
+ ModuleErrorBuilder: () => ModuleErrorBuilder,
34
+ SupportedQueryValidator: () => SupportedQueryValidator,
35
+ isQuerySupportedByModule: () => isQuerySupportedByModule
36
+ });
17
37
  module.exports = __toCommonJS(src_exports);
18
- __reExport(src_exports, require("./AbstractModule"), module.exports);
19
- __reExport(src_exports, require("./AbstractModuleInstance"), module.exports);
20
- __reExport(src_exports, require("./BaseEmitter"), module.exports);
21
- __reExport(src_exports, require("./Error"), module.exports);
22
- __reExport(src_exports, require("./QueryValidator"), module.exports);
38
+
39
+ // src/AbstractModule.ts
40
+ var import_assert = require("@xylabs/assert");
41
+ var import_exists = require("@xylabs/exists");
42
+ var import_lodash = require("@xylabs/lodash");
43
+ var import_account = require("@xyo-network/account");
44
+ var import_address_payload_plugin = require("@xyo-network/address-payload-plugin");
45
+ var import_archivist_model = require("@xyo-network/archivist-model");
46
+ var import_boundwitness_builder3 = require("@xyo-network/boundwitness-builder");
47
+ var import_config_payload_plugin = require("@xyo-network/config-payload-plugin");
48
+ var import_core2 = require("@xyo-network/core");
49
+ var import_error = require("@xyo-network/error");
50
+ var import_manifest_model = require("@xyo-network/manifest-model");
51
+ var import_module_model = require("@xyo-network/module-model");
52
+ var import_module_resolver = require("@xyo-network/module-resolver");
53
+ var import_payload_builder2 = require("@xyo-network/payload-builder");
54
+ var import_promise = require("@xyo-network/promise");
55
+ var import_query_payload_plugin = require("@xyo-network/query-payload-plugin");
56
+ var import_shared = require("@xyo-network/shared");
57
+
58
+ // src/BaseEmitter.ts
59
+ var import_core = require("@xyo-network/core");
60
+ var import_module_events = require("@xyo-network/module-events");
61
+ var _BaseEmitter = class _BaseEmitter extends import_core.Base {
62
+ //just here to query types
63
+ eventData = {};
64
+ events;
65
+ constructor(params) {
66
+ super(params);
67
+ this.events = new import_module_events.Events();
68
+ }
69
+ clearListeners(eventNames) {
70
+ return this.events.clearListeners(eventNames);
71
+ }
72
+ emit(eventName, eventArgs) {
73
+ return this.events.emit(eventName, eventArgs);
74
+ }
75
+ emitSerial(eventName, eventArgs) {
76
+ return this.events.emitSerial(eventName, eventArgs);
77
+ }
78
+ listenerCount(eventNames) {
79
+ return this.events.listenerCount(eventNames);
80
+ }
81
+ off(eventNames, listener) {
82
+ return this.events.off(eventNames, listener);
83
+ }
84
+ offAny(listener) {
85
+ return this.events.offAny(listener);
86
+ }
87
+ on(eventNames, listener) {
88
+ return this.events.on(eventNames, listener);
89
+ }
90
+ onAny(listener) {
91
+ return this.events.onAny(listener);
92
+ }
93
+ once(eventName, listener) {
94
+ return this.events.once(eventName, listener);
95
+ }
96
+ };
97
+ __name(_BaseEmitter, "BaseEmitter");
98
+ var BaseEmitter = _BaseEmitter;
99
+
100
+ // src/Error.ts
101
+ var import_payload_builder = require("@xyo-network/payload-builder");
102
+ var import_payload_model = require("@xyo-network/payload-model");
103
+ var _ModuleErrorBuilder = class _ModuleErrorBuilder extends import_payload_builder.PayloadBuilder {
104
+ _message;
105
+ _name;
106
+ _query;
107
+ _sources;
108
+ constructor() {
109
+ super({
110
+ schema: import_payload_model.ModuleErrorSchema
111
+ });
112
+ }
113
+ build() {
114
+ return {
115
+ message: this._message,
116
+ name: this._name,
117
+ query: this._query,
118
+ schema: import_payload_model.ModuleErrorSchema,
119
+ sources: this._sources
120
+ };
121
+ }
122
+ message(message) {
123
+ this._message = message;
124
+ return this;
125
+ }
126
+ name(name) {
127
+ this._name = name;
128
+ return this;
129
+ }
130
+ query(query) {
131
+ this._query = query;
132
+ return this;
133
+ }
134
+ sources(sources) {
135
+ this._sources = sources;
136
+ return this;
137
+ }
138
+ };
139
+ __name(_ModuleErrorBuilder, "ModuleErrorBuilder");
140
+ var ModuleErrorBuilder = _ModuleErrorBuilder;
141
+
142
+ // src/QueryValidator/ModuleConfigQueryValidator.ts
143
+ var import_boundwitness_builder = require("@xyo-network/boundwitness-builder");
144
+ var delimiter = "";
145
+ var _ModuleConfigQueryValidator = class _ModuleConfigQueryValidator {
146
+ allowed = {};
147
+ disallowed = {};
148
+ hasAllowedRules;
149
+ hasDisallowedRules;
150
+ hasRules;
151
+ constructor(config) {
152
+ var _a, _b, _c, _d;
153
+ if ((_a = config == null ? void 0 : config.security) == null ? void 0 : _a.allowed) {
154
+ Object.entries((_b = config.security) == null ? void 0 : _b.allowed).forEach(([schema, addresses]) => {
155
+ this.allowed[schema] = addresses.map(toAddressesString);
156
+ });
157
+ }
158
+ if ((_c = config == null ? void 0 : config.security) == null ? void 0 : _c.disallowed) {
159
+ Object.entries((_d = config.security) == null ? void 0 : _d.disallowed).forEach(([schema, addresses]) => {
160
+ this.disallowed[schema] = addresses.map(toAddressesString);
161
+ });
162
+ }
163
+ this.hasAllowedRules = Object.keys(this.allowed).length > 0;
164
+ this.hasDisallowedRules = Object.keys(this.disallowed).length > 0;
165
+ this.hasRules = this.hasAllowedRules || this.hasDisallowedRules;
166
+ }
167
+ queryable = async (query, payloads) => {
168
+ if (!this.hasRules)
169
+ return true;
170
+ const addresses = query.addresses;
171
+ if (!addresses.length)
172
+ return false;
173
+ const wrapper = import_boundwitness_builder.QueryBoundWitnessWrapper.parseQuery(query, payloads);
174
+ const schema = (await wrapper.getQuery()).schema;
175
+ return this.queryAllowed(schema, addresses) && !this.queryDisallowed(schema, addresses);
176
+ };
177
+ queryAllowed = (schema, addresses) => {
178
+ var _a, _b;
179
+ if (!this.hasAllowedRules)
180
+ return true;
181
+ if (addresses.length > 1) {
182
+ const signatories = toAddressesString(addresses);
183
+ const validCosigners = (_b = (_a = this.allowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(signatories);
184
+ if (validCosigners)
185
+ return true;
186
+ }
187
+ return addresses.every((address) => {
188
+ var _a2, _b2;
189
+ return ((_b2 = (_a2 = this.allowed) == null ? void 0 : _a2[schema]) == null ? void 0 : _b2.includes(address)) || false;
190
+ });
191
+ };
192
+ queryDisallowed = (schema, addresses) => {
193
+ if (!this.hasDisallowedRules)
194
+ return false;
195
+ return addresses.some((address) => {
196
+ var _a, _b;
197
+ return (_b = (_a = this.disallowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(address);
198
+ });
199
+ };
200
+ };
201
+ __name(_ModuleConfigQueryValidator, "ModuleConfigQueryValidator");
202
+ var ModuleConfigQueryValidator = _ModuleConfigQueryValidator;
203
+ var toAddressesString = /* @__PURE__ */ __name((addresses) => {
204
+ return Array.isArray(addresses) ? addresses.sort().map((address) => address.toLowerCase()).join(delimiter) : addresses.toLowerCase();
205
+ }, "toAddressesString");
206
+
207
+ // src/QueryValidator/SupportedQueryValidator.ts
208
+ var import_boundwitness_builder2 = require("@xyo-network/boundwitness-builder");
209
+ var isQuerySupportedByModule = /* @__PURE__ */ __name(async (mod, query, payloads) => {
210
+ const wrapper = import_boundwitness_builder2.QueryBoundWitnessWrapper.parseQuery(query, payloads);
211
+ const schema = (await wrapper.getQuery()).schema;
212
+ return mod.queries.includes(schema);
213
+ }, "isQuerySupportedByModule");
214
+ var _SupportedQueryValidator = class _SupportedQueryValidator {
215
+ mod;
216
+ constructor(mod) {
217
+ this.mod = mod;
218
+ this.queryable = (query, payloads) => {
219
+ return isQuerySupportedByModule(this.mod, query, payloads);
220
+ };
221
+ }
222
+ queryable;
223
+ };
224
+ __name(_SupportedQueryValidator, "SupportedQueryValidator");
225
+ var SupportedQueryValidator = _SupportedQueryValidator;
226
+
227
+ // src/AbstractModule.ts
228
+ var _AbstractModule = class _AbstractModule extends BaseEmitter {
229
+ downResolver = new import_module_resolver.CompositeModuleResolver();
230
+ upResolver = new import_module_resolver.CompositeModuleResolver();
231
+ _account = void 0;
232
+ _baseModuleQueryAccountPaths = {
233
+ [import_module_model.ModuleAddressQuerySchema]: "1",
234
+ [import_module_model.ModuleDescribeQuerySchema]: "4",
235
+ [import_module_model.ModuleDiscoverQuerySchema]: "2",
236
+ [import_module_model.ModuleManifestQuerySchema]: "5",
237
+ [import_module_model.ModuleSubscribeQuerySchema]: "3"
238
+ };
239
+ _queryAccounts = {
240
+ [import_module_model.ModuleAddressQuerySchema]: void 0,
241
+ [import_module_model.ModuleDescribeQuerySchema]: void 0,
242
+ [import_module_model.ModuleDiscoverQuerySchema]: void 0,
243
+ [import_module_model.ModuleManifestQuerySchema]: void 0,
244
+ [import_module_model.ModuleSubscribeQuerySchema]: void 0
245
+ };
246
+ _startPromise = void 0;
247
+ _started = void 0;
248
+ moduleConfigQueryValidator;
249
+ supportedQueryValidator;
250
+ _busyCount = 0;
251
+ constructor(privateConstructorKey, params, account) {
252
+ (0, import_assert.assertEx)(_AbstractModule.privateConstructorKey === privateConstructorKey, "Use create function instead of constructor");
253
+ const mutatedParams = {
254
+ ...params
255
+ };
256
+ super(mutatedParams);
257
+ this._account = account;
258
+ this.supportedQueryValidator = new SupportedQueryValidator(this).queryable;
259
+ this.moduleConfigQueryValidator = new ModuleConfigQueryValidator(mutatedParams == null ? void 0 : mutatedParams.config).queryable;
260
+ }
261
+ static get configSchema() {
262
+ return this.configSchemas[0];
263
+ }
264
+ get account() {
265
+ return (0, import_assert.assertEx)(this._account, "Missing account");
266
+ }
267
+ get address() {
268
+ return this.account.address;
269
+ }
270
+ get allowAnonymous() {
271
+ var _a;
272
+ return !!((_a = this.config.security) == null ? void 0 : _a.allowAnonymous);
273
+ }
274
+ get config() {
275
+ return this.params.config;
276
+ }
277
+ get ephemeralQueryAccountEnabled() {
278
+ return !!this.params.ephemeralQueryAccountEnabled;
279
+ }
280
+ get queries() {
281
+ return [
282
+ import_module_model.ModuleDiscoverQuerySchema,
283
+ import_module_model.ModuleAddressQuerySchema,
284
+ import_module_model.ModuleSubscribeQuerySchema,
285
+ import_module_model.ModuleDescribeQuerySchema,
286
+ import_module_model.ModuleManifestQuerySchema
287
+ ];
288
+ }
289
+ get queryAccountPaths() {
290
+ return {
291
+ ...this._baseModuleQueryAccountPaths,
292
+ ...this._queryAccountPaths
293
+ };
294
+ }
295
+ get queryAccounts() {
296
+ return this._queryAccounts;
297
+ }
298
+ get timestamp() {
299
+ return this.config.timestamp ?? false;
300
+ }
301
+ static _getRootFunction(funcName) {
302
+ let anyThis = this;
303
+ while (anyThis.__proto__[funcName]) {
304
+ anyThis = anyThis.__proto__;
305
+ }
306
+ return anyThis[funcName];
307
+ }
308
+ static _noOverride(functionName) {
309
+ const thisFunc = this[functionName];
310
+ const rootFunc = this._getRootFunction(functionName);
311
+ (0, import_assert.assertEx)(thisFunc === rootFunc, `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
312
+ }
313
+ static async create(params) {
314
+ var _a, _b, _c, _d;
315
+ this._noOverride("create");
316
+ if (!this.configSchemas || this.configSchemas.length === 0) {
317
+ throw Error(`Missing configSchema [${(_a = params == null ? void 0 : params.config) == null ? void 0 : _a.schema}][${this.name}]`);
318
+ }
319
+ const { account, config, wallet } = params ?? {};
320
+ const { accountDerivationPath } = config ?? {};
321
+ (0, import_assert.assertEx)(!(!!account && !!wallet), `Specifying both {account} and {wallet} are not allowed [${config == null ? void 0 : config.schema}] [${account === "random" ? "random" : account == null ? void 0 : account.address}, ${wallet == null ? void 0 : wallet.address}]`);
322
+ const schema = ((_b = params == null ? void 0 : params.config) == null ? void 0 : _b.schema) ?? this.configSchema;
323
+ const allowedSchemas = this.configSchemas;
324
+ (0, import_assert.assertEx)(allowedSchemas.filter((allowedSchema) => allowedSchema === schema).length > 0, `Bad Config Schema [Received ${schema}] [Expected ${JSON.stringify(allowedSchemas)}]`);
325
+ const mutatedConfig = {
326
+ ...params == null ? void 0 : params.config,
327
+ schema
328
+ };
329
+ (_c = params == null ? void 0 : params.logger) == null ? void 0 : _c.debug(`config: ${JSON.stringify(mutatedConfig, null, 2)}`);
330
+ const mutatedParams = {
331
+ ...params,
332
+ config: mutatedConfig
333
+ };
334
+ const activeLogger = (params == null ? void 0 : params.logger) ?? _AbstractModule.defaultLogger;
335
+ const generatedAccount = await _AbstractModule.determineAccount({
336
+ account,
337
+ accountDerivationPath,
338
+ wallet
339
+ });
340
+ const address = generatedAccount.address;
341
+ mutatedParams.logger = activeLogger ? new import_shared.IdLogger(activeLogger, () => `0x${address}`) : void 0;
342
+ const newModule = new this(_AbstractModule.privateConstructorKey, mutatedParams, generatedAccount);
343
+ if (!_AbstractModule.enableLazyLoad) {
344
+ await ((_d = newModule.start) == null ? void 0 : _d.call(newModule));
345
+ }
346
+ return newModule;
347
+ }
348
+ static async determineAccount({ account, accountDerivationPath, wallet }) {
349
+ if (wallet) {
350
+ return (0, import_assert.assertEx)(accountDerivationPath ? await wallet.derivePath(accountDerivationPath) : wallet, "Failed to derive account from path");
351
+ } else if (account === "random") {
352
+ return await import_account.HDWallet.random();
353
+ } else if (account) {
354
+ return account;
355
+ } else {
356
+ console.warn("AbstractModule.determineAccount: No account provided - Creating Random account");
357
+ return await import_account.HDWallet.random();
358
+ }
359
+ }
360
+ static factory(params) {
361
+ return import_module_model.ModuleFactory.withParams(this, params);
362
+ }
363
+ _getRootFunction(funcName) {
364
+ let anyThis = this;
365
+ while (anyThis.__proto__[funcName]) {
366
+ anyThis = anyThis.__proto__;
367
+ }
368
+ return anyThis[funcName];
369
+ }
370
+ _noOverride(functionName) {
371
+ const thisFunc = this[functionName];
372
+ const rootFunc = this._getRootFunction(functionName);
373
+ (0, import_assert.assertEx)(thisFunc === rootFunc, `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
374
+ }
375
+ async busy(closure) {
376
+ if (this._busyCount <= 0) {
377
+ this._busyCount = 0;
378
+ const args = {
379
+ busy: true,
380
+ module: this
381
+ };
382
+ await this.emit("moduleBusy", args);
383
+ }
384
+ this._busyCount++;
385
+ try {
386
+ return await closure();
387
+ } finally {
388
+ this._busyCount--;
389
+ if (this._busyCount <= 0) {
390
+ this._busyCount = 0;
391
+ const args = {
392
+ busy: false,
393
+ module: this
394
+ };
395
+ await this.emit("moduleBusy", args);
396
+ }
397
+ }
398
+ }
399
+ emit(eventName, eventArgs) {
400
+ return super.emit(eventName, eventArgs);
401
+ }
402
+ previousHash() {
403
+ return this.account.previousHash;
404
+ }
405
+ async query(query, payloads, queryConfig) {
406
+ this._noOverride("query");
407
+ return await this.busy(async () => {
408
+ const resultPayloads = [];
409
+ const errorPayloads = [];
410
+ const queryAccount = this.ephemeralQueryAccountEnabled ? await import_account.HDWallet.random() : void 0;
411
+ try {
412
+ await this.started("throw");
413
+ if (!this.allowAnonymous) {
414
+ if (query.addresses.length === 0) {
415
+ throw Error(`Anonymous Queries not allowed, but running anyway [${this.config.name}], [${this.address}]`);
416
+ }
417
+ }
418
+ resultPayloads.push(...await this.queryHandler((0, import_assert.assertEx)(import_boundwitness_builder3.QueryBoundWitnessWrapper.unwrap(query)), payloads, queryConfig));
419
+ } catch (ex) {
420
+ await (0, import_error.handleErrorAsync)(ex, async (error) => {
421
+ errorPayloads.push(new ModuleErrorBuilder().sources([
422
+ await import_core2.PayloadHasher.hashAsync(query)
423
+ ]).name(this.config.name ?? "<Unknown>").query(query.schema).message(error.message).build());
424
+ });
425
+ }
426
+ if (this.timestamp) {
427
+ const timestamp = {
428
+ schema: "network.xyo.timestamp",
429
+ timestamp: Date.now()
430
+ };
431
+ resultPayloads.push(timestamp);
432
+ }
433
+ const result = await this.bindQueryResult(query, resultPayloads, queryAccount ? [
434
+ queryAccount
435
+ ] : [], errorPayloads);
436
+ const args = {
437
+ module: this,
438
+ payloads,
439
+ query,
440
+ result
441
+ };
442
+ await this.emit("moduleQueried", args);
443
+ return result;
444
+ });
445
+ }
446
+ queryable(query, payloads, queryConfig) {
447
+ if (!this.started("warn"))
448
+ return false;
449
+ const configValidator = queryConfig ? new ModuleConfigQueryValidator(Object.assign({}, this.config, queryConfig)).queryable : this.moduleConfigQueryValidator;
450
+ const validators = [
451
+ this.supportedQueryValidator,
452
+ configValidator
453
+ ];
454
+ return validators.every((validator) => validator(query, payloads));
455
+ }
456
+ async resolve(nameOrAddressOrFilter, options) {
457
+ const direction = (options == null ? void 0 : options.direction) ?? "all";
458
+ const up = direction === "up" || direction === "all";
459
+ const down = direction === "down" || direction === "all";
460
+ switch (typeof nameOrAddressOrFilter) {
461
+ case "string": {
462
+ return (down ? await this.downResolver.resolve(nameOrAddressOrFilter, options) : void 0) ?? (up ? await this.upResolver.resolve(nameOrAddressOrFilter, options) : void 0);
463
+ }
464
+ default: {
465
+ const filter = nameOrAddressOrFilter;
466
+ return [
467
+ ...down ? await this.downResolver.resolve(filter, options) : [],
468
+ ...up ? await this.upResolver.resolve(filter, options) : []
469
+ ].filter(import_module_model.duplicateModules);
470
+ }
471
+ }
472
+ }
473
+ start(_timeout) {
474
+ this._startPromise = this._startPromise ?? this.startHandler();
475
+ return this._startPromise;
476
+ }
477
+ async started(notStartedAction = "log", tryStart = true) {
478
+ const started = await this._started;
479
+ if (started === true) {
480
+ return true;
481
+ }
482
+ if (!started) {
483
+ this._started = (async () => {
484
+ var _a, _b, _c;
485
+ if (tryStart) {
486
+ try {
487
+ await this.start();
488
+ return true;
489
+ } catch (ex) {
490
+ (0, import_error.handleError)(ex, (error) => {
491
+ var _a2;
492
+ (_a2 = this.logger) == null ? void 0 : _a2.warn(`Autostart of Module Failed: ${error.message})`);
493
+ this._started = void 0;
494
+ });
495
+ }
496
+ }
497
+ switch (notStartedAction) {
498
+ case "throw":
499
+ throw Error(`Module not Started [${this.address}]`);
500
+ case "warn":
501
+ (_a = this.logger) == null ? void 0 : _a.warn("Module not started");
502
+ break;
503
+ case "error":
504
+ (_b = this.logger) == null ? void 0 : _b.error("Module not started");
505
+ break;
506
+ case "none":
507
+ break;
508
+ case "log":
509
+ default: {
510
+ (_c = this.logger) == null ? void 0 : _c.log("Module not started");
511
+ break;
512
+ }
513
+ }
514
+ return false;
515
+ })();
516
+ }
517
+ if (!this._started) {
518
+ throw "Failed to create start promise";
519
+ }
520
+ return await this._started;
521
+ }
522
+ async stop(_timeout) {
523
+ return await this.busy(async () => {
524
+ const result = await this.stopHandler();
525
+ this._started = void 0;
526
+ this._startPromise = void 0;
527
+ return result;
528
+ });
529
+ }
530
+ bindHashes(hashes, schema, account) {
531
+ const promise = new import_promise.PromiseEx((resolve) => {
532
+ const result = this.bindHashesInternal(hashes, schema, account);
533
+ resolve == null ? void 0 : resolve(result);
534
+ return result;
535
+ }, account);
536
+ return promise;
537
+ }
538
+ async bindHashesInternal(hashes, schema, account) {
539
+ var _a;
540
+ const builder = new import_boundwitness_builder3.BoundWitnessBuilder().hashes(hashes, schema).witness(this.account);
541
+ const result = (await (account ? builder.witness(account) : builder).build())[0];
542
+ (_a = this.logger) == null ? void 0 : _a.debug(`result: ${JSON.stringify(result, null, 2)}`);
543
+ return result;
544
+ }
545
+ bindQuery(query, payloads, account) {
546
+ const promise = new import_promise.PromiseEx(async (resolve) => {
547
+ const result = await this.bindQueryInternal(query, payloads, account);
548
+ resolve == null ? void 0 : resolve(result);
549
+ return result;
550
+ }, account);
551
+ return promise;
552
+ }
553
+ async bindQueryInternal(query, payloads, account) {
554
+ const builder = new import_boundwitness_builder3.QueryBoundWitnessBuilder().payloads(payloads).witness(this.account).query(query);
555
+ const result = await (account ? builder.witness(account) : builder).build();
556
+ return result;
557
+ }
558
+ async bindQueryResult(query, payloads, additionalWitnesses = [], errors) {
559
+ const builder = new import_boundwitness_builder3.BoundWitnessBuilder().payloads(payloads).errors(errors);
560
+ const queryWitnessAccount = this.queryAccounts[query.schema];
561
+ const witnesses = [
562
+ this.account,
563
+ queryWitnessAccount,
564
+ ...additionalWitnesses
565
+ ].filter(import_exists.exists);
566
+ builder.witnesses(witnesses);
567
+ const result = [
568
+ (await builder.build())[0],
569
+ payloads,
570
+ errors ?? []
571
+ ];
572
+ return result;
573
+ }
574
+ commitArchivist = () => this.getArchivist("commit");
575
+ async describeHandler() {
576
+ var _a;
577
+ const description = {
578
+ address: this.address,
579
+ queries: this.queries,
580
+ schema: import_module_model.ModuleDescriptionSchema
581
+ };
582
+ if ((_a = this.config) == null ? void 0 : _a.name) {
583
+ description.name = this.config.name;
584
+ }
585
+ const discover = await this.discoverHandler();
586
+ description.children = (0, import_lodash.compact)((discover == null ? void 0 : discover.map((payload) => {
587
+ const address = payload.schema === import_address_payload_plugin.AddressSchema ? payload.address : void 0;
588
+ return address != this.address ? address : void 0;
589
+ })) ?? []);
590
+ return description;
591
+ }
592
+ discoverHandler() {
593
+ var _a;
594
+ const config = this.config;
595
+ const address = new import_payload_builder2.PayloadBuilder({
596
+ schema: import_address_payload_plugin.AddressSchema
597
+ }).fields({
598
+ address: this.address,
599
+ name: (_a = this.config) == null ? void 0 : _a.name
600
+ }).build();
601
+ const queries = this.queries.map((query) => {
602
+ return new import_payload_builder2.PayloadBuilder({
603
+ schema: import_query_payload_plugin.QuerySchema
604
+ }).fields({
605
+ query
606
+ }).build();
607
+ });
608
+ const configSchema = {
609
+ config: config.schema,
610
+ schema: import_config_payload_plugin.ConfigSchema
611
+ };
612
+ return (0, import_lodash.compact)([
613
+ config,
614
+ configSchema,
615
+ address,
616
+ ...queries
617
+ ]);
618
+ }
619
+ async getArchivist(kind) {
620
+ var _a, _b;
621
+ if (!this.config.archivist)
622
+ return void 0;
623
+ const filter = typeof this.config.archivist === "string" || this.config.archivist instanceof String ? this.config.archivist : (_b = (_a = this.config) == null ? void 0 : _a.archivist) == null ? void 0 : _b[kind];
624
+ const resolved = await this.upResolver.resolve(filter);
625
+ return (0, import_archivist_model.asArchivistInstance)(resolved);
626
+ }
627
+ async initializeQueryAccounts() {
628
+ var _a, _b;
629
+ const paths = Object.values(this.queryAccountPaths).filter(import_exists.exists);
630
+ const distinctPaths = new Set(paths);
631
+ (0, import_assert.assertEx)(distinctPaths.size === paths.length, `${((_a = this.config) == null ? void 0 : _a.name) ? this.config.name + ": " : ""}Duplicate query account paths`);
632
+ const wallet = this.account;
633
+ if (wallet == null ? void 0 : wallet.derivePath) {
634
+ for (const key in this.queryAccountPaths) {
635
+ if (Object.prototype.hasOwnProperty.call(this.queryAccountPaths, key)) {
636
+ const query = key;
637
+ const queryAccountPath = this.queryAccountPaths[query];
638
+ if (queryAccountPath) {
639
+ this._queryAccounts[query] = await ((_b = wallet.derivePath) == null ? void 0 : _b.call(wallet, queryAccountPath));
640
+ }
641
+ }
642
+ }
643
+ }
644
+ }
645
+ manifestHandler(_ignoreAddresses) {
646
+ const name = this.config.name ?? "Anonymous";
647
+ return {
648
+ config: {
649
+ name,
650
+ ...this.config
651
+ },
652
+ schema: import_manifest_model.ModuleManifestPayloadSchema
653
+ };
654
+ }
655
+ moduleAddressHandler() {
656
+ const queryAccounts = Object.entries(this.queryAccounts).filter((value) => {
657
+ return (0, import_exists.exists)(value[1]);
658
+ }).map(([name2, account]) => {
659
+ const address2 = account.address;
660
+ const previousHash2 = account.previousHash;
661
+ return [
662
+ {
663
+ address: address2,
664
+ name: name2,
665
+ schema: import_address_payload_plugin.AddressSchema
666
+ },
667
+ {
668
+ address: address2,
669
+ previousHash: previousHash2,
670
+ schema: import_module_model.AddressPreviousHashSchema
671
+ }
672
+ ];
673
+ });
674
+ const address = this.address;
675
+ const name = this.config.name;
676
+ const previousHash = this.address;
677
+ const moduleAccount = name ? {
678
+ address,
679
+ name,
680
+ schema: import_address_payload_plugin.AddressSchema
681
+ } : {
682
+ address,
683
+ schema: import_address_payload_plugin.AddressSchema
684
+ };
685
+ const moduleAccountPreviousHash = previousHash ? {
686
+ address,
687
+ previousHash,
688
+ schema: import_module_model.AddressPreviousHashSchema
689
+ } : {
690
+ address,
691
+ schema: import_module_model.AddressPreviousHashSchema
692
+ };
693
+ return [
694
+ moduleAccount,
695
+ moduleAccountPreviousHash,
696
+ ...queryAccounts
697
+ ].flat();
698
+ }
699
+ async queryHandler(query, payloads, queryConfig) {
700
+ await this.started("throw");
701
+ const wrapper = import_boundwitness_builder3.QueryBoundWitnessWrapper.parseQuery(query, payloads);
702
+ const queryPayload = await wrapper.getQuery();
703
+ (0, import_assert.assertEx)(this.queryable(query, payloads, queryConfig));
704
+ const resultPayloads = [];
705
+ switch (queryPayload.schema) {
706
+ case import_module_model.ModuleManifestQuerySchema: {
707
+ resultPayloads.push(await this.manifestHandler());
708
+ break;
709
+ }
710
+ case import_module_model.ModuleDiscoverQuerySchema: {
711
+ resultPayloads.push(...await this.discoverHandler());
712
+ break;
713
+ }
714
+ case import_module_model.ModuleDescribeQuerySchema: {
715
+ resultPayloads.push(await this.describeHandler());
716
+ break;
717
+ }
718
+ case import_module_model.ModuleAddressQuerySchema: {
719
+ resultPayloads.push(...await this.moduleAddressHandler());
720
+ break;
721
+ }
722
+ case import_module_model.ModuleSubscribeQuerySchema: {
723
+ this.subscribeHandler();
724
+ break;
725
+ }
726
+ default:
727
+ throw Error(`Unsupported Query [${queryPayload.schema}]`);
728
+ }
729
+ return resultPayloads;
730
+ }
731
+ readArchivist = () => this.getArchivist("read");
732
+ async startHandler() {
733
+ this.validateConfig();
734
+ await this.initializeQueryAccounts();
735
+ this._started = true;
736
+ return true;
737
+ }
738
+ stopHandler(_timeout) {
739
+ this._started = void 0;
740
+ return true;
741
+ }
742
+ subscribeHandler() {
743
+ return;
744
+ }
745
+ validateConfig(config, parents = []) {
746
+ return Object.entries(config ?? this.config ?? {}).reduce((valid, [key, value]) => {
747
+ var _a, _b;
748
+ switch (typeof value) {
749
+ case "function":
750
+ (_a = this.logger) == null ? void 0 : _a.warn(`Fields of type function not allowed in config [${parents == null ? void 0 : parents.join(".")}.${key}]`);
751
+ return false;
752
+ case "object": {
753
+ if (Array.isArray(value)) {
754
+ return value.reduce((valid2, value2) => {
755
+ return this.validateConfig(value2, [
756
+ ...parents,
757
+ key
758
+ ]) && valid2;
759
+ }, true) && valid;
760
+ }
761
+ if (!(0, import_module_model.serializableField)(value)) {
762
+ (_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}]`);
763
+ return false;
764
+ }
765
+ return value ? this.validateConfig(value, [
766
+ ...parents,
767
+ key
768
+ ]) && valid : true;
769
+ }
770
+ default:
771
+ return valid;
772
+ }
773
+ }, true);
774
+ }
775
+ writeArchivist = () => this.getArchivist("write");
776
+ };
777
+ __name(_AbstractModule, "AbstractModule");
778
+ __publicField(_AbstractModule, "configSchemas");
779
+ __publicField(_AbstractModule, "enableLazyLoad", false);
780
+ __publicField(_AbstractModule, "privateConstructorKey", Date.now().toString());
781
+ var AbstractModule = _AbstractModule;
782
+
783
+ // src/AbstractModuleInstance.ts
784
+ var import_assert2 = require("@xylabs/assert");
785
+ var _AbstractModuleInstance = class _AbstractModuleInstance extends AbstractModule {
786
+ constructor(privateConstructorKey, params, account) {
787
+ (0, import_assert2.assertEx)(AbstractModule.privateConstructorKey === privateConstructorKey, "Use create function instead of constructor");
788
+ const mutatedParams = {
789
+ ...params
790
+ };
791
+ super(privateConstructorKey, mutatedParams, account);
792
+ this.upResolver.add(this);
793
+ this.downResolver.add(this);
794
+ }
795
+ describe() {
796
+ return this.busy(async () => {
797
+ return await this.describeHandler();
798
+ });
799
+ }
800
+ discover() {
801
+ return this.busy(async () => {
802
+ return await this.discoverHandler();
803
+ });
804
+ }
805
+ manifest(ignoreAddresses) {
806
+ return this.busy(async () => {
807
+ return await this.manifestHandler(ignoreAddresses);
808
+ });
809
+ }
810
+ moduleAddress() {
811
+ return this.busy(async () => {
812
+ return await this.moduleAddressHandler();
813
+ });
814
+ }
815
+ subscribe(_queryAccount) {
816
+ return this.subscribeHandler();
817
+ }
818
+ };
819
+ __name(_AbstractModuleInstance, "AbstractModuleInstance");
820
+ var AbstractModuleInstance = _AbstractModuleInstance;
23
821
  // Annotate the CommonJS export names for ESM import in node:
24
822
  0 && (module.exports = {
25
- ...require("./AbstractModule"),
26
- ...require("./AbstractModuleInstance"),
27
- ...require("./BaseEmitter"),
28
- ...require("./Error"),
29
- ...require("./QueryValidator")
823
+ AbstractModule,
824
+ AbstractModuleInstance,
825
+ BaseEmitter,
826
+ ModuleConfigQueryValidator,
827
+ ModuleErrorBuilder,
828
+ SupportedQueryValidator,
829
+ isQuerySupportedByModule
30
830
  });
31
831
  //# sourceMappingURL=index.js.map