@private.me/xbind 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  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.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,488 +1 @@
1
- /**
2
- * @module trace-spans
3
- * Distributed tracing spans with parent-child relationships
4
- *
5
- * Provides span tracking for distributed tracing with automatic timing,
6
- * attribute collection, and integration with W3C Trace Context.
7
- *
8
- * Performance target: <1ms overhead per operation
9
- *
10
- * Usage:
11
- * ```typescript
12
- * import { TraceSpan, SpanRecorder } from '@private.me/xbind';
13
- *
14
- * // Create a span recorder
15
- * const recorder = new SpanRecorder();
16
- *
17
- * // Start a span
18
- * const span = recorder.startSpan('operation-name', { attr: 'value' });
19
- *
20
- * // Do work...
21
- *
22
- * // End the span
23
- * span.end();
24
- *
25
- * // Get completed spans
26
- * const spans = recorder.getCompletedSpans();
27
- * ```
28
- */
29
- import { TraceContext, generateSpanId } from './trace-context.js';
30
- /**
31
- * Span status codes (aligned with OpenTelemetry)
32
- */
33
- export var SpanStatusCode;
34
- (function (SpanStatusCode) {
35
- /** Operation completed successfully */
36
- SpanStatusCode[SpanStatusCode["OK"] = 0] = "OK";
37
- /** Operation encountered an error */
38
- SpanStatusCode[SpanStatusCode["ERROR"] = 1] = "ERROR";
39
- /** Status is unset (default) */
40
- SpanStatusCode[SpanStatusCode["UNSET"] = 2] = "UNSET";
41
- })(SpanStatusCode || (SpanStatusCode = {}));
42
- /**
43
- * Span kind (aligned with OpenTelemetry)
44
- */
45
- export var SpanKind;
46
- (function (SpanKind) {
47
- /** Internal span (default) */
48
- SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL";
49
- /** Server span (handling incoming request) */
50
- SpanKind[SpanKind["SERVER"] = 1] = "SERVER";
51
- /** Client span (outgoing request) */
52
- SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT";
53
- /** Producer span (message queue producer) */
54
- SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER";
55
- /** Consumer span (message queue consumer) */
56
- SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER";
57
- })(SpanKind || (SpanKind = {}));
58
- /**
59
- * Trace span for distributed tracing
60
- *
61
- * Represents a single unit of work in a distributed trace with automatic timing.
62
- */
63
- export class TraceSpan {
64
- /** Span ID (unique within trace) */
65
- spanId;
66
- /** Trace context */
67
- traceContext;
68
- /** Span name */
69
- name;
70
- /** Span kind */
71
- kind;
72
- /** Parent span ID */
73
- parentSpanId;
74
- /** Start timestamp (milliseconds since epoch) */
75
- startTime;
76
- /** End timestamp (milliseconds since epoch, undefined if not ended) */
77
- endTime;
78
- /** Span status */
79
- status;
80
- /** Span attributes */
81
- attributes;
82
- /** Span events */
83
- events;
84
- /** Whether span has ended */
85
- ended;
86
- /**
87
- * Create a trace span
88
- *
89
- * @param name - Span name
90
- * @param traceContext - Trace context
91
- * @param options - Span options
92
- */
93
- constructor(name, traceContext, options = {}) {
94
- this.spanId = generateSpanId();
95
- this.traceContext = traceContext;
96
- this.name = name;
97
- this.kind = options.kind ?? SpanKind.INTERNAL;
98
- this.parentSpanId = options.parentSpanId;
99
- this.startTime = Date.now();
100
- this.status = { code: SpanStatusCode.UNSET };
101
- this.attributes = options.attributes ?? {};
102
- this.events = [];
103
- this.ended = false;
104
- }
105
- /**
106
- * Set span attribute
107
- *
108
- * @param key - Attribute key
109
- * @param value - Attribute value
110
- * @returns This span (for chaining)
111
- */
112
- setAttribute(key, value) {
113
- if (this.ended) {
114
- throw new Error('Cannot set attribute on ended span');
115
- }
116
- this.attributes[key] = value;
117
- return this;
118
- }
119
- /**
120
- * Set multiple span attributes
121
- *
122
- * @param attributes - Attributes to set
123
- * @returns This span (for chaining)
124
- */
125
- setAttributes(attributes) {
126
- if (this.ended) {
127
- throw new Error('Cannot set attributes on ended span');
128
- }
129
- Object.assign(this.attributes, attributes);
130
- return this;
131
- }
132
- /**
133
- * Add an event to the span
134
- *
135
- * Events are timestamped log entries within a span.
136
- *
137
- * @param name - Event name
138
- * @param attributes - Optional event attributes
139
- * @returns This span (for chaining)
140
- */
141
- addEvent(name, attributes) {
142
- if (this.ended) {
143
- throw new Error('Cannot add event to ended span');
144
- }
145
- this.events.push({
146
- name,
147
- timestamp: Date.now(),
148
- attributes,
149
- });
150
- return this;
151
- }
152
- /**
153
- * Set span status
154
- *
155
- * @param code - Status code
156
- * @param message - Optional status message
157
- * @returns This span (for chaining)
158
- */
159
- setStatus(code, message) {
160
- if (this.ended) {
161
- throw new Error('Cannot set status on ended span');
162
- }
163
- this.status = { code, message };
164
- return this;
165
- }
166
- /**
167
- * Record an exception in the span
168
- *
169
- * Automatically sets status to ERROR and adds exception event.
170
- *
171
- * @param error - Error to record
172
- * @returns This span (for chaining)
173
- */
174
- recordException(error) {
175
- if (this.ended) {
176
- throw new Error('Cannot record exception on ended span');
177
- }
178
- this.setStatus(SpanStatusCode.ERROR);
179
- const attributes = {};
180
- if (error instanceof Error) {
181
- attributes['exception.type'] = error.name;
182
- attributes['exception.message'] = error.message;
183
- if (error.stack) {
184
- attributes['exception.stacktrace'] = error.stack;
185
- }
186
- }
187
- else {
188
- attributes['exception.message'] = String(error);
189
- }
190
- this.addEvent('exception', attributes);
191
- return this;
192
- }
193
- /**
194
- * End the span
195
- *
196
- * Records the end timestamp and marks the span as complete.
197
- * If status is UNSET, automatically sets to OK.
198
- *
199
- * @param endTime - Optional end timestamp (defaults to now)
200
- */
201
- end(endTime) {
202
- if (this.ended) {
203
- return; // Idempotent
204
- }
205
- this.endTime = endTime ?? Date.now();
206
- this.ended = true;
207
- // Auto-set status to OK if unset
208
- if (this.status.code === SpanStatusCode.UNSET) {
209
- this.status = { code: SpanStatusCode.OK };
210
- }
211
- }
212
- /**
213
- * Check if span has ended
214
- *
215
- * @returns True if ended
216
- */
217
- isEnded() {
218
- return this.ended;
219
- }
220
- /**
221
- * Get span duration in milliseconds
222
- *
223
- * @returns Duration or null if not ended
224
- */
225
- getDuration() {
226
- if (!this.ended || !this.endTime)
227
- return null;
228
- return this.endTime - this.startTime;
229
- }
230
- /**
231
- * Export span data
232
- *
233
- * @returns Span data (throws if span not ended)
234
- */
235
- toData() {
236
- if (!this.ended || !this.endTime) {
237
- throw new Error('Cannot export data from active span. Call end() first.');
238
- }
239
- return {
240
- spanId: this.spanId,
241
- traceId: this.traceContext.traceId,
242
- parentSpanId: this.parentSpanId,
243
- name: this.name,
244
- kind: this.kind,
245
- startTime: this.startTime,
246
- endTime: this.endTime,
247
- duration: this.endTime - this.startTime,
248
- status: { ...this.status },
249
- attributes: { ...this.attributes },
250
- events: this.events.map((e) => ({
251
- name: e.name,
252
- timestamp: e.timestamp,
253
- attributes: e.attributes ? { ...e.attributes } : undefined,
254
- })),
255
- };
256
- }
257
- /**
258
- * Create a child span
259
- *
260
- * The child span will have the same trace ID but a new span ID.
261
- *
262
- * @param name - Child span name
263
- * @param options - Span options
264
- * @returns New child span
265
- */
266
- createChild(name, options = {}) {
267
- return new TraceSpan(name, this.traceContext, {
268
- ...options,
269
- parentSpanId: this.spanId,
270
- });
271
- }
272
- }
273
- /**
274
- * Span recorder for collecting completed spans
275
- *
276
- * Manages span lifecycle and provides access to completed span data.
277
- */
278
- export class SpanRecorder {
279
- /** Active spans (not yet ended) */
280
- activeSpans;
281
- /** Completed spans */
282
- completedSpans;
283
- /** Maximum number of completed spans to keep (prevent memory leak) */
284
- maxSpans;
285
- /** Trace context for root spans */
286
- rootContext;
287
- /**
288
- * Create a span recorder
289
- *
290
- * @param options - Recorder options
291
- */
292
- constructor(options = {}) {
293
- this.activeSpans = new Map();
294
- this.completedSpans = [];
295
- this.maxSpans = options.maxSpans ?? 1000;
296
- this.rootContext = options.traceContext;
297
- }
298
- /**
299
- * Start a new span
300
- *
301
- * @param name - Span name
302
- * @param options - Span options
303
- * @returns New span
304
- */
305
- startSpan(name, options = {}) {
306
- const context = options.traceContext ??
307
- options.parentSpan?.traceContext ??
308
- this.rootContext ??
309
- TraceContext.create();
310
- const span = new TraceSpan(name, context, {
311
- kind: options.kind,
312
- attributes: options.attributes,
313
- parentSpanId: options.parentSpan?.spanId,
314
- });
315
- this.activeSpans.set(span.spanId, span);
316
- // Auto-end on next tick if forgotten (safety measure)
317
- // This prevents memory leaks from forgotten spans
318
- const timeout = setTimeout(() => {
319
- if (!span.isEnded()) {
320
- span.setStatus(SpanStatusCode.ERROR, 'Span not ended (auto-ended by recorder)');
321
- this.endSpan(span);
322
- }
323
- }, 60000); // 60 second timeout
324
- // Clear timeout if span ends normally
325
- const originalEnd = span.end.bind(span);
326
- span.end = (endTime) => {
327
- clearTimeout(timeout);
328
- originalEnd(endTime);
329
- this.endSpan(span);
330
- };
331
- return span;
332
- }
333
- /**
334
- * End a span and record its data
335
- *
336
- * @param span - Span to end
337
- */
338
- endSpan(span) {
339
- if (!span.isEnded()) {
340
- span.end();
341
- }
342
- // Remove from active spans
343
- this.activeSpans.delete(span.spanId);
344
- // Add to completed spans
345
- const data = span.toData();
346
- this.completedSpans.push(data);
347
- // Enforce max spans limit (FIFO)
348
- if (this.completedSpans.length > this.maxSpans) {
349
- this.completedSpans.shift();
350
- }
351
- }
352
- /**
353
- * Get all completed spans
354
- *
355
- * @returns Array of completed span data
356
- */
357
- getCompletedSpans() {
358
- return [...this.completedSpans];
359
- }
360
- /**
361
- * Get active spans
362
- *
363
- * @returns Array of active spans
364
- */
365
- getActiveSpans() {
366
- return Array.from(this.activeSpans.values());
367
- }
368
- /**
369
- * Clear all completed spans
370
- */
371
- clearCompletedSpans() {
372
- this.completedSpans = [];
373
- }
374
- /**
375
- * Get span count
376
- *
377
- * @returns Object with active and completed span counts
378
- */
379
- getSpanCount() {
380
- return {
381
- active: this.activeSpans.size,
382
- completed: this.completedSpans.length,
383
- };
384
- }
385
- /**
386
- * Find completed spans by trace ID
387
- *
388
- * @param traceId - Trace ID to search for
389
- * @returns Array of matching spans
390
- */
391
- findSpansByTraceId(traceId) {
392
- return this.completedSpans.filter((span) => span.traceId === traceId);
393
- }
394
- /**
395
- * Build trace tree from completed spans
396
- *
397
- * Groups spans by trace ID and builds parent-child relationships.
398
- *
399
- * @param traceId - Trace ID to build tree for
400
- * @returns Tree structure
401
- */
402
- buildTraceTree(traceId) {
403
- const spans = this.findSpansByTraceId(traceId);
404
- if (spans.length === 0)
405
- return null;
406
- // Find root span (no parent)
407
- const root = spans.find((s) => !s.parentSpanId);
408
- if (!root)
409
- return null;
410
- // Build tree recursively
411
- return buildSpanTreeNode(root, spans);
412
- }
413
- }
414
- /**
415
- * Build span tree node recursively
416
- *
417
- * @param span - Current span
418
- * @param allSpans - All spans in trace
419
- * @returns Tree node
420
- */
421
- function buildSpanTreeNode(span, allSpans) {
422
- const children = allSpans
423
- .filter((s) => s.parentSpanId === span.spanId)
424
- .map((child) => buildSpanTreeNode(child, allSpans));
425
- return { span, children };
426
- }
427
- /**
428
- * Helper function to measure async operation with automatic span tracking
429
- *
430
- * @param recorder - Span recorder
431
- * @param name - Span name
432
- * @param fn - Async function to measure
433
- * @param options - Span options
434
- * @returns Result of async function
435
- *
436
- * @example
437
- * ```typescript
438
- * const result = await measureAsync(recorder, 'database-query', async () => {
439
- * return await db.query('SELECT * FROM users');
440
- * });
441
- * ```
442
- */
443
- export async function measureAsync(recorder, name, fn, options) {
444
- const span = recorder.startSpan(name, options);
445
- try {
446
- const result = await fn();
447
- span.setStatus(SpanStatusCode.OK);
448
- return result;
449
- }
450
- catch (error) {
451
- span.recordException(error);
452
- throw error;
453
- }
454
- finally {
455
- span.end();
456
- }
457
- }
458
- /**
459
- * Helper function to measure sync operation with automatic span tracking
460
- *
461
- * @param recorder - Span recorder
462
- * @param name - Span name
463
- * @param fn - Sync function to measure
464
- * @param options - Span options
465
- * @returns Result of sync function
466
- *
467
- * @example
468
- * ```typescript
469
- * const result = measureSync(recorder, 'encryption', () => {
470
- * return encrypt(data, key);
471
- * });
472
- * ```
473
- */
474
- export function measureSync(recorder, name, fn, options) {
475
- const span = recorder.startSpan(name, options);
476
- try {
477
- const result = fn();
478
- span.setStatus(SpanStatusCode.OK);
479
- return result;
480
- }
481
- catch (error) {
482
- span.recordException(error);
483
- throw error;
484
- }
485
- finally {
486
- span.end();
487
- }
488
- }
1
+ import{TraceContext,generateSpanId}from"./trace-context.js";export var SpanStatusCode;!function(t){t[t.OK=0]="OK",t[t.ERROR=1]="ERROR",t[t.UNSET=2]="UNSET"}(SpanStatusCode||(SpanStatusCode={}));export var SpanKind;!function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"}(SpanKind||(SpanKind={}));export class TraceSpan{spanId;traceContext;name;kind;parentSpanId;startTime;endTime;status;attributes;events;ended;constructor(t,e,n={}){this.spanId=generateSpanId(),this.traceContext=e,this.name=t,this.kind=n.kind??SpanKind.INTERNAL,this.parentSpanId=n.parentSpanId,this.startTime=Date.now(),this.status={code:SpanStatusCode.UNSET},this.attributes=n.attributes??{},this.events=[],this.ended=!1}setAttribute(t,e){if(this.ended)throw new Error("Cannot set attribute on ended span");return this.attributes[t]=e,this}setAttributes(t){if(this.ended)throw new Error("Cannot set attributes on ended span");return Object.assign(this.attributes,t),this}addEvent(t,e){if(this.ended)throw new Error("Cannot add event to ended span");return this.events.push({name:t,timestamp:Date.now(),attributes:e}),this}setStatus(t,e){if(this.ended)throw new Error("Cannot set status on ended span");return this.status={code:t,message:e},this}recordException(t){if(this.ended)throw new Error("Cannot record exception on ended span");this.setStatus(SpanStatusCode.ERROR);const e={};return t instanceof Error?(e["exception.type"]=t.name,e["exception.message"]=t.message,t.stack&&(e["exception.stacktrace"]=t.stack)):e["exception.message"]=String(t),this.addEvent("exception",e),this}end(t){this.ended||(this.endTime=t??Date.now(),this.ended=!0,this.status.code===SpanStatusCode.UNSET&&(this.status={code:SpanStatusCode.OK}))}isEnded(){return this.ended}getDuration(){return this.ended&&this.endTime?this.endTime-this.startTime:null}toData(){if(!this.ended||!this.endTime)throw new Error("Cannot export data from active span. Call end() first.");return{spanId:this.spanId,traceId:this.traceContext.traceId,parentSpanId:this.parentSpanId,name:this.name,kind:this.kind,startTime:this.startTime,endTime:this.endTime,duration:this.endTime-this.startTime,status:{...this.status},attributes:{...this.attributes},events:this.events.map(t=>({name:t.name,timestamp:t.timestamp,attributes:t.attributes?{...t.attributes}:void 0}))}}createChild(t,e={}){return new TraceSpan(t,this.traceContext,{...e,parentSpanId:this.spanId})}}export class SpanRecorder{activeSpans;completedSpans;maxSpans;rootContext;constructor(t={}){this.activeSpans=new Map,this.completedSpans=[],this.maxSpans=t.maxSpans??1e3,this.rootContext=t.traceContext}startSpan(t,e={}){const n=e.traceContext??e.parentSpan?.traceContext??this.rootContext??TraceContext.create(),a=new TraceSpan(t,n,{kind:e.kind,attributes:e.attributes,parentSpanId:e.parentSpan?.spanId});this.activeSpans.set(a.spanId,a);const s=setTimeout(()=>{a.isEnded()||(a.setStatus(SpanStatusCode.ERROR,"Span not ended (auto-ended by recorder)"),this.endSpan(a))},6e4),r=a.end.bind(a);return a.end=t=>{clearTimeout(s),r(t),this.endSpan(a)},a}endSpan(t){t.isEnded()||t.end(),this.activeSpans.delete(t.spanId);const e=t.toData();this.completedSpans.push(e),this.completedSpans.length>this.maxSpans&&this.completedSpans.shift()}getCompletedSpans(){return[...this.completedSpans]}getActiveSpans(){return Array.from(this.activeSpans.values())}clearCompletedSpans(){this.completedSpans=[]}getSpanCount(){return{active:this.activeSpans.size,completed:this.completedSpans.length}}findSpansByTraceId(t){return this.completedSpans.filter(e=>e.traceId===t)}buildTraceTree(t){const e=this.findSpansByTraceId(t);if(0===e.length)return null;const n=e.find(t=>!t.parentSpanId);return n?buildSpanTreeNode(n,e):null}}function buildSpanTreeNode(t,e){const n=e.filter(e=>e.parentSpanId===t.spanId).map(t=>buildSpanTreeNode(t,e));return{span:t,children:n}}export async function measureAsync(t,e,n,a){const s=t.startSpan(e,a);try{const t=await n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}export function measureSync(t,e,n,a){const s=t.startSpan(e,a);try{const t=n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}
@@ -1,7 +1,7 @@
1
1
  import type { Result } from '@private.me/shared';
2
2
  import type { AnyTransportEnvelope } from './envelope.js';
3
3
  /** Transport-level error codes. */
4
- export type TransportError = 'SEND_FAILED' | 'NETWORK_ERROR' | 'RECIPIENT_UNREACHABLE' | 'TIMEOUT';
4
+ export type TransportError = 'SEND_FAILED' | 'NETWORK_ERROR' | 'RECIPIENT_UNREACHABLE' | 'TIMEOUT' | 'HTTPS_REQUIRED' | 'INVALID_URL';
5
5
  /** Handler invoked when an envelope is received. */
6
6
  export type EnvelopeHandler = (envelope: AnyTransportEnvelope) => void;
7
7
  /**
@@ -1,59 +1 @@
1
- import { ok, err } from"./_deps/shared/index.js";
2
- /**
3
- * HTTPS transport adapter — sends envelopes as JSON POST requests.
4
- *
5
- * Recipient URL resolved as: baseUrl/deliver/{recipientDid}
6
- * This is the SDK's default transport for server-to-server delivery.
7
- */
8
- export class HttpsTransportAdapter {
9
- baseUrl;
10
- timeoutMs;
11
- fetchFn;
12
- handlers = [];
13
- constructor(opts) {
14
- this.baseUrl = opts.baseUrl.replace(/\/$/, '');
15
- this.timeoutMs = opts.timeoutMs ?? 10_000;
16
- this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
17
- }
18
- async send(envelope, recipientDid) {
19
- const url = `${this.baseUrl}/deliver/${encodeURIComponent(recipientDid)}`;
20
- try {
21
- const controller = new AbortController();
22
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
23
- const response = await this.fetchFn(url, {
24
- method: 'POST',
25
- headers: { 'Content-Type': 'application/json' },
26
- body: JSON.stringify(envelope),
27
- signal: controller.signal,
28
- });
29
- clearTimeout(timer);
30
- if (!response.ok) {
31
- return err(response.status === 404
32
- ? 'RECIPIENT_UNREACHABLE'
33
- : 'SEND_FAILED');
34
- }
35
- return ok(undefined);
36
- }
37
- catch (e) {
38
- if (e instanceof DOMException && e.name === 'AbortError') {
39
- return err('TIMEOUT');
40
- }
41
- return err('NETWORK_ERROR');
42
- }
43
- }
44
- onReceive(handler) {
45
- this.handlers.push(handler);
46
- }
47
- /**
48
- * Dispatch a received envelope to all handlers.
49
- * Called by the server when an incoming POST is received.
50
- */
51
- dispatch(envelope) {
52
- for (const handler of this.handlers) {
53
- handler(envelope);
54
- }
55
- }
56
- dispose() {
57
- this.handlers = [];
58
- }
59
- }
1
+ import{ok,err}from"./_deps/shared/index.js";export class HttpsTransportAdapter{baseUrl;timeoutMs;fetchFn;handlers=[];constructor(t){if(!t.baseUrl||"string"!=typeof t.baseUrl)throw new TypeError("HttpsTransportOptions.baseUrl is required and must be a string");if(0===t.baseUrl.trim().length)throw new TypeError("HttpsTransportOptions.baseUrl cannot be empty");this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeoutMs=t.timeoutMs??1e4,this.fetchFn=t.fetch??globalThis.fetch.bind(globalThis)}async send(t,e){try{const t=new URL(this.baseUrl),e=t.hostname.toLowerCase(),r="127.0.0.1"===e||"localhost"===e||"[::1]"===e||"::1"===e||e.startsWith("127.")||e.endsWith(".localhost");if("https:"!==t.protocol&&!r)return err("HTTPS_REQUIRED")}catch{return err("INVALID_URL")}const r=`${this.baseUrl}/deliver/${encodeURIComponent(e)}`;try{const e=new AbortController,s=setTimeout(()=>e.abort(),this.timeoutMs),o=await this.fetchFn(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:e.signal});return clearTimeout(s),o.ok?ok(void 0):err(404===o.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(t){return t instanceof DOMException&&"AbortError"===t.name?err("TIMEOUT"):err("NETWORK_ERROR")}}onReceive(t){this.handlers.push(t)}dispatch(t){for(const e of this.handlers)e(t)}dispose(){this.handlers=[]}}
@@ -82,7 +82,7 @@ export interface RegistryEntry {
82
82
  readonly publicKey: Uint8Array;
83
83
  readonly name: string;
84
84
  readonly scopes: ReadonlySet<string>;
85
- /** Scopes this agent accepts for incoming messages. Undefined = accept all. */
85
+ /** Scopes this agent accepts for incoming messages. Undefined = defaults to send scopes. */
86
86
  readonly receiveScopes?: ReadonlySet<string>;
87
87
  readonly revoked: boolean;
88
88
  /** Optional X25519 public key for ECDH forward secrecy. */
@@ -222,7 +222,7 @@ export declare class HttpTrustRegistry implements TrustRegistry {
222
222
  constructor(opts: HttpTrustRegistryOptions);
223
223
  /** Clear all cached entries. Call after registration or revocation. */
224
224
  clearCache(): void;
225
- register(did: string, publicKey: Uint8Array, name: string, scopes?: string[], x25519PublicKey?: Uint8Array, mlKemPublicKey?: Uint8Array, mlDsaPublicKey?: Uint8Array, xchange?: boolean, receiveScopes?: string[], sdkVersion?: string, minEnvelopeVersion?: number, maxEnvelopeVersion?: number, ttlMs?: number, clientIP?: string): Promise<Result<void, RegistryError>>;
225
+ register(did: string, publicKey: Uint8Array, name: string, scopes?: string[], x25519PublicKey?: Uint8Array, mlKemPublicKey?: Uint8Array, mlDsaPublicKey?: Uint8Array, xchange?: boolean, receiveScopes?: string[], sdkVersion?: string, minEnvelopeVersion?: number, maxEnvelopeVersion?: number, ttlMs?: number, _clientIP?: string): Promise<Result<void, RegistryError>>;
226
226
  resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
227
227
  hasScope(did: string, scope: string): Promise<boolean>;
228
228
  hasReceiveScope(did: string, scope: string): Promise<boolean>;
@@ -322,7 +322,7 @@ export declare class FileTrustRegistry implements TrustRegistry {
322
322
  private init;
323
323
  /** Append record to JSONL file. */
324
324
  private append;
325
- register(did: string, publicKey: Uint8Array, name: string, scopes?: string[], x25519PublicKey?: Uint8Array, mlKemPublicKey?: Uint8Array, mlDsaPublicKey?: Uint8Array, xchange?: boolean, receiveScopes?: string[], sdkVersion?: string, minEnvelopeVersion?: number, maxEnvelopeVersion?: number, ttlMs?: number, clientIP?: string): Promise<Result<void, RegistryError>>;
325
+ register(did: string, publicKey: Uint8Array, name: string, scopes?: string[], x25519PublicKey?: Uint8Array, mlKemPublicKey?: Uint8Array, mlDsaPublicKey?: Uint8Array, xchange?: boolean, receiveScopes?: string[], sdkVersion?: string, minEnvelopeVersion?: number, maxEnvelopeVersion?: number, ttlMs?: number, _clientIP?: string): Promise<Result<void, RegistryError>>;
326
326
  resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
327
327
  hasScope(did: string, scope: string): Promise<boolean>;
328
328
  hasReceiveScope(did: string, scope: string): Promise<boolean>;