@xyo-network/module-abstract 2.106.0 → 2.107.1

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