@private.me/xbind 3.0.2 → 3.0.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 (221) hide show
  1. package/README.md +2366 -204
  2. package/README.md.backup +2121 -0
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  7. package/dist-standalone/_deps/shared/errors.js +1 -244
  8. package/dist-standalone/_deps/shared/index.js +1 -72
  9. package/dist-standalone/_deps/shared/types.js +1 -86
  10. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  20. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  21. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  28. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  29. package/dist-standalone/_deps/xchange/errors.js +1 -1
  30. package/dist-standalone/_deps/xchange/index.js +1 -1
  31. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  32. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  33. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  34. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  40. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  41. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  42. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  43. package/dist-standalone/_deps/xregistry/index.js +1 -1
  44. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  45. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  46. package/dist-standalone/_deps/xregistry/types.js +1 -1
  47. package/dist-standalone/agent-call.d.ts +2 -2
  48. package/dist-standalone/agent-call.js +1 -659
  49. package/dist-standalone/agent-sdk.js +1 -328
  50. package/dist-standalone/agent.d.ts +2 -0
  51. package/dist-standalone/agent.js +1 -1800
  52. package/dist-standalone/approval.js +1 -193
  53. package/dist-standalone/async-iterators.d.ts +3 -3
  54. package/dist-standalone/async-iterators.js +1 -382
  55. package/dist-standalone/auth.js +1 -219
  56. package/dist-standalone/auto-accept.js +1 -229
  57. package/dist-standalone/backup-config.js +1 -201
  58. package/dist-standalone/backup.js +1 -326
  59. package/dist-standalone/batch-operations.js +1 -388
  60. package/dist-standalone/cancellation.js +1 -477
  61. package/dist-standalone/checkpoint.js +1 -186
  62. package/dist-standalone/circuit-breaker.js +1 -468
  63. package/dist-standalone/cjs/agent-call.js +1 -701
  64. package/dist-standalone/cjs/agent-sdk.js +1 -332
  65. package/dist-standalone/cjs/agent.js +1 -1837
  66. package/dist-standalone/cjs/approval.js +1 -199
  67. package/dist-standalone/cjs/async-iterators.js +1 -392
  68. package/dist-standalone/cjs/auth.js +1 -225
  69. package/dist-standalone/cjs/auto-accept.js +1 -233
  70. package/dist-standalone/cjs/backup-config.js +1 -207
  71. package/dist-standalone/cjs/backup.js +1 -330
  72. package/dist-standalone/cjs/batch-operations.js +1 -397
  73. package/dist-standalone/cjs/cancellation.js +1 -490
  74. package/dist-standalone/cjs/checkpoint.js +1 -193
  75. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  76. package/dist-standalone/cjs/cli/init.js +1 -492
  77. package/dist-standalone/cjs/config-validation.js +1 -522
  78. package/dist-standalone/cjs/connect.js +1 -312
  79. package/dist-standalone/cjs/connection-pool.js +1 -506
  80. package/dist-standalone/cjs/correlation-id.js +1 -339
  81. package/dist-standalone/cjs/crypto-utils.js +1 -176
  82. package/dist-standalone/cjs/debug-mode.js +1 -534
  83. package/dist-standalone/cjs/did-document.js +1 -101
  84. package/dist-standalone/cjs/did-privateme.js +1 -130
  85. package/dist-standalone/cjs/did-web.js +1 -201
  86. package/dist-standalone/cjs/discovery.js +1 -462
  87. package/dist-standalone/cjs/dual-mode.js +1 -251
  88. package/dist-standalone/cjs/email-templates.js +1 -313
  89. package/dist-standalone/cjs/email-transport.js +1 -239
  90. package/dist-standalone/cjs/envelope.js +1 -538
  91. package/dist-standalone/cjs/errors.js +1 -913
  92. package/dist-standalone/cjs/event-emitter.js +1 -461
  93. package/dist-standalone/cjs/gateway-state.js +1 -55
  94. package/dist-standalone/cjs/gateway-transport.js +1 -120
  95. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  96. package/dist-standalone/cjs/guardrails.js +1 -223
  97. package/dist-standalone/cjs/health-check.js +1 -336
  98. package/dist-standalone/cjs/http-compat.js +1 -272
  99. package/dist-standalone/cjs/http-status-map.js +1 -571
  100. package/dist-standalone/cjs/identity.js +1 -645
  101. package/dist-standalone/cjs/index.js +1 -406
  102. package/dist-standalone/cjs/invitation.js +1 -421
  103. package/dist-standalone/cjs/invite.js +1 -328
  104. package/dist-standalone/cjs/key-agreement.js +1 -335
  105. package/dist-standalone/cjs/lazy-init.js +1 -300
  106. package/dist-standalone/cjs/logger.js +1 -291
  107. package/dist-standalone/cjs/loopback-transport.js +1 -0
  108. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  109. package/dist-standalone/cjs/nonce-store.js +1 -80
  110. package/dist-standalone/cjs/pairing-manager.js +1 -223
  111. package/dist-standalone/cjs/plugin-system.js +1 -264
  112. package/dist-standalone/cjs/plugins/logging.js +1 -168
  113. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  114. package/dist-standalone/cjs/plugins/validation.js +1 -302
  115. package/dist-standalone/cjs/policy.js +1 -320
  116. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  117. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  118. package/dist-standalone/cjs/registry-middleware.js +1 -50
  119. package/dist-standalone/cjs/retry-strategies.js +1 -544
  120. package/dist-standalone/cjs/retry-transport.js +1 -102
  121. package/dist-standalone/cjs/runtime/browser.js +1 -533
  122. package/dist-standalone/cjs/runtime/edge.js +1 -526
  123. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  124. package/dist-standalone/cjs/security-policy.js +1 -245
  125. package/dist-standalone/cjs/serialization.js +1 -1040
  126. package/dist-standalone/cjs/split-channel.js +1 -225
  127. package/dist-standalone/cjs/subscription-proof.js +1 -230
  128. package/dist-standalone/cjs/succession.js +1 -148
  129. package/dist-standalone/cjs/timeouts.js +1 -412
  130. package/dist-standalone/cjs/trace-context.js +1 -424
  131. package/dist-standalone/cjs/trace-spans.js +1 -495
  132. package/dist-standalone/cjs/transport.js +1 -63
  133. package/dist-standalone/cjs/trust-registry.js +1 -991
  134. package/dist-standalone/cjs/types/error-response.js +1 -56
  135. package/dist-standalone/cjs/vault-auth.js +1 -178
  136. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  137. package/dist-standalone/cjs/verify.js +1 -25
  138. package/dist-standalone/cjs/version-info.js +1 -543
  139. package/dist-standalone/cjs/xfetch.js +1 -340
  140. package/dist-standalone/cli/init.js +1 -455
  141. package/dist-standalone/cli/setup.js +1 -514
  142. package/dist-standalone/cli/types.js +1 -27
  143. package/dist-standalone/cli/xbind.js +1 -148
  144. package/dist-standalone/config-validation.js +1 -513
  145. package/dist-standalone/connect.js +1 -274
  146. package/dist-standalone/connection-pool.js +1 -500
  147. package/dist-standalone/correlation-id.js +1 -326
  148. package/dist-standalone/crypto-utils.d.ts +2 -7
  149. package/dist-standalone/crypto-utils.js +1 -157
  150. package/dist-standalone/debug-mode.js +1 -510
  151. package/dist-standalone/did-document.js +1 -96
  152. package/dist-standalone/did-privateme.js +1 -121
  153. package/dist-standalone/did-web.js +1 -196
  154. package/dist-standalone/discovery.js +1 -458
  155. package/dist-standalone/dual-mode.js +1 -247
  156. package/dist-standalone/email-templates.js +1 -309
  157. package/dist-standalone/email-transport.d.ts +2 -2
  158. package/dist-standalone/email-transport.js +1 -232
  159. package/dist-standalone/envelope.js +1 -525
  160. package/dist-standalone/errors.d.ts +13 -3
  161. package/dist-standalone/errors.js +1 -896
  162. package/dist-standalone/event-emitter.js +1 -456
  163. package/dist-standalone/gateway-state.d.ts +1 -1
  164. package/dist-standalone/gateway-state.js +1 -51
  165. package/dist-standalone/gateway-transport.js +1 -116
  166. package/dist-standalone/graceful-degradation.js +1 -396
  167. package/dist-standalone/guardrails.js +1 -216
  168. package/dist-standalone/health-check.d.ts +5 -1
  169. package/dist-standalone/health-check.js +1 -332
  170. package/dist-standalone/http-compat.d.ts +1 -1
  171. package/dist-standalone/http-compat.js +1 -267
  172. package/dist-standalone/http-status-map.js +1 -561
  173. package/dist-standalone/identity.js +1 -619
  174. package/dist-standalone/index.d.ts +15 -4
  175. package/dist-standalone/index.js +1 -78
  176. package/dist-standalone/invitation.js +1 -415
  177. package/dist-standalone/invite.js +1 -324
  178. package/dist-standalone/key-agreement.js +1 -325
  179. package/dist-standalone/lazy-init.d.ts +11 -6
  180. package/dist-standalone/lazy-init.js +1 -295
  181. package/dist-standalone/logger.js +1 -285
  182. package/dist-standalone/loopback-transport.d.ts +87 -0
  183. package/dist-standalone/loopback-transport.js +1 -0
  184. package/dist-standalone/mdns-discovery.js +1 -195
  185. package/dist-standalone/nonce-store.js +1 -76
  186. package/dist-standalone/pairing-manager.js +1 -219
  187. package/dist-standalone/plugin-system.js +1 -257
  188. package/dist-standalone/plugins/logging.js +1 -163
  189. package/dist-standalone/plugins/metrics.d.ts +4 -4
  190. package/dist-standalone/plugins/metrics.js +1 -176
  191. package/dist-standalone/plugins/validation.js +1 -297
  192. package/dist-standalone/policy.js +1 -315
  193. package/dist-standalone/progress-callbacks.js +1 -576
  194. package/dist-standalone/redis-nonce-store.js +1 -72
  195. package/dist-standalone/registry-middleware.js +1 -47
  196. package/dist-standalone/retry-strategies.js +1 -534
  197. package/dist-standalone/retry-transport.js +1 -98
  198. package/dist-standalone/runtime/browser.js +1 -516
  199. package/dist-standalone/runtime/edge.js +1 -511
  200. package/dist-standalone/runtime/react-native.d.ts +1 -1
  201. package/dist-standalone/runtime/react-native.js +1 -383
  202. package/dist-standalone/security-policy.js +1 -239
  203. package/dist-standalone/serialization.js +1 -1031
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.js +1 -59
  211. package/dist-standalone/trust-registry.d.ts +3 -3
  212. package/dist-standalone/trust-registry.js +1 -950
  213. package/dist-standalone/types/error-response.js +1 -52
  214. package/dist-standalone/vault-auth.js +1 -174
  215. package/dist-standalone/vault-store-loader.d.ts +9 -0
  216. package/dist-standalone/vault-store-loader.js +1 -187
  217. package/dist-standalone/verify.js +1 -16
  218. package/dist-standalone/version-info.js +1 -530
  219. package/dist-standalone/xfetch.js +1 -335
  220. package/package.json +1 -1
  221. package/share1.dat +0 -0
@@ -1,461 +1 @@
1
- "use strict";
2
- /**
3
- * @module event-emitter
4
- * Type-safe event emitter for xBind agent events.
5
- *
6
- * Provides event-driven architecture for agent lifecycle events:
7
- * - message-sent: Emitted when a message is successfully sent
8
- * - message-received: Emitted when a message is received
9
- * - key-rotated: Emitted when encryption keys are rotated
10
- * - error: Emitted when an error occurs
11
- * - connection-status: Emitted when connection state changes
12
- */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.XBindEventEmitter = void 0;
15
- exports.createScopedEmitter = createScopedEmitter;
16
- const shared_1 = require("../_deps/shared/index.js");
17
- /**
18
- * Type-safe event emitter for xBind agent events.
19
- *
20
- * Features:
21
- * - Type-safe event names and payloads
22
- * - Listener priority support
23
- * - Once listeners
24
- * - Event bubbling to parent emitters
25
- * - Async listener support with error handling
26
- * - Memory leak detection
27
- *
28
- * @example
29
- * ```typescript
30
- * const emitter = new XBindEventEmitter();
31
- *
32
- * // Register listener
33
- * emitter.on('message-received', (event) => {
34
- * console.log('Received from:', event.senderDid);
35
- * });
36
- *
37
- * // Register one-time listener
38
- * emitter.once('connection-status', (event) => {
39
- * console.log('Status:', event.status);
40
- * });
41
- *
42
- * // Emit event
43
- * await emitter.emit('message-received', {
44
- * type: 'message-received',
45
- * timestamp: new Date().toISOString(),
46
- * eventId: '123',
47
- * senderDid: 'did:key:z6Mk...',
48
- * message: { payload: 'Hello' },
49
- * messageId: 'msg-1',
50
- * verified: true
51
- * });
52
- * ```
53
- */
54
- class XBindEventEmitter {
55
- listeners = new Map();
56
- parent;
57
- disposed = false;
58
- eventCounter = 0;
59
- /** Maximum listeners per event type before warning (0 = unlimited) */
60
- maxListeners = 10;
61
- /** Whether warnings are enabled */
62
- warningsEnabled = true;
63
- /**
64
- * Create a new event emitter.
65
- *
66
- * @param parent - Optional parent emitter for event bubbling
67
- */
68
- constructor(parent) {
69
- this.parent = parent;
70
- }
71
- /**
72
- * Register an event listener.
73
- *
74
- * @param eventType - Event type to listen for
75
- * @param listener - Listener function
76
- * @param options - Listener options (priority, once)
77
- * @returns This emitter for chaining
78
- *
79
- * @example
80
- * ```typescript
81
- * emitter.on('error', (event) => {
82
- * console.error('Error:', event.message);
83
- * }, { priority: 10 });
84
- * ```
85
- */
86
- on(eventType, listener, options = {}) {
87
- this.checkDisposed();
88
- if (typeof listener !== 'function') {
89
- throw new Error('Listener must be a function');
90
- }
91
- const listeners = this.listeners.get(eventType) ?? [];
92
- const registered = {
93
- listener: listener,
94
- once: options.once ?? false,
95
- priority: options.priority ?? 0,
96
- };
97
- listeners.push(registered);
98
- // Sort by priority (highest first)
99
- listeners.sort((a, b) => b.priority - a.priority);
100
- this.listeners.set(eventType, listeners);
101
- // Check for potential memory leaks
102
- if (this.warningsEnabled && this.maxListeners > 0 && listeners.length > this.maxListeners) {
103
- // eslint-disable-next-line no-console
104
- console.warn(`[xBind EventEmitter] Possible memory leak detected: ${listeners.length} listeners for event '${eventType}'. ` +
105
- `Use emitter.setMaxListeners() to increase limit.`);
106
- }
107
- return this;
108
- }
109
- /**
110
- * Register a one-time event listener.
111
- * Listener is automatically removed after first invocation.
112
- *
113
- * @param eventType - Event type to listen for
114
- * @param listener - Listener function
115
- * @param options - Listener options (priority)
116
- * @returns This emitter for chaining
117
- *
118
- * @example
119
- * ```typescript
120
- * emitter.once('connection-status', (event) => {
121
- * console.log('First status change:', event.status);
122
- * });
123
- * ```
124
- */
125
- once(eventType, listener, options = {}) {
126
- return this.on(eventType, listener, { ...options, once: true });
127
- }
128
- /**
129
- * Remove an event listener.
130
- *
131
- * @param eventType - Event type
132
- * @param listener - Listener function to remove
133
- * @returns This emitter for chaining
134
- *
135
- * @example
136
- * ```typescript
137
- * const handler = (event) => console.log(event);
138
- * emitter.on('error', handler);
139
- * emitter.off('error', handler);
140
- * ```
141
- */
142
- off(eventType, listener) {
143
- this.checkDisposed();
144
- const listeners = this.listeners.get(eventType);
145
- if (!listeners)
146
- return this;
147
- const filtered = listeners.filter(l => l.listener !== listener);
148
- if (filtered.length === 0) {
149
- this.listeners.delete(eventType);
150
- }
151
- else {
152
- this.listeners.set(eventType, filtered);
153
- }
154
- return this;
155
- }
156
- /**
157
- * Remove all listeners for an event type, or all listeners if no type specified.
158
- *
159
- * @param eventType - Optional event type (removes all if not specified)
160
- * @returns This emitter for chaining
161
- *
162
- * @example
163
- * ```typescript
164
- * emitter.removeAllListeners('error'); // Remove all error listeners
165
- * emitter.removeAllListeners(); // Remove all listeners
166
- * ```
167
- */
168
- removeAllListeners(eventType) {
169
- this.checkDisposed();
170
- if (eventType) {
171
- this.listeners.delete(eventType);
172
- }
173
- else {
174
- this.listeners.clear();
175
- }
176
- return this;
177
- }
178
- /**
179
- * Emit an event to all registered listeners.
180
- * Listeners are called in priority order (highest first).
181
- * Async listeners are awaited in sequence.
182
- *
183
- * @param eventType - Event type to emit
184
- * @param event - Event payload
185
- * @param options - Emission options (bubble, stopPropagation)
186
- * @returns Result indicating success or first error encountered
187
- *
188
- * @example
189
- * ```typescript
190
- * await emitter.emit('error', {
191
- * type: 'error',
192
- * timestamp: new Date().toISOString(),
193
- * eventId: '123',
194
- * code: 'NETWORK_ERROR',
195
- * message: 'Connection failed',
196
- * context: 'transport'
197
- * });
198
- * ```
199
- */
200
- async emit(eventType, event, options = {}) {
201
- this.checkDisposed();
202
- // Add standard fields if not present
203
- const fullEvent = {
204
- ...event,
205
- eventId: options.eventId ?? this.generateEventId(),
206
- timestamp: new Date().toISOString(),
207
- };
208
- const listeners = this.listeners.get(eventType);
209
- if (listeners && listeners.length > 0) {
210
- // Create a copy to avoid issues if listeners modify the array
211
- const listenersCopy = [...listeners];
212
- for (const registered of listenersCopy) {
213
- try {
214
- await registered.listener(fullEvent);
215
- // Remove once listeners
216
- if (registered.once) {
217
- this.off(eventType, registered.listener);
218
- }
219
- // Stop propagation if requested
220
- if (options.stopPropagation) {
221
- return (0, shared_1.ok)(undefined);
222
- }
223
- }
224
- catch (error) {
225
- // Log error but continue with other listeners
226
- // eslint-disable-next-line no-console
227
- console.error(`[xBind EventEmitter] Error in listener for '${eventType}':`, error);
228
- // Return first error encountered
229
- return (0, shared_1.err)('LISTENER_ERROR');
230
- }
231
- }
232
- }
233
- // Bubble to parent if requested
234
- if (options.bubble !== false && this.parent) {
235
- return this.parent.emit(eventType, event, { ...options, bubble: true });
236
- }
237
- return (0, shared_1.ok)(undefined);
238
- }
239
- /**
240
- * Check if there are any listeners for an event type.
241
- *
242
- * @param eventType - Event type to check
243
- * @returns True if there are listeners
244
- *
245
- * @example
246
- * ```typescript
247
- * if (emitter.hasListeners('error')) {
248
- * await emitter.emit('error', errorEvent);
249
- * }
250
- * ```
251
- */
252
- hasListeners(eventType) {
253
- const listeners = this.listeners.get(eventType);
254
- return listeners !== undefined && listeners.length > 0;
255
- }
256
- /**
257
- * Get the number of listeners for an event type.
258
- *
259
- * @param eventType - Event type
260
- * @returns Number of listeners
261
- *
262
- * @example
263
- * ```typescript
264
- * const count = emitter.listenerCount('message-received');
265
- * console.log(`${count} listeners registered`);
266
- * ```
267
- */
268
- listenerCount(eventType) {
269
- const listeners = this.listeners.get(eventType);
270
- return listeners?.length ?? 0;
271
- }
272
- /**
273
- * Get all registered event types.
274
- *
275
- * @returns Array of event types with active listeners
276
- *
277
- * @example
278
- * ```typescript
279
- * const events = emitter.eventNames();
280
- * console.log('Active events:', events);
281
- * ```
282
- */
283
- eventNames() {
284
- return Array.from(this.listeners.keys());
285
- }
286
- /**
287
- * Set the maximum number of listeners per event before warning.
288
- * Use 0 for unlimited listeners.
289
- *
290
- * @param n - Maximum listeners (0 = unlimited)
291
- * @returns This emitter for chaining
292
- *
293
- * @example
294
- * ```typescript
295
- * emitter.setMaxListeners(20); // Allow up to 20 listeners
296
- * emitter.setMaxListeners(0); // Unlimited
297
- * ```
298
- */
299
- setMaxListeners(n) {
300
- if (n < 0 || !Number.isInteger(n)) {
301
- throw new Error('Max listeners must be a non-negative integer');
302
- }
303
- this.maxListeners = n;
304
- return this;
305
- }
306
- /**
307
- * Get the maximum number of listeners per event.
308
- *
309
- * @returns Maximum listeners (0 = unlimited)
310
- */
311
- getMaxListeners() {
312
- return this.maxListeners;
313
- }
314
- /**
315
- * Enable or disable memory leak warnings.
316
- *
317
- * @param enabled - Whether warnings are enabled
318
- * @returns This emitter for chaining
319
- */
320
- setWarningsEnabled(enabled) {
321
- this.warningsEnabled = enabled;
322
- return this;
323
- }
324
- /**
325
- * Set the parent emitter for event bubbling.
326
- *
327
- * @param parent - Parent emitter (undefined to remove parent)
328
- * @returns This emitter for chaining
329
- *
330
- * @example
331
- * ```typescript
332
- * const parent = new XBindEventEmitter();
333
- * const child = new XBindEventEmitter();
334
- * child.setParent(parent);
335
- *
336
- * parent.on('error', (event) => console.log('Parent received:', event));
337
- * await child.emit('error', errorEvent, { bubble: true });
338
- * ```
339
- */
340
- setParent(parent) {
341
- this.parent = parent;
342
- return this;
343
- }
344
- /**
345
- * Get the parent emitter.
346
- *
347
- * @returns Parent emitter or undefined
348
- */
349
- getParent() {
350
- return this.parent;
351
- }
352
- /**
353
- * Wait for a specific event to be emitted.
354
- * Returns a promise that resolves with the event payload.
355
- *
356
- * @param eventType - Event type to wait for
357
- * @param timeout - Optional timeout in milliseconds
358
- * @returns Promise resolving to event or rejecting on timeout
359
- *
360
- * @example
361
- * ```typescript
362
- * const event = await emitter.waitFor('connection-status', 5000);
363
- * console.log('Status changed to:', event.status);
364
- * ```
365
- */
366
- waitFor(eventType, timeout) {
367
- return new Promise((resolve, reject) => {
368
- let timeoutId;
369
- const handler = (event) => {
370
- if (timeoutId)
371
- clearTimeout(timeoutId);
372
- resolve(event);
373
- };
374
- this.once(eventType, handler);
375
- if (timeout !== undefined && timeout > 0) {
376
- timeoutId = setTimeout(() => {
377
- this.off(eventType, handler);
378
- reject(new Error(`Timeout waiting for event '${eventType}' after ${timeout}ms`));
379
- }, timeout);
380
- }
381
- });
382
- }
383
- /**
384
- * Dispose the event emitter and remove all listeners.
385
- * After disposal, no events can be emitted and listeners cannot be registered.
386
- *
387
- * @example
388
- * ```typescript
389
- * emitter.dispose();
390
- * ```
391
- */
392
- dispose() {
393
- this.disposed = true;
394
- this.listeners.clear();
395
- this.parent = undefined;
396
- }
397
- /**
398
- * Check if the emitter has been disposed.
399
- *
400
- * @returns True if disposed
401
- */
402
- isDisposed() {
403
- return this.disposed;
404
- }
405
- checkDisposed() {
406
- if (this.disposed) {
407
- throw new Error('EventEmitter has been disposed');
408
- }
409
- }
410
- generateEventId() {
411
- return `evt-${Date.now()}-${++this.eventCounter}`;
412
- }
413
- }
414
- exports.XBindEventEmitter = XBindEventEmitter;
415
- /**
416
- * Create a scoped event emitter that only emits specific event types.
417
- * Useful for isolating event channels.
418
- *
419
- * @param parent - Parent emitter
420
- * @param allowedEvents - Array of allowed event types
421
- * @returns Scoped event emitter
422
- *
423
- * @example
424
- * ```typescript
425
- * const parent = new XBindEventEmitter();
426
- * const errorOnly = createScopedEmitter(parent, ['error']);
427
- *
428
- * errorOnly.emit('error', errorEvent); // OK
429
- * errorOnly.emit('message-sent', event); // TypeScript error
430
- * ```
431
- */
432
- function createScopedEmitter(parent, allowedEvents) {
433
- const emitter = new XBindEventEmitter(parent);
434
- const allowedSet = new Set(allowedEvents);
435
- return {
436
- on: (type, listener, options) => {
437
- if (!allowedSet.has(type)) {
438
- throw new Error(`Event type '${String(type)}' not allowed in scoped emitter`);
439
- }
440
- return emitter.on(type, listener, options);
441
- },
442
- once: (type, listener, options) => {
443
- if (!allowedSet.has(type)) {
444
- throw new Error(`Event type '${String(type)}' not allowed in scoped emitter`);
445
- }
446
- return emitter.once(type, listener, options);
447
- },
448
- off: (type, listener) => {
449
- return emitter.off(type, listener);
450
- },
451
- emit: (type, event, options) => {
452
- if (!allowedSet.has(type)) {
453
- return Promise.resolve((0, shared_1.err)('INVALID_EVENT_TYPE'));
454
- }
455
- return emitter.emit(type, event, options);
456
- },
457
- hasListeners: (type) => emitter.hasListeners(type),
458
- listenerCount: (type) => emitter.listenerCount(type),
459
- dispose: () => emitter.dispose(),
460
- };
461
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XBindEventEmitter=void 0,exports.createScopedEmitter=createScopedEmitter;const shared_1=require("../_deps/shared/index.js");class XBindEventEmitter{listeners=new Map;parent;disposed=!1;eventCounter=0;maxListeners=10;warningsEnabled=!0;constructor(e){this.parent=e}on(e,t,s={}){if(this.checkDisposed(),"function"!=typeof t)throw new Error("Listener must be a function");const r=this.listeners.get(e)??[],n={listener:t,once:s.once??!1,priority:s.priority??0};return r.push(n),r.sort((e,t)=>t.priority-e.priority),this.listeners.set(e,r),this.warningsEnabled&&this.maxListeners>0&&r.length>this.maxListeners&&console.warn(`[xBind EventEmitter] Possible memory leak detected: ${r.length} listeners for event '${e}'. Use emitter.setMaxListeners() to increase limit.`),this}once(e,t,s={}){return this.on(e,t,{...s,once:!0})}off(e,t){this.checkDisposed();const s=this.listeners.get(e);if(!s)return this;const r=s.filter(e=>e.listener!==t);return 0===r.length?this.listeners.delete(e):this.listeners.set(e,r),this}removeAllListeners(e){return this.checkDisposed(),e?this.listeners.delete(e):this.listeners.clear(),this}async emit(e,t,s={}){this.checkDisposed();const r={...t,eventId:s.eventId??this.generateEventId(),timestamp:(new Date).toISOString()},n=this.listeners.get(e);if(n&&n.length>0){const t=[...n];for(const n of t)try{if(await n.listener(r),n.once&&this.off(e,n.listener),s.stopPropagation)return(0,shared_1.ok)(void 0)}catch(t){return console.error(`[xBind EventEmitter] Error in listener for '${e}':`,t),(0,shared_1.err)("LISTENER_ERROR")}}return!1!==s.bubble&&this.parent?this.parent.emit(e,t,{...s,bubble:!0}):(0,shared_1.ok)(void 0)}hasListeners(e){const t=this.listeners.get(e);return void 0!==t&&t.length>0}listenerCount(e){const t=this.listeners.get(e);return t?.length??0}eventNames(){return Array.from(this.listeners.keys())}setMaxListeners(e){if(e<0||!Number.isInteger(e))throw new Error("Max listeners must be a non-negative integer");return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}setWarningsEnabled(e){return this.warningsEnabled=e,this}setParent(e){return this.parent=e,this}getParent(){return this.parent}waitFor(e,t){return new Promise((s,r)=>{let n;const i=e=>{n&&clearTimeout(n),s(e)};this.once(e,i),void 0!==t&&t>0&&(n=setTimeout(()=>{this.off(e,i),r(new Error(`Timeout waiting for event '${e}' after ${t}ms`))},t))})}dispose(){this.disposed=!0,this.listeners.clear(),this.parent=void 0}isDisposed(){return this.disposed}checkDisposed(){if(this.disposed)throw new Error("EventEmitter has been disposed")}generateEventId(){return`evt-${Date.now()}-${++this.eventCounter}`}}function createScopedEmitter(e,t){const s=new XBindEventEmitter(e),r=new Set(t);return{on:(e,t,n)=>{if(!r.has(e))throw new Error(`Event type '${String(e)}' not allowed in scoped emitter`);return s.on(e,t,n)},once:(e,t,n)=>{if(!r.has(e))throw new Error(`Event type '${String(e)}' not allowed in scoped emitter`);return s.once(e,t,n)},off:(e,t)=>s.off(e,t),emit:(e,t,n)=>r.has(e)?s.emit(e,t,n):Promise.resolve((0,shared_1.err)("INVALID_EVENT_TYPE")),hasListeners:e=>s.hasListeners(e),listenerCount:e=>s.listenerCount(e),dispose:()=>s.dispose()}}exports.XBindEventEmitter=XBindEventEmitter;
@@ -1,55 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GatewayConnectionState = void 0;
4
- /**
5
- * Gateway connection state manager.
6
- *
7
- * Online-only model: State evaporates immediately on disconnect.
8
- * No 12-hour windows, no persistent state.
9
- *
10
- * Note: WebSocket type is runtime-dependent (browser WebSocket or 'ws' package).
11
- */
12
- class GatewayConnectionState {
13
- connections = new Map(); // did → socket
14
- /**
15
- * Register agent connection.
16
- *
17
- * @param did - DID of the connecting agent
18
- * @param socket - WebSocket connection (browser or Node.js 'ws' package)
19
- */
20
- connect(did, socket) {
21
- this.connections.set(did, socket);
22
- // Handle close event (works for both browser and Node.js ws)
23
- if (typeof socket.on === 'function') {
24
- // Node.js 'ws' package style
25
- socket.on('close', () => {
26
- this.connections.delete(did); // Immediate evaporation
27
- });
28
- }
29
- else if (socket.addEventListener) {
30
- // Browser WebSocket style
31
- socket.addEventListener('close', () => {
32
- this.connections.delete(did);
33
- });
34
- }
35
- }
36
- /**
37
- * Check if agent is currently online.
38
- */
39
- isOnline(did) {
40
- return this.connections.has(did);
41
- }
42
- /**
43
- * Get WebSocket for online agent (or null if offline).
44
- */
45
- getSocket(did) {
46
- return this.connections.get(did) ?? null;
47
- }
48
- /**
49
- * Get all online DIDs.
50
- */
51
- getOnlineDids() {
52
- return Array.from(this.connections.keys());
53
- }
54
- }
55
- exports.GatewayConnectionState = GatewayConnectionState;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GatewayConnectionState=void 0;class GatewayConnectionState{connections=new Map;connect(e,n){this.connections.set(e,n),"function"==typeof n.on?n.on("close",()=>{this.connections.delete(e)}):n.addEventListener&&n.addEventListener("close",()=>{this.connections.delete(e)})}isOnline(e){return this.connections.has(e)}getSocket(e){return this.connections.get(e)??null}getOnlineDids(){return Array.from(this.connections.keys())}}exports.GatewayConnectionState=GatewayConnectionState;
@@ -1,120 +1 @@
1
- "use strict";
2
- /**
3
- * Gateway transport adapter for delivering envelopes to Xail inbox users.
4
- *
5
- * Sends envelopes via POST /gateway/deliver on the hosted gateway API.
6
- * For agent-to-agent (M2M), use HttpsTransportAdapter with direct URLs.
7
- * Optionally polls for incoming messages.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.GatewayTransport = void 0;
11
- const shared_1 = require("../_deps/shared/index.js");
12
- /**
13
- * Transport adapter for the Xail Gateway.
14
- *
15
- * Sends envelopes via POST /gateway/deliver with API key auth.
16
- * Optionally polls GET /gateway/messages/:did for incoming messages.
17
- */
18
- class GatewayTransport {
19
- apiKey;
20
- gateway;
21
- timeoutMs;
22
- fetchFn;
23
- pollIntervalMs;
24
- handlers = [];
25
- pollTimer = null;
26
- senderDid = null;
27
- constructor(opts) {
28
- this.apiKey = opts.apiKey;
29
- this.gateway = opts.gateway.replace(/\/$/, '');
30
- this.timeoutMs = opts.timeoutMs ?? 15_000;
31
- this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
32
- this.pollIntervalMs = opts.pollIntervalMs ?? 0;
33
- }
34
- /**
35
- * Send a signed envelope to a recipient via the gateway.
36
- * @param envelope - The signed transport envelope.
37
- * @param _recipientDid - Recipient DID (already in envelope.recipient).
38
- * @returns Success or transport error.
39
- */
40
- async send(envelope, _recipientDid) {
41
- const url = `${this.gateway}/gateway/deliver`;
42
- try {
43
- const controller = new AbortController();
44
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
45
- const response = await this.fetchFn(url, {
46
- method: 'POST',
47
- headers: {
48
- 'Content-Type': 'application/json',
49
- 'Authorization': `Bearer ${this.apiKey}`,
50
- },
51
- body: JSON.stringify(envelope),
52
- signal: controller.signal,
53
- });
54
- clearTimeout(timer);
55
- if (!response.ok) {
56
- return (0, shared_1.err)(response.status === 404
57
- ? 'RECIPIENT_UNREACHABLE'
58
- : 'SEND_FAILED');
59
- }
60
- return (0, shared_1.ok)(undefined);
61
- }
62
- catch (e) {
63
- if (e instanceof DOMException && e.name === 'AbortError') {
64
- return (0, shared_1.err)('TIMEOUT');
65
- }
66
- return (0, shared_1.err)('NETWORK_ERROR');
67
- }
68
- }
69
- /** Register a handler for incoming envelopes. */
70
- onReceive(handler) {
71
- this.handlers.push(handler);
72
- }
73
- /**
74
- * Start polling for incoming messages.
75
- * Must be called after Agent.create() sets the sender DID.
76
- * @param did - The agent's own DID for polling.
77
- */
78
- startPolling(did) {
79
- this.senderDid = did;
80
- if (this.pollIntervalMs > 0 && !this.pollTimer) {
81
- this.pollTimer = setInterval(() => void this.poll(), this.pollIntervalMs);
82
- }
83
- }
84
- /** Shut down the transport (stop polling, clear handlers). */
85
- dispose() {
86
- if (this.pollTimer) {
87
- clearInterval(this.pollTimer);
88
- this.pollTimer = null;
89
- }
90
- this.handlers = [];
91
- }
92
- /** Poll for incoming messages and dispatch to handlers. */
93
- async poll() {
94
- if (!this.senderDid)
95
- return;
96
- try {
97
- const url = `${this.gateway}/gateway/messages/${encodeURIComponent(this.senderDid)}`;
98
- const res = await this.fetchFn(url, {
99
- headers: { Authorization: `Bearer ${this.apiKey}` },
100
- });
101
- if (!res.ok)
102
- return;
103
- const data = (await res.json());
104
- for (const msg of data.messages) {
105
- for (const handler of this.handlers) {
106
- handler(msg.envelope);
107
- }
108
- // Ack delivery
109
- await this.fetchFn(`${this.gateway}/gateway/ack/${msg.id}`, {
110
- method: 'POST',
111
- headers: { Authorization: `Bearer ${this.apiKey}` },
112
- });
113
- }
114
- }
115
- catch {
116
- // Silent failure — polling errors are non-fatal
117
- }
118
- }
119
- }
120
- exports.GatewayTransport = GatewayTransport;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GatewayTransport=void 0;const shared_1=require("../_deps/shared/index.js");class GatewayTransport{apiKey;gateway;timeoutMs;fetchFn;pollIntervalMs;handlers=[];pollTimer=null;senderDid=null;constructor(e){this.apiKey=e.apiKey,this.gateway=e.gateway.replace(/\/$/,""),this.timeoutMs=e.timeoutMs??15e3,this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.pollIntervalMs=e.pollIntervalMs??0}async send(e,t){const s=`${this.gateway}/gateway/deliver`;try{const t=new AbortController,a=setTimeout(()=>t.abort(),this.timeoutMs),r=await this.fetchFn(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e),signal:t.signal});return clearTimeout(a),r.ok?(0,shared_1.ok)(void 0):(0,shared_1.err)(404===r.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(e){return e instanceof DOMException&&"AbortError"===e.name?(0,shared_1.err)("TIMEOUT"):(0,shared_1.err)("NETWORK_ERROR")}}onReceive(e){this.handlers.push(e)}startPolling(e){this.senderDid=e,this.pollIntervalMs>0&&!this.pollTimer&&(this.pollTimer=setInterval(()=>{this.poll()},this.pollIntervalMs))}dispose(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.handlers=[]}async poll(){if(this.senderDid)try{const e=`${this.gateway}/gateway/messages/${encodeURIComponent(this.senderDid)}`,t=await this.fetchFn(e,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!t.ok)return;const s=await t.json();for(const e of s.messages){for(const t of this.handlers)t(e.envelope);await this.fetchFn(`${this.gateway}/gateway/ack/${e.id}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`}})}}catch{}}}exports.GatewayTransport=GatewayTransport;