@xyo-network/bridge-pub-sub 2.99.2 → 2.99.3

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 (149) hide show
  1. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.cts +11 -0
  2. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.cts.map +1 -0
  3. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.mts +11 -0
  4. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.mts.map +1 -0
  5. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.ts +11 -0
  6. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.ts.map +1 -0
  7. package/dist/neutral/AbstractModuleHost/index.d.cts +2 -0
  8. package/dist/neutral/AbstractModuleHost/index.d.cts.map +1 -0
  9. package/dist/neutral/AbstractModuleHost/index.d.mts +2 -0
  10. package/dist/neutral/AbstractModuleHost/index.d.mts.map +1 -0
  11. package/dist/neutral/AbstractModuleHost/index.d.ts +2 -0
  12. package/dist/neutral/AbstractModuleHost/index.d.ts.map +1 -0
  13. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts +144 -0
  14. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts.map +1 -0
  15. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts +144 -0
  16. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts.map +1 -0
  17. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts +144 -0
  18. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts.map +1 -0
  19. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts +33 -0
  20. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -0
  21. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts +33 -0
  22. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -0
  23. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts +33 -0
  24. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -0
  25. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts +72 -0
  26. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -0
  27. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts +72 -0
  28. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -0
  29. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts +72 -0
  30. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -0
  31. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.cts +12 -0
  32. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.cts.map +1 -0
  33. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.mts +12 -0
  34. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.mts.map +1 -0
  35. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.ts +12 -0
  36. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.ts.map +1 -0
  37. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.cts +2 -0
  38. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.cts.map +1 -0
  39. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.mts +2 -0
  40. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.mts.map +1 -0
  41. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.ts +2 -0
  42. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.ts.map +1 -0
  43. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts +19 -0
  44. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts.map +1 -0
  45. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts +19 -0
  46. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts.map +1 -0
  47. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts +19 -0
  48. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts.map +1 -0
  49. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.cts +2 -0
  50. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.cts.map +1 -0
  51. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.mts +2 -0
  52. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.mts.map +1 -0
  53. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.ts +2 -0
  54. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.ts.map +1 -0
  55. package/dist/neutral/AsyncQueryBus/index.d.cts +6 -0
  56. package/dist/neutral/AsyncQueryBus/index.d.cts.map +1 -0
  57. package/dist/neutral/AsyncQueryBus/index.d.mts +6 -0
  58. package/dist/neutral/AsyncQueryBus/index.d.mts.map +1 -0
  59. package/dist/neutral/AsyncQueryBus/index.d.ts +6 -0
  60. package/dist/neutral/AsyncQueryBus/index.d.ts.map +1 -0
  61. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts +14 -0
  62. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts.map +1 -0
  63. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts +14 -0
  64. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts.map +1 -0
  65. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts +14 -0
  66. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts.map +1 -0
  67. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts +9 -0
  68. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts.map +1 -0
  69. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts +9 -0
  70. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts.map +1 -0
  71. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts +9 -0
  72. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts.map +1 -0
  73. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts +22 -0
  74. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts.map +1 -0
  75. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts +22 -0
  76. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts.map +1 -0
  77. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts +22 -0
  78. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts.map +1 -0
  79. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts +12 -0
  80. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts.map +1 -0
  81. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts +12 -0
  82. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts.map +1 -0
  83. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts +12 -0
  84. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts.map +1 -0
  85. package/dist/neutral/AsyncQueryBus/model/Params.d.cts +12 -0
  86. package/dist/neutral/AsyncQueryBus/model/Params.d.cts.map +1 -0
  87. package/dist/neutral/AsyncQueryBus/model/Params.d.mts +12 -0
  88. package/dist/neutral/AsyncQueryBus/model/Params.d.mts.map +1 -0
  89. package/dist/neutral/AsyncQueryBus/model/Params.d.ts +12 -0
  90. package/dist/neutral/AsyncQueryBus/model/Params.d.ts.map +1 -0
  91. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.cts +3 -0
  92. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.cts.map +1 -0
  93. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.mts +3 -0
  94. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.mts.map +1 -0
  95. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.ts +3 -0
  96. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.ts.map +1 -0
  97. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.cts +15 -0
  98. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.cts.map +1 -0
  99. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.mts +15 -0
  100. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.mts.map +1 -0
  101. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.ts +15 -0
  102. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.ts.map +1 -0
  103. package/dist/neutral/AsyncQueryBus/model/index.d.cts +8 -0
  104. package/dist/neutral/AsyncQueryBus/model/index.d.cts.map +1 -0
  105. package/dist/neutral/AsyncQueryBus/model/index.d.mts +8 -0
  106. package/dist/neutral/AsyncQueryBus/model/index.d.mts.map +1 -0
  107. package/dist/neutral/AsyncQueryBus/model/index.d.ts +8 -0
  108. package/dist/neutral/AsyncQueryBus/model/index.d.ts.map +1 -0
  109. package/dist/neutral/Config.d.cts +15 -0
  110. package/dist/neutral/Config.d.cts.map +1 -0
  111. package/dist/neutral/Config.d.mts +15 -0
  112. package/dist/neutral/Config.d.mts.map +1 -0
  113. package/dist/neutral/Config.d.ts +15 -0
  114. package/dist/neutral/Config.d.ts.map +1 -0
  115. package/dist/neutral/Params.d.cts +8 -0
  116. package/dist/neutral/Params.d.cts.map +1 -0
  117. package/dist/neutral/Params.d.mts +8 -0
  118. package/dist/neutral/Params.d.mts.map +1 -0
  119. package/dist/neutral/Params.d.ts +8 -0
  120. package/dist/neutral/Params.d.ts.map +1 -0
  121. package/dist/neutral/PubSubBridge.d.cts +34 -0
  122. package/dist/neutral/PubSubBridge.d.cts.map +1 -0
  123. package/dist/neutral/PubSubBridge.d.mts +34 -0
  124. package/dist/neutral/PubSubBridge.d.mts.map +1 -0
  125. package/dist/neutral/PubSubBridge.d.ts +34 -0
  126. package/dist/neutral/PubSubBridge.d.ts.map +1 -0
  127. package/dist/neutral/PubSubBridgeModuleResolver.d.cts +10 -0
  128. package/dist/neutral/PubSubBridgeModuleResolver.d.cts.map +1 -0
  129. package/dist/neutral/PubSubBridgeModuleResolver.d.mts +10 -0
  130. package/dist/neutral/PubSubBridgeModuleResolver.d.mts.map +1 -0
  131. package/dist/neutral/PubSubBridgeModuleResolver.d.ts +10 -0
  132. package/dist/neutral/PubSubBridgeModuleResolver.d.ts.map +1 -0
  133. package/dist/neutral/Schema.d.cts +3 -0
  134. package/dist/neutral/Schema.d.cts.map +1 -0
  135. package/dist/neutral/Schema.d.mts +3 -0
  136. package/dist/neutral/Schema.d.mts.map +1 -0
  137. package/dist/neutral/Schema.d.ts +3 -0
  138. package/dist/neutral/Schema.d.ts.map +1 -0
  139. package/dist/neutral/index.cjs +875 -0
  140. package/dist/neutral/index.cjs.map +1 -0
  141. package/dist/neutral/index.d.cts +8 -0
  142. package/dist/neutral/index.d.cts.map +1 -0
  143. package/dist/neutral/index.d.mts +8 -0
  144. package/dist/neutral/index.d.mts.map +1 -0
  145. package/dist/neutral/index.d.ts +8 -0
  146. package/dist/neutral/index.d.ts.map +1 -0
  147. package/dist/neutral/index.js +854 -0
  148. package/dist/neutral/index.js.map +1 -0
  149. package/package.json +32 -32
@@ -0,0 +1,875 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ AbstractModuleHost: () => AbstractModuleHost,
25
+ AsyncQueryBusClient: () => AsyncQueryBusClient,
26
+ AsyncQueryBusHost: () => AsyncQueryBusHost,
27
+ AsyncQueryBusModuleHost: () => AsyncQueryBusModuleHost,
28
+ AsyncQueryBusModuleProxy: () => AsyncQueryBusModuleProxy,
29
+ Pending: () => Pending,
30
+ PubSubBridge: () => PubSubBridge,
31
+ PubSubBridgeConfigSchema: () => PubSubBridgeConfigSchema,
32
+ PubSubBridgeModuleResolver: () => PubSubBridgeModuleResolver,
33
+ PubSubBridgeSchema: () => PubSubBridgeSchema
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+
37
+ // src/AbstractModuleHost/AbstractModuleHost.ts
38
+ var import_object = require("@xylabs/object");
39
+ var AbstractModuleHost = class extends import_object.Base {
40
+ static {
41
+ __name(this, "AbstractModuleHost");
42
+ }
43
+ };
44
+
45
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
46
+ var import_assert2 = require("@xylabs/assert");
47
+ var import_delay = require("@xylabs/delay");
48
+ var import_forget = require("@xylabs/forget");
49
+ var import_timer = require("@xylabs/timer");
50
+ var import_boundwitness_model = require("@xyo-network/boundwitness-model");
51
+ var import_diviner_boundwitness_model = require("@xyo-network/diviner-boundwitness-model");
52
+ var import_payload_builder = require("@xyo-network/payload-builder");
53
+ var import_lru_cache2 = require("lru-cache");
54
+
55
+ // src/AsyncQueryBus/AsyncQueryBusBase.ts
56
+ var import_assert = require("@xylabs/assert");
57
+ var import_object2 = require("@xylabs/object");
58
+ var import_archivist_model = require("@xyo-network/archivist-model");
59
+ var import_diviner_model = require("@xyo-network/diviner-model");
60
+ var import_module_model = require("@xyo-network/module-model");
61
+ var import_async_mutex = require("async-mutex");
62
+ var import_lru_cache = require("lru-cache");
63
+ var POLLING_FREQUENCY_MIN = 100;
64
+ var POLLING_FREQUENCY_MAX = 6e4;
65
+ var POLLING_FREQUENCY_DEFAULT = 1e3;
66
+ var AsyncQueryBusBase = class extends import_object2.Base {
67
+ static {
68
+ __name(this, "AsyncQueryBusBase");
69
+ }
70
+ _lastState;
71
+ _targetConfigs = {};
72
+ _targetQueries = {};
73
+ _lastResolveFailure = {};
74
+ _queriesArchivist;
75
+ _queriesDiviner;
76
+ _reResolveDelay = 1e3 * 5;
77
+ _resolveMutex = new import_async_mutex.Mutex();
78
+ _responsesArchivist;
79
+ _responsesDiviner;
80
+ constructor(params) {
81
+ super(params);
82
+ }
83
+ get config() {
84
+ return this.params.config;
85
+ }
86
+ get pollFrequency() {
87
+ const frequency = this.config?.pollFrequency ?? POLLING_FREQUENCY_DEFAULT;
88
+ if (frequency < POLLING_FREQUENCY_MIN || frequency > POLLING_FREQUENCY_MAX) {
89
+ return POLLING_FREQUENCY_DEFAULT;
90
+ }
91
+ return frequency;
92
+ }
93
+ get rootModule() {
94
+ return this.params.rootModule;
95
+ }
96
+ /**
97
+ * A cache of the last offset of the Diviner process per address
98
+ */
99
+ get lastState() {
100
+ const requiredConfig = {
101
+ max: 1e3,
102
+ ttl: 0
103
+ };
104
+ this._lastState = this._lastState ?? new import_lru_cache.LRUCache(requiredConfig);
105
+ return this._lastState;
106
+ }
107
+ async queriesArchivist() {
108
+ return await this._resolveMutex.runExclusive(async () => {
109
+ this._queriesArchivist = this._queriesArchivist ?? await this.resolve((0, import_assert.assertEx)(this.config?.intersect?.queries?.archivist, () => "No queries Archivist defined"), import_archivist_model.isArchivistInstance);
110
+ return this._queriesArchivist;
111
+ });
112
+ }
113
+ async queriesDiviner() {
114
+ return await this._resolveMutex.runExclusive(async () => {
115
+ this._queriesDiviner = this._queriesDiviner ?? await this.resolve((0, import_assert.assertEx)(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined"), import_diviner_model.isDivinerInstance);
116
+ return this._queriesDiviner;
117
+ });
118
+ }
119
+ async responsesArchivist() {
120
+ return await this._resolveMutex.runExclusive(async () => {
121
+ this._responsesArchivist = this._responsesArchivist ?? await this.resolve((0, import_assert.assertEx)(this.config?.intersect?.responses?.archivist, () => "No responses Archivist defined"), import_archivist_model.isArchivistInstance);
122
+ return this._responsesArchivist;
123
+ });
124
+ }
125
+ async responsesDiviner() {
126
+ return await this._resolveMutex.runExclusive(async () => {
127
+ this._responsesDiviner = this._responsesDiviner ?? await this.resolve((0, import_assert.assertEx)(this.config?.intersect?.responses?.boundWitnessDiviner, () => "No responses Diviner defined"), import_diviner_model.isDivinerInstance);
128
+ return this._responsesDiviner;
129
+ });
130
+ }
131
+ /**
132
+ * Commit the internal state of the process. This is similar
133
+ * to a transaction completion in a database and should only be called
134
+ * when results have been successfully persisted to the appropriate
135
+ * external stores.
136
+ * @param address The module address to commit the state for
137
+ * @param nextState The state to commit
138
+ */
139
+ async commitState(address, nextState) {
140
+ await Promise.resolve();
141
+ const lastState = this.lastState.get(address);
142
+ if (lastState && lastState >= nextState)
143
+ return;
144
+ this.lastState.set(address, nextState);
145
+ }
146
+ /**
147
+ * Retrieves the last state of the process. Used to recover state after
148
+ * preemptions, reboots, etc.
149
+ */
150
+ async retrieveState(address) {
151
+ await Promise.resolve();
152
+ const state = this.lastState.get(address);
153
+ if (state === void 0) {
154
+ const newState = Date.now() - 1e3;
155
+ this.lastState.set(address, newState);
156
+ return newState;
157
+ } else {
158
+ return state;
159
+ }
160
+ }
161
+ async resolve(id, typeCheck) {
162
+ if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {
163
+ return;
164
+ }
165
+ this._lastResolveFailure[id] = Date.now();
166
+ const resolved = await import_module_model.ResolveHelper.resolveModuleIdentifier(this.rootModule, id);
167
+ if (resolved) {
168
+ if (typeCheck(resolved)) {
169
+ delete this._lastResolveFailure[id];
170
+ return resolved;
171
+ } else {
172
+ this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${id}][${resolved?.constructor?.name}]: ${resolved.id}`);
173
+ }
174
+ } else {
175
+ this.logger?.debug(`Unable to resolve queriesArchivist [${id}] [${await import_module_model.ResolveHelper.traceModuleIdentifier(this.rootModule, id)}]`);
176
+ }
177
+ }
178
+ };
179
+
180
+ // src/AsyncQueryBus/model/QueryStatus.ts
181
+ var Pending = "pending";
182
+
183
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
184
+ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
185
+ static {
186
+ __name(this, "AsyncQueryBusClient");
187
+ }
188
+ _queryCache;
189
+ _pollCount = 0;
190
+ _pollId;
191
+ constructor(params) {
192
+ super(params);
193
+ }
194
+ get queryCacheConfig() {
195
+ const queryCacheConfig = this.config?.queryCache === true ? {} : this.config?.queryCache;
196
+ return {
197
+ max: 100,
198
+ ttl: 1e3 * 60,
199
+ ...queryCacheConfig
200
+ };
201
+ }
202
+ get started() {
203
+ return !!this._pollId;
204
+ }
205
+ /**
206
+ * A cache of queries that have been issued
207
+ */
208
+ get queryCache() {
209
+ const config = this.queryCacheConfig;
210
+ const requiredConfig = {
211
+ noUpdateTTL: false,
212
+ ttlAutopurge: true
213
+ };
214
+ this._queryCache = this._queryCache ?? new import_lru_cache2.LRUCache({
215
+ ...config,
216
+ ...requiredConfig
217
+ });
218
+ return this._queryCache;
219
+ }
220
+ listeningAddresses() {
221
+ return this._queryCache?.keys();
222
+ }
223
+ async send(address, query, payloads) {
224
+ this.logger?.debug(`Begin issuing query to: ${address}`);
225
+ const $meta = {
226
+ ...query?.$meta,
227
+ destination: [
228
+ address
229
+ ]
230
+ };
231
+ const routedQuery = await import_payload_builder.PayloadBuilder.build({
232
+ ...query,
233
+ $meta
234
+ });
235
+ const queryArchivist = (0, import_assert2.assertEx)(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
236
+ const routedQueryHash = (
237
+ // Trust the signed hash if it's there
238
+ routedQuery?.$hash ?? // TODO: What is the right way to find the dataHash
239
+ Object.keys(await import_payload_builder.PayloadBuilder.toDataHashMap([
240
+ routedQuery
241
+ ]))[0]
242
+ );
243
+ this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`);
244
+ const data = payloads ? [
245
+ routedQuery,
246
+ ...payloads
247
+ ] : [
248
+ routedQuery
249
+ ];
250
+ const insertResult = await queryArchivist.insert?.(data);
251
+ this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`);
252
+ this.queryCache.set(routedQueryHash, Pending);
253
+ if (!insertResult)
254
+ throw new Error("Unable to issue query to queryArchivist");
255
+ const context = new Promise((resolve, reject) => {
256
+ this.logger?.debug(`Polling for response to query: ${routedQueryHash}`);
257
+ let nextDelay = 100;
258
+ const pollForResponse = /* @__PURE__ */ __name(async () => {
259
+ try {
260
+ this.start();
261
+ let response = this.queryCache.get(routedQueryHash);
262
+ while (response !== void 0) {
263
+ await (0, import_delay.delay)(nextDelay);
264
+ response = this.queryCache.get(routedQueryHash);
265
+ if (response && response !== Pending) {
266
+ this.logger?.log(`Returning response to query: ${routedQueryHash}`);
267
+ resolve(response);
268
+ return;
269
+ }
270
+ nextDelay = Math.floor(nextDelay * 1.2);
271
+ if (nextDelay > 1e3)
272
+ nextDelay = 1e3;
273
+ }
274
+ this.logger?.error("Timeout waiting for query response");
275
+ const error = {
276
+ message: "Timeout waiting for query response",
277
+ query: "network.xyo.boundwitness",
278
+ schema: "network.xyo.error.module",
279
+ sources: [
280
+ routedQueryHash
281
+ ]
282
+ };
283
+ reject(error);
284
+ return;
285
+ } finally {
286
+ this.stop();
287
+ }
288
+ }, "pollForResponse");
289
+ (0, import_forget.forget)(pollForResponse());
290
+ });
291
+ return context;
292
+ }
293
+ /**
294
+ * Runs the background divine process on a loop with a delay
295
+ * specified by the `config.pollFrequency`
296
+ */
297
+ poll() {
298
+ this._pollId = (0, import_timer.setTimeoutEx)(async () => {
299
+ try {
300
+ await this.processIncomingResponses();
301
+ } catch (e) {
302
+ this.logger?.error?.(`Error in main loop: ${e}`);
303
+ } finally {
304
+ if (this._pollId)
305
+ (0, import_timer.clearTimeoutEx)(this._pollId);
306
+ this._pollId = void 0;
307
+ this.poll();
308
+ }
309
+ }, this.pollFrequency);
310
+ }
311
+ /**
312
+ * Background process for processing incoming responses to previously issued queries
313
+ */
314
+ processIncomingResponses = async () => {
315
+ const responseArchivist = await this.responsesArchivist();
316
+ if (responseArchivist) {
317
+ const responseBoundWitnessDiviner = await this.responsesDiviner();
318
+ if (responseBoundWitnessDiviner) {
319
+ const pendingCommands = [
320
+ ...this.queryCache.entries()
321
+ ].filter(([_, status]) => status === Pending);
322
+ await Promise.allSettled(pendingCommands.map(async ([sourceQuery, status]) => {
323
+ if (status === Pending) {
324
+ const divinerQuery = {
325
+ limit: 1,
326
+ order: "desc",
327
+ schema: import_diviner_boundwitness_model.BoundWitnessDivinerQuerySchema,
328
+ sourceQuery
329
+ };
330
+ const result = await responseBoundWitnessDiviner.divine([
331
+ divinerQuery
332
+ ]);
333
+ if (result && result.length > 0) {
334
+ const response = result.find(import_boundwitness_model.isBoundWitnessWithMeta);
335
+ if (response && response?.$meta?.sourceQuery === sourceQuery) {
336
+ this.logger?.debug(`Found response to query: ${sourceQuery}`);
337
+ const payloads = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : [];
338
+ this.queryCache.set(sourceQuery, [
339
+ response,
340
+ payloads,
341
+ []
342
+ ]);
343
+ }
344
+ }
345
+ }
346
+ }));
347
+ }
348
+ }
349
+ };
350
+ start() {
351
+ if (this._pollCount === 0) {
352
+ this.poll();
353
+ }
354
+ this._pollCount++;
355
+ }
356
+ stop() {
357
+ this._pollCount--;
358
+ if (this._pollCount <= 0) {
359
+ if (this._pollId)
360
+ (0, import_timer.clearTimeoutEx)(this._pollId);
361
+ this._pollId = void 0;
362
+ this._pollCount = 0;
363
+ }
364
+ }
365
+ };
366
+
367
+ // src/AsyncQueryBus/AsyncQueryBusHost.ts
368
+ var import_array = require("@xylabs/array");
369
+ var import_assert3 = require("@xylabs/assert");
370
+ var import_timer2 = require("@xylabs/timer");
371
+ var import_boundwitness_model2 = require("@xyo-network/boundwitness-model");
372
+ var import_bridge_model = require("@xyo-network/bridge-model");
373
+ var import_diviner_boundwitness_model2 = require("@xyo-network/diviner-boundwitness-model");
374
+ var import_module_model2 = require("@xyo-network/module-model");
375
+ var import_payload_builder2 = require("@xyo-network/payload-builder");
376
+ var IDLE_POLLING_FREQUENCY_RATIO_MIN = 4;
377
+ var IDLE_POLLING_FREQUENCY_RATIO_MAX = 64;
378
+ var IDLE_POLLING_FREQUENCY_RATIO_DEFAULT = 16;
379
+ var IDLE_THRESHOLD_RATIO_MIN = 4;
380
+ var IDLE_THRESHOLD_RATIO_MAX = 64;
381
+ var IDLE_THRESHOLD_RATIO_DEFAULT = 16;
382
+ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
383
+ static {
384
+ __name(this, "AsyncQueryBusHost");
385
+ }
386
+ _exposedAddresses = /* @__PURE__ */ new Set();
387
+ _exposeOptions = {};
388
+ _idle = false;
389
+ _lastQueryTime;
390
+ _pollId;
391
+ constructor(params) {
392
+ super(params);
393
+ }
394
+ get exposedAddresses() {
395
+ return this._exposedAddresses;
396
+ }
397
+ get idlePollFrequency() {
398
+ const frequency = this.config?.idlePollFrequency ?? IDLE_POLLING_FREQUENCY_RATIO_DEFAULT * this.pollFrequency;
399
+ if (frequency < this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MIN) {
400
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
401
+ }
402
+ if (frequency > this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MAX) {
403
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
404
+ }
405
+ return frequency;
406
+ }
407
+ get idleThreshold() {
408
+ const threshold = this.config?.idleThreshold ?? IDLE_THRESHOLD_RATIO_DEFAULT * this.idlePollFrequency;
409
+ if (threshold < this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MIN) {
410
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
411
+ }
412
+ if (threshold > this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MAX) {
413
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
414
+ }
415
+ return threshold;
416
+ }
417
+ get perAddressBatchQueryLimit() {
418
+ return this.config?.perAddressBatchQueryLimit ?? 10;
419
+ }
420
+ get started() {
421
+ return !!this._pollId;
422
+ }
423
+ expose(module2, options) {
424
+ const { failOnAlreadyExposed } = options ?? {};
425
+ if ((0, import_bridge_model.isBridgeInstance)(module2)) {
426
+ this.logger?.warn(`Attempted to expose a BridgeModule [${module2.id}] - Not exposing`);
427
+ } else {
428
+ (0, import_assert3.assertEx)(!failOnAlreadyExposed || !this._exposedAddresses.has(module2.address), () => `Address already exposed: ${module2.id} [${module2.address}]`);
429
+ this._exposedAddresses.add(module2.address);
430
+ this._exposeOptions[module2.address] = {
431
+ ...options
432
+ };
433
+ this.logger?.debug(`${module2.id} exposed [${module2.address}]`);
434
+ return module2;
435
+ }
436
+ }
437
+ async listeningModules() {
438
+ const exposedModules = [
439
+ ...this.config?.listeningModules ?? [],
440
+ ...this.exposedAddresses.values()
441
+ ];
442
+ const mods = await Promise.all(exposedModules.map(async (exposedModule) => (0, import_assert3.assertEx)((0, import_module_model2.asModuleInstance)(await (0, import_module_model2.resolveAddressToInstance)(this.rootModule, exposedModule)), () => `Unable to resolve listeningModule [${exposedModule}]`)));
443
+ return mods;
444
+ }
445
+ start() {
446
+ if (this.started) {
447
+ console.warn("AsyncQueryBus starting when already started");
448
+ }
449
+ this.poll();
450
+ }
451
+ stop() {
452
+ if (!this.started) {
453
+ console.warn("AsyncQueryBus stopping when already stopped");
454
+ }
455
+ if (this._pollId)
456
+ (0, import_timer2.clearTimeoutEx)(this._pollId);
457
+ this._pollId = void 0;
458
+ }
459
+ async unexpose(id, validate = true) {
460
+ const module2 = (0, import_module_model2.asModuleInstance)(await this.rootModule.resolve(id, {
461
+ maxDepth: 10
462
+ }));
463
+ if (module2) {
464
+ (0, import_assert3.assertEx)(!validate || this._exposedAddresses.has(module2.address), () => `Address not exposed [${module2.address}][${module2.id}]`);
465
+ this._exposedAddresses.delete(module2.address);
466
+ delete this._exposeOptions[module2.address];
467
+ this.logger?.debug(`${module2.address} [${module2.id}] unexposed`);
468
+ }
469
+ return module2;
470
+ }
471
+ callLocalModule = async (localModule, query) => {
472
+ this._idle = false;
473
+ this._lastQueryTime = Date.now();
474
+ const localModuleName = localModule.config.name ?? localModule.address;
475
+ const queryArchivist = (0, import_assert3.assertEx)(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
476
+ const responsesArchivist = (0, import_assert3.assertEx)(await this.responsesArchivist(), () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`);
477
+ const queryDestination = query.$meta?.destination;
478
+ if (queryDestination && queryDestination?.includes(localModule.address)) {
479
+ const queryIndex = query.payload_hashes.indexOf(query.query);
480
+ if (queryIndex !== -1) {
481
+ const querySchema = query.payload_schemas[queryIndex];
482
+ if (localModule.queries.includes(querySchema)) {
483
+ const queryPayloads = await queryArchivist.get(query.payload_hashes);
484
+ const queryPayloadsDict = await import_payload_builder2.PayloadBuilder.toAllHashMap(queryPayloads);
485
+ const queryHash = (await import_payload_builder2.PayloadBuilder.build(query)).$hash;
486
+ if (!(0, import_array.containsAll)(Object.keys(queryPayloadsDict), query.payload_hashes)) {
487
+ this.logger?.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`);
488
+ return;
489
+ }
490
+ try {
491
+ const querySchema2 = queryPayloadsDict[query.query].schema;
492
+ this.logger?.debug(`Issuing query ${querySchema2} (${queryHash}) addressed to module: ${localModuleName}`);
493
+ const response = await localModule.query(query, queryPayloads, {
494
+ allowedQueries: this._exposeOptions[localModule.address]?.allowedQueries,
495
+ schema: import_module_model2.ModuleConfigSchema
496
+ });
497
+ const [bw, payloads, errors] = response;
498
+ this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`);
499
+ const insertResult = await responsesArchivist.insert([
500
+ bw,
501
+ ...payloads,
502
+ ...errors
503
+ ]);
504
+ if (insertResult.length === 0) {
505
+ this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`);
506
+ }
507
+ if (query?.timestamp) {
508
+ await this.commitState(localModule.address, query.timestamp);
509
+ }
510
+ } catch (error) {
511
+ this.logger?.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
512
+ }
513
+ }
514
+ }
515
+ }
516
+ };
517
+ /**
518
+ * Finds unprocessed commands addressed to the supplied address
519
+ * @param address The address to find commands for
520
+ */
521
+ findQueriesToAddress = async (address) => {
522
+ const queriesDivinerId = (0, import_assert3.assertEx)(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined");
523
+ const queriesBoundWitnessDiviner = await this.queriesDiviner();
524
+ if (queriesBoundWitnessDiviner) {
525
+ const timestamp = await this.retrieveState(address);
526
+ const destination = [
527
+ address
528
+ ];
529
+ const limit = this.perAddressBatchQueryLimit;
530
+ const divinerQuery = {
531
+ destination,
532
+ limit,
533
+ order: "asc",
534
+ schema: import_diviner_boundwitness_model2.BoundWitnessDivinerQuerySchema,
535
+ timestamp
536
+ };
537
+ const result = await queriesBoundWitnessDiviner.divine([
538
+ divinerQuery
539
+ ]);
540
+ const queries = result.filter(import_boundwitness_model2.isQueryBoundWitnessWithMeta);
541
+ const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? 0)) + 1 : timestamp;
542
+ await this.commitState(address, nextState);
543
+ return queries;
544
+ } else {
545
+ this.logger?.warn(`Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await import_module_model2.ResolveHelper.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`);
546
+ }
547
+ };
548
+ /**
549
+ * Runs the background divine process on a loop with a delay
550
+ * specified by the `config.pollFrequency`
551
+ */
552
+ poll() {
553
+ this._pollId = (0, import_timer2.setTimeoutEx)(async () => {
554
+ try {
555
+ await this.processIncomingQueries();
556
+ } catch (e) {
557
+ this.logger?.error?.(`Error in main loop: ${e}`);
558
+ } finally {
559
+ if (this._pollId)
560
+ (0, import_timer2.clearTimeoutEx)(this._pollId);
561
+ this._pollId = void 0;
562
+ this.poll();
563
+ }
564
+ const now = Date.now();
565
+ if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
566
+ this._idle = true;
567
+ }
568
+ }, this._idle ? this.idlePollFrequency : this.pollFrequency);
569
+ }
570
+ /**
571
+ * Background process for checking for inbound queries
572
+ */
573
+ processIncomingQueries = async () => {
574
+ this.logger?.debug("Checking for inbound queries");
575
+ const localModules = await this.listeningModules();
576
+ await Promise.allSettled(localModules.map(async (localModule) => {
577
+ try {
578
+ const localModuleName = localModule.config.name ?? localModule.address;
579
+ this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
580
+ const queries = await this.findQueriesToAddress(localModule.address) ?? [];
581
+ if (queries.length === 0)
582
+ return;
583
+ this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`);
584
+ for (const query of queries) {
585
+ await this.callLocalModule(localModule, query);
586
+ }
587
+ } catch (error) {
588
+ this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`);
589
+ }
590
+ }));
591
+ };
592
+ };
593
+
594
+ // src/AsyncQueryBus/ModuleHost/ModuleHost.ts
595
+ var AsyncQueryBusModuleHost = class extends AbstractModuleHost {
596
+ static {
597
+ __name(this, "AsyncQueryBusModuleHost");
598
+ }
599
+ _busHost;
600
+ constructor(params) {
601
+ super(params);
602
+ }
603
+ async start() {
604
+ const listeningModules = this.params.config.listeningModules ?? (await this.params.module.resolve("*", {
605
+ direction: "down"
606
+ })).map((m) => m.address);
607
+ this._busHost = new AsyncQueryBusHost({
608
+ config: {
609
+ ...this.params.config,
610
+ listeningModules
611
+ },
612
+ logger: this.params.logger,
613
+ rootModule: this.params.module
614
+ });
615
+ this._busHost?.start();
616
+ }
617
+ stop() {
618
+ this._busHost?.stop();
619
+ }
620
+ };
621
+
622
+ // src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts
623
+ var import_abstract_bridge = require("@xyo-network/abstract-bridge");
624
+ var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends import_abstract_bridge.AbstractModuleProxy {
625
+ static {
626
+ __name(this, "AsyncQueryBusModuleProxy");
627
+ }
628
+ static createCount = 0;
629
+ constructor(params) {
630
+ _AsyncQueryBusModuleProxy.createCount = _AsyncQueryBusModuleProxy.createCount + 1;
631
+ if (Math.floor(_AsyncQueryBusModuleProxy.createCount / 10) === _AsyncQueryBusModuleProxy.createCount / 10) {
632
+ console.log(`AsyncQueryBusModuleProxy.createCount: ${_AsyncQueryBusModuleProxy.createCount}`);
633
+ }
634
+ super(params);
635
+ }
636
+ async proxyQueryHandler(query, payloads) {
637
+ return await this.params.busClient.send(this.address, query, payloads);
638
+ }
639
+ async startHandler() {
640
+ return await super.startHandler();
641
+ }
642
+ };
643
+
644
+ // src/Schema.ts
645
+ var PubSubBridgeSchema = "network.xyo.bridge.pubsub";
646
+
647
+ // src/Config.ts
648
+ var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
649
+
650
+ // src/PubSubBridge.ts
651
+ var import_assert5 = require("@xylabs/assert");
652
+ var import_exists = require("@xylabs/exists");
653
+ var import_object3 = require("@xylabs/object");
654
+ var import_abstract_bridge3 = require("@xyo-network/abstract-bridge");
655
+ var import_address_payload_plugin = require("@xyo-network/address-payload-plugin");
656
+ var import_module_model4 = require("@xyo-network/module-model");
657
+ var import_node_model = require("@xyo-network/node-model");
658
+ var import_payload_model = require("@xyo-network/payload-model");
659
+
660
+ // src/PubSubBridgeModuleResolver.ts
661
+ var import_assert4 = require("@xylabs/assert");
662
+ var import_hex = require("@xylabs/hex");
663
+ var import_abstract_bridge2 = require("@xyo-network/abstract-bridge");
664
+ var import_account = require("@xyo-network/account");
665
+ var import_config_payload_plugin = require("@xyo-network/config-payload-plugin");
666
+ var import_module_model3 = require("@xyo-network/module-model");
667
+ var PubSubBridgeModuleResolver = class extends import_abstract_bridge2.AbstractBridgeModuleResolver {
668
+ static {
669
+ __name(this, "PubSubBridgeModuleResolver");
670
+ }
671
+ async resolveHandler(id, options) {
672
+ const parentResult = await super.resolveHandler(id, options);
673
+ if (parentResult) {
674
+ return parentResult;
675
+ }
676
+ const idParts = id.split(":");
677
+ const firstPart = idParts.shift();
678
+ (0, import_assert4.assertEx)((0, import_hex.isAddress)(firstPart), () => `Invalid module address: ${firstPart}`);
679
+ const remainderParts = idParts.join(":");
680
+ const account = import_account.Account.randomSync();
681
+ const params = {
682
+ account,
683
+ busClient: this.params.busClient,
684
+ config: {
685
+ schema: import_module_model3.ModuleConfigSchema
686
+ },
687
+ host: this.params.bridge,
688
+ moduleAddress: firstPart
689
+ };
690
+ const proxy = new AsyncQueryBusModuleProxy(params);
691
+ if (proxy) {
692
+ const state = await proxy.state();
693
+ if (state) {
694
+ const configSchema = state.find((payload) => payload.schema === import_config_payload_plugin.ConfigSchema)?.config;
695
+ const config = (0, import_assert4.assertEx)(state.find((payload) => payload.schema === configSchema), () => "Unable to locate config");
696
+ proxy.setConfig(config);
697
+ }
698
+ }
699
+ await proxy.start?.();
700
+ const wrapped = (0, import_abstract_bridge2.wrapModuleWithType)(proxy, account);
701
+ const as = (0, import_assert4.assertEx)((0, import_module_model3.asModuleInstance)(wrapped, {}), () => `Failed to asModuleInstance [${id}]`);
702
+ proxy.upResolver.add(as);
703
+ proxy.downResolver.add(as);
704
+ this.add(as);
705
+ return remainderParts.length > 0 ? await proxy.resolve(remainderParts, options) : as;
706
+ }
707
+ };
708
+
709
+ // src/PubSubBridge.ts
710
+ function _ts_decorate(decorators, target, key, desc) {
711
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
712
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
713
+ r = Reflect.decorate(decorators, target, key, desc);
714
+ else
715
+ for (var i = decorators.length - 1; i >= 0; i--)
716
+ if (d = decorators[i])
717
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
718
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
719
+ }
720
+ __name(_ts_decorate, "_ts_decorate");
721
+ var moduleName = "PubSubBridge";
722
+ var PubSubBridge = class extends import_abstract_bridge3.AbstractBridge {
723
+ static {
724
+ __name(this, "PubSubBridge");
725
+ }
726
+ static configSchemas = [
727
+ ...super.configSchemas,
728
+ PubSubBridgeConfigSchema
729
+ ];
730
+ static defaultConfigSchema = PubSubBridgeConfigSchema;
731
+ _configRootAddress = "";
732
+ _configStateStoreArchivist = "";
733
+ _configStateStoreBoundWitnessDiviner = "";
734
+ _exposedAddresses = [];
735
+ _lastState;
736
+ _busClient;
737
+ _busHost;
738
+ _resolver;
739
+ get resolver() {
740
+ this._resolver = this._resolver ?? new PubSubBridgeModuleResolver({
741
+ bridge: this,
742
+ busClient: (0, import_assert5.assertEx)(this.busClient(), () => "busClient not configured"),
743
+ root: this,
744
+ wrapperAccount: this.account
745
+ });
746
+ return this._resolver;
747
+ }
748
+ get moduleName() {
749
+ return `${this.config.name ?? moduleName}`;
750
+ }
751
+ async connect(id, maxDepth = 5) {
752
+ const transformedId = (0, import_assert5.assertEx)(await import_module_model4.ResolveHelper.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
753
+ const existingInstance = await this.resolve(transformedId);
754
+ if (existingInstance) {
755
+ return existingInstance.address;
756
+ }
757
+ const instance = await this.resolver.resolve(id);
758
+ return await this.connectInstance(instance, maxDepth);
759
+ }
760
+ async disconnect(id) {
761
+ const transformedId = (0, import_assert5.assertEx)(await import_module_model4.ResolveHelper.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
762
+ const instance = await this.resolve(transformedId);
763
+ if (instance) {
764
+ this.downResolver.remove(instance.address);
765
+ return instance.address;
766
+ }
767
+ }
768
+ async discoverRoots() {
769
+ const rootAddresses = (await Promise.all((this.config.roots ?? []).map((id) => import_module_model4.ResolveHelper.transformModuleIdentifier(id)))).filter(import_exists.exists);
770
+ const rootInstances = (await Promise.all(rootAddresses.map(async (root) => await this.resolver.resolve(root)))).filter(import_exists.exists);
771
+ for (const instance of rootInstances) {
772
+ this.downResolver.add(instance);
773
+ }
774
+ this._roots = rootInstances;
775
+ return rootInstances;
776
+ }
777
+ async exposeHandler(address, options) {
778
+ const { maxDepth = 5, required = true } = options ?? {};
779
+ const host = (0, import_assert5.assertEx)(this.busHost(), () => "Not configured as a host");
780
+ const module2 = await (0, import_module_model4.resolveAddressToInstanceUp)(this, address);
781
+ if (required && !module2) {
782
+ throw new Error(`Unable to find required module: ${address}`);
783
+ }
784
+ if (module2) {
785
+ host.expose(module2);
786
+ const children = maxDepth > 0 ? await module2.publicChildren?.() ?? [] : [];
787
+ console.log(`childrenToExpose [${module2.id}]: ${(0, import_object3.toJsonString)(children.map((child) => child.id))}`);
788
+ const exposedChildren = (await Promise.all(children.map((child) => this.exposeHandler(child.address, {
789
+ maxDepth: maxDepth - 1,
790
+ required: false
791
+ })))).flat().filter(import_exists.exists);
792
+ const allExposed = [
793
+ module2,
794
+ ...exposedChildren
795
+ ];
796
+ for (const mod of allExposed)
797
+ this.logger?.log(`exposed: ${mod.address} [${mod.id}]`);
798
+ return [
799
+ module2,
800
+ ...exposedChildren
801
+ ];
802
+ }
803
+ return [];
804
+ }
805
+ exposedHandler() {
806
+ const exposedSet = this.busHost()?.exposedAddresses;
807
+ return exposedSet ? [
808
+ ...exposedSet
809
+ ] : [];
810
+ }
811
+ async startHandler() {
812
+ this.busHost()?.start();
813
+ return await super.startHandler();
814
+ }
815
+ async unexposeHandler(id, options) {
816
+ const { maxDepth = 2, required = true } = options ?? {};
817
+ const host = (0, import_assert5.assertEx)(this.busHost(), () => "Not configured as a host");
818
+ const module2 = await host.unexpose(id, required);
819
+ if (module2) {
820
+ const children = maxDepth > 0 ? await module2.publicChildren?.() ?? [] : [];
821
+ const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, {
822
+ maxDepth: maxDepth - 1,
823
+ required: false
824
+ })))).flat().filter(import_exists.exists);
825
+ return [
826
+ module2,
827
+ ...exposedChildren
828
+ ];
829
+ }
830
+ return [];
831
+ }
832
+ busClient() {
833
+ if (!this._busClient && this.config.client) {
834
+ this._busClient = new AsyncQueryBusClient({
835
+ config: this.config.client,
836
+ logger: this.logger,
837
+ rootModule: this
838
+ });
839
+ }
840
+ return this._busClient;
841
+ }
842
+ busHost() {
843
+ if (!this._busHost && this.config.host) {
844
+ this._busHost = new AsyncQueryBusHost({
845
+ config: this.config.host,
846
+ logger: this.logger,
847
+ rootModule: this
848
+ });
849
+ }
850
+ return this._busHost;
851
+ }
852
+ async connectInstance(instance, maxDepth = 5) {
853
+ if (instance) {
854
+ this.downResolver.add(instance);
855
+ if (maxDepth > 0) {
856
+ const node = (0, import_node_model.asNodeInstance)(instance);
857
+ if (node) {
858
+ const state = await node.state();
859
+ const children = (state?.filter((0, import_payload_model.isPayloadOfSchemaType)(import_address_payload_plugin.AddressSchema)).map((s) => s.address) ?? []).filter((a) => a !== instance.address);
860
+ await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
861
+ }
862
+ }
863
+ this.logger?.log(`Connect: ${instance.config.name ?? instance.address}`);
864
+ return instance.address;
865
+ }
866
+ }
867
+ stopHandler(_timeout) {
868
+ this.busHost()?.stop();
869
+ return true;
870
+ }
871
+ };
872
+ PubSubBridge = _ts_decorate([
873
+ (0, import_module_model4.creatableModule)()
874
+ ], PubSubBridge);
875
+ //# sourceMappingURL=index.cjs.map