@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,332 +1 @@
1
- /**
2
- * @module health-check
3
- * Health check endpoint for operational monitoring and load balancer probes.
4
- *
5
- * Provides three probe types following Kubernetes health check patterns:
6
- * - **Startup probe**: Verify initialization complete (one-time check)
7
- * - **Readiness probe**: Verify dependencies ready (registry, transport)
8
- * - **Liveness probe**: Verify service responsive (self-check)
9
- *
10
- * @example
11
- * ```typescript
12
- * import { createHealthChecker } from '@private.me/xbind';
13
- *
14
- * const checker = createHealthChecker({
15
- * registry: myTrustRegistry,
16
- * transport: myTransport
17
- * });
18
- *
19
- * // Load balancer endpoint
20
- * app.get('/health', async (req, res) => {
21
- * const status = await checker.check();
22
- * res.status(status.healthy ? 200 : 503).json(status);
23
- * });
24
- * ```
25
- */
26
- /* ── Implementation ── */
27
- class HealthCheckerImpl {
28
- startTime;
29
- registry;
30
- transport;
31
- serviceName;
32
- version;
33
- environment;
34
- timeoutMs;
35
- enableStartupProbe;
36
- startupComplete = false;
37
- constructor(options = {}) {
38
- this.startTime = Date.now();
39
- this.registry = options.registry;
40
- this.transport = options.transport;
41
- this.serviceName = options.serviceName;
42
- this.version = options.version;
43
- this.environment = options.environment;
44
- this.timeoutMs = options.timeoutMs ?? 5000;
45
- this.enableStartupProbe = options.enableStartupProbe ?? true;
46
- }
47
- markStartupComplete() {
48
- this.startupComplete = true;
49
- }
50
- isStartupComplete() {
51
- return this.startupComplete;
52
- }
53
- async check(probe = 'readiness') {
54
- const timestamp = new Date().toISOString();
55
- const uptimeSeconds = Math.floor((Date.now() - this.startTime) / 1000);
56
- // Startup probe: Check if initialization complete
57
- if (probe === 'startup' && this.enableStartupProbe) {
58
- const components = [
59
- {
60
- name: 'startup',
61
- status: this.startupComplete ? 'healthy' : 'unhealthy',
62
- message: this.startupComplete
63
- ? 'Initialization complete'
64
- : 'Waiting for startup completion (call markStartupComplete())',
65
- lastCheck: timestamp,
66
- },
67
- ];
68
- return {
69
- healthy: this.startupComplete,
70
- timestamp,
71
- uptimeSeconds,
72
- components,
73
- metadata: this.buildMetadata(),
74
- };
75
- }
76
- // Liveness probe: Basic self-check (service responsive)
77
- if (probe === 'liveness') {
78
- const components = [
79
- {
80
- name: 'self',
81
- status: 'healthy',
82
- message: 'Service responsive',
83
- lastCheck: timestamp,
84
- },
85
- ];
86
- return {
87
- healthy: true,
88
- timestamp,
89
- uptimeSeconds,
90
- components,
91
- metadata: this.buildMetadata(),
92
- };
93
- }
94
- // Readiness probe: Check all dependencies
95
- const components = [];
96
- // Check registry if configured
97
- if (this.registry) {
98
- const registryHealth = await this.checkRegistry();
99
- components.push(registryHealth);
100
- }
101
- // Check transport if configured
102
- if (this.transport) {
103
- const transportHealth = await this.checkTransport();
104
- components.push(transportHealth);
105
- }
106
- // If no components configured, return basic health
107
- if (components.length === 0) {
108
- components.push({
109
- name: 'self',
110
- status: 'healthy',
111
- message: 'No dependencies configured',
112
- lastCheck: timestamp,
113
- });
114
- }
115
- // Overall health: healthy if all components healthy
116
- const healthy = components.every((c) => c.status === 'healthy');
117
- return {
118
- healthy,
119
- timestamp,
120
- uptimeSeconds,
121
- components,
122
- metadata: this.buildMetadata(),
123
- };
124
- }
125
- buildMetadata() {
126
- const metadata = {};
127
- if (this.serviceName)
128
- metadata.service = this.serviceName;
129
- if (this.version)
130
- metadata.version = this.version;
131
- if (this.environment)
132
- metadata.environment = this.environment;
133
- return Object.keys(metadata).length > 0 ? metadata : undefined;
134
- }
135
- async checkRegistry() {
136
- const startTime = Date.now();
137
- const lastCheck = new Date().toISOString();
138
- try {
139
- if (!this.registry) {
140
- return {
141
- name: 'registry',
142
- status: 'unhealthy',
143
- message: 'Registry not configured',
144
- lastCheck,
145
- };
146
- }
147
- // Use timeout wrapper
148
- const result = await this.withTimeout(this.registry.resolve('did:xail:health_check_probe'), this.timeoutMs);
149
- const latencyMs = Date.now() - startTime;
150
- // Registry returns Result<Uint8Array, RegistryError>
151
- // For non-existent DIDs, it returns err with NOT_FOUND code (this is healthy behavior)
152
- // For registry errors, it returns err with other error codes (unhealthy)
153
- if (result && typeof result === 'object' && 'ok' in result) {
154
- // Result type - check if ok or err
155
- if (result.ok) {
156
- // Registry found the DID (healthy)
157
- return {
158
- name: 'registry',
159
- status: 'healthy',
160
- message: 'Registry responding',
161
- latencyMs,
162
- lastCheck,
163
- };
164
- }
165
- else {
166
- // Registry returned an error
167
- const errorCode = typeof result.error === 'string' ? result.error : 'UNKNOWN';
168
- // NOT_FOUND is healthy (registry works, DID doesn't exist)
169
- if (errorCode.includes('NOT_FOUND')) {
170
- return {
171
- name: 'registry',
172
- status: 'healthy',
173
- message: 'Registry responding',
174
- latencyMs,
175
- lastCheck,
176
- };
177
- }
178
- // Other errors are unhealthy
179
- return {
180
- name: 'registry',
181
- status: 'unhealthy',
182
- message: `Registry error: ${errorCode}`,
183
- latencyMs,
184
- lastCheck,
185
- };
186
- }
187
- }
188
- // Fallback: if result is anything else, assume healthy
189
- return {
190
- name: 'registry',
191
- status: 'healthy',
192
- message: 'Registry responding',
193
- latencyMs,
194
- lastCheck,
195
- };
196
- }
197
- catch (error) {
198
- const latencyMs = Date.now() - startTime;
199
- const message = error instanceof Error ? error.message : 'Unknown error';
200
- // Timeout is degraded (slow but responsive)
201
- if (message.toLowerCase().includes('timeout')) {
202
- return {
203
- name: 'registry',
204
- status: 'degraded',
205
- message: `Registry slow (>${this.timeoutMs}ms)`,
206
- latencyMs,
207
- lastCheck,
208
- };
209
- }
210
- // Other errors are unhealthy
211
- return {
212
- name: 'registry',
213
- status: 'unhealthy',
214
- message: `Registry error: ${message}`,
215
- latencyMs,
216
- lastCheck,
217
- };
218
- }
219
- }
220
- async checkTransport() {
221
- const startTime = Date.now();
222
- const lastCheck = new Date().toISOString();
223
- try {
224
- if (!this.transport) {
225
- return {
226
- name: 'transport',
227
- status: 'unhealthy',
228
- message: 'Transport not configured',
229
- lastCheck,
230
- };
231
- }
232
- // Transport doesn't expose a health check method, so we check if it's instantiated
233
- // In production, you might want to add a ping() method to XailTransportAdapter
234
- const latencyMs = Date.now() - startTime;
235
- return {
236
- name: 'transport',
237
- status: 'healthy',
238
- message: 'Transport adapter available',
239
- latencyMs,
240
- lastCheck,
241
- };
242
- }
243
- catch (error) {
244
- const latencyMs = Date.now() - startTime;
245
- const message = error instanceof Error ? error.message : 'Unknown error';
246
- return {
247
- name: 'transport',
248
- status: 'unhealthy',
249
- message: `Transport error: ${message}`,
250
- latencyMs,
251
- lastCheck,
252
- };
253
- }
254
- }
255
- async withTimeout(promise, timeoutMs) {
256
- return Promise.race([
257
- promise,
258
- new Promise((_, reject) => setTimeout(() => reject(new Error('Health check timeout')), timeoutMs)),
259
- ]);
260
- }
261
- }
262
- /* ── Public API ── */
263
- /**
264
- * Create a health checker instance.
265
- *
266
- * @param options - Configuration options
267
- * @returns Health checker instance
268
- *
269
- * @example
270
- * ```typescript
271
- * const checker = createHealthChecker({
272
- * registry: agent.registry,
273
- * transport: agent.transport,
274
- * serviceName: 'my-service',
275
- * version: '1.0.0'
276
- * });
277
- *
278
- * // Mark startup complete after initialization
279
- * await agent.register();
280
- * checker.markStartupComplete();
281
- *
282
- * // Check health
283
- * const status = await checker.check('readiness');
284
- * console.log(status.healthy ? 'Ready' : 'Not ready');
285
- * ```
286
- */
287
- export function createHealthChecker(options) {
288
- return new HealthCheckerImpl(options);
289
- }
290
- /**
291
- * Express/Fastify middleware helper for health endpoint.
292
- *
293
- * @param checker - Health checker instance
294
- * @param probe - Probe type (default: 'readiness')
295
- * @returns Request handler
296
- *
297
- * @example
298
- * ```typescript
299
- * const checker = createHealthChecker({ registry, transport });
300
- *
301
- * // Express
302
- * app.get('/health', healthEndpoint(checker));
303
- * app.get('/health/startup', healthEndpoint(checker, 'startup'));
304
- * app.get('/health/liveness', healthEndpoint(checker, 'liveness'));
305
- * app.get('/health/readiness', healthEndpoint(checker, 'readiness'));
306
- * ```
307
- */
308
- export function healthEndpoint(checker, probe = 'readiness') {
309
- return async (_req, res) => {
310
- try {
311
- const status = await checker.check(probe);
312
- const statusCode = status.healthy ? 200 : 503;
313
- res.status(statusCode).json(status);
314
- }
315
- catch (error) {
316
- const message = error instanceof Error ? error.message : 'Unknown error';
317
- res.status(503).json({
318
- healthy: false,
319
- timestamp: new Date().toISOString(),
320
- uptimeSeconds: 0,
321
- components: [
322
- {
323
- name: 'health-check',
324
- status: 'unhealthy',
325
- message: `Health check failed: ${message}`,
326
- lastCheck: new Date().toISOString(),
327
- },
328
- ],
329
- });
330
- }
331
- };
332
- }
1
+ class HealthCheckerImpl{startTime;registry;transport;serviceName;version;environment;timeoutMs;enableStartupProbe;startupComplete=!1;constructor(t={}){this.startTime=Date.now(),this.registry=t.registry,this.transport=t.transport,this.serviceName=t.serviceName,this.version=t.version,this.environment=t.environment,this.timeoutMs=t.timeoutMs??5e3,this.enableStartupProbe=t.enableStartupProbe??!0}markStartupComplete(){this.startupComplete=!0}isStartupComplete(){return this.startupComplete}async check(t="readiness"){const e=(new Date).toISOString(),s=Math.floor((Date.now()-this.startTime)/1e3);if("startup"===t&&this.enableStartupProbe){const t=[{name:"startup",status:this.startupComplete?"healthy":"unhealthy",message:this.startupComplete?"Initialization complete":"Waiting for startup completion (call markStartupComplete())",lastCheck:e}];return{healthy:this.startupComplete,timestamp:e,uptimeSeconds:s,components:t,metadata:this.buildMetadata()}}if("liveness"===t){return{healthy:!0,timestamp:e,uptimeSeconds:s,components:[{name:"self",status:"healthy",message:"Service responsive",lastCheck:e}],metadata:this.buildMetadata()}}const a=[];if(this.registry){const t=await this.checkRegistry();a.push(t)}if(this.transport){const t=await this.checkTransport();a.push(t)}0===a.length&&a.push({name:"self",status:"healthy",message:"No dependencies configured",lastCheck:e});return{healthy:a.every(t=>"healthy"===t.status),timestamp:e,uptimeSeconds:s,components:a,metadata:this.buildMetadata()}}buildMetadata(){const t={};return this.serviceName&&(t.service=this.serviceName),this.version&&(t.version=this.version),this.environment&&(t.environment=this.environment),Object.keys(t).length>0?t:void 0}async checkRegistry(){const t=Date.now(),e=(new Date).toISOString();try{if(!this.registry)return{name:"registry",status:"unhealthy",message:"Registry not configured",lastCheck:e};const s=await this.withTimeout(this.registry.resolve("did:xail:health_check_probe"),this.timeoutMs),a=Date.now()-t;if(s&&"object"==typeof s&&"ok"in s){if(s.ok)return{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e};{const t="string"==typeof s.error?s.error:"UNKNOWN";return t.includes("NOT_FOUND")?{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e}:{name:"registry",status:"unhealthy",message:`Registry error: ${t}`,latencyMs:a,lastCheck:e}}}return{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e}}catch(s){const a=Date.now()-t,r=s instanceof Error?s.message:"Unknown error";return r.toLowerCase().includes("timeout")?{name:"registry",status:"degraded",message:`Registry slow (>${this.timeoutMs}ms)`,latencyMs:a,lastCheck:e}:{name:"registry",status:"unhealthy",message:`Registry error: ${r}`,latencyMs:a,lastCheck:e}}}async checkTransport(){const t=Date.now(),e=(new Date).toISOString();try{if(!this.transport)return{name:"transport",status:"unhealthy",message:"Transport not configured",lastCheck:e};return{name:"transport",status:"healthy",message:"Transport adapter available",latencyMs:Date.now()-t,lastCheck:e}}catch(s){const a=Date.now()-t;return{name:"transport",status:"unhealthy",message:`Transport error: ${s instanceof Error?s.message:"Unknown error"}`,latencyMs:a,lastCheck:e}}}async withTimeout(t,e){return Promise.race([t,new Promise((t,s)=>setTimeout(()=>s(new Error("Health check timeout")),e))])}}export function createHealthChecker(t){return new HealthCheckerImpl(t)}export function healthEndpoint(t,e="readiness"){return async(s,a)=>{try{const s=await t.check(e),r=s.healthy?200:503;a.status(r).json(s)}catch(t){const e=t instanceof Error?t.message:"Unknown error";a.status(503).json({healthy:!1,timestamp:(new Date).toISOString(),uptimeSeconds:0,components:[{name:"health-check",status:"unhealthy",message:`Health check failed: ${e}`,lastCheck:(new Date).toISOString()}]})}}}
@@ -147,4 +147,4 @@ export declare function createGotCompat(): {
147
147
  * const response = await fetch('https://api.example.com/data');
148
148
  * ```
149
149
  */
150
- export declare function wrapFetch(fetchImpl: typeof fetch): typeof xfetch;
150
+ export declare function wrapFetch(_fetchImpl: typeof fetch): typeof xfetch;
@@ -1,267 +1 @@
1
- /**
2
- * @module http-compat
3
- * HTTP client compatibility adapters for xBind auto-upgrade
4
- *
5
- * Provides drop-in replacements for popular HTTP clients (fetch, axios, got)
6
- * that transparently upgrade to xBind when both parties support it.
7
- */
8
- import { xfetch } from './xfetch.js';
9
- /**
10
- * Create axios-compatible HTTP client with xBind auto-upgrade
11
- *
12
- * Drop-in replacement for axios that transparently upgrades to xBind.
13
- *
14
- * @returns Axios-compatible client
15
- *
16
- * @example
17
- * ```typescript
18
- * import { createAxiosCompat } from '@private.me/xbind/http-compat';
19
- *
20
- * const axios = createAxiosCompat();
21
- *
22
- * // Auto-upgrades to xBind if supported
23
- * const response = await axios.get('https://api.example.com/data');
24
- * console.log('Used xBind?', response.xbind?.used);
25
- * console.log('Data:', response.data);
26
- * ```
27
- */
28
- export function createAxiosCompat() {
29
- async function request(config) {
30
- // Normalize config
31
- const cfg = typeof config === 'string' ? { url: config } : config;
32
- const method = cfg.method?.toUpperCase() ?? 'GET';
33
- const url = cfg.baseURL
34
- ? new URL(cfg.url ?? '', cfg.baseURL).toString()
35
- : cfg.url ?? '';
36
- // Build headers
37
- const headers = { ...cfg.headers };
38
- // Build URL with query params
39
- let finalUrl = url;
40
- if (cfg.params) {
41
- const params = new URLSearchParams();
42
- for (const [key, value] of Object.entries(cfg.params)) {
43
- params.append(key, String(value));
44
- }
45
- finalUrl = `${url}?${params.toString()}`;
46
- }
47
- // Build request body
48
- let body;
49
- if (cfg.data) {
50
- if (typeof cfg.data === 'string') {
51
- body = cfg.data;
52
- }
53
- else {
54
- body = JSON.stringify(cfg.data);
55
- headers['Content-Type'] = 'application/json';
56
- }
57
- }
58
- // Convert to xfetch options
59
- const xfetchOpts = {
60
- method,
61
- headers,
62
- body,
63
- timeout: cfg.timeout,
64
- forceXBind: cfg.forceXBind,
65
- disableXBind: cfg.disableXBind,
66
- };
67
- // Make request via xfetch
68
- const response = await xfetch(finalUrl, xfetchOpts);
69
- // Parse response body based on responseType
70
- let data;
71
- const responseType = cfg.responseType ?? 'json';
72
- switch (responseType) {
73
- case 'json':
74
- data = (await response.json());
75
- break;
76
- case 'text':
77
- data = (await response.text());
78
- break;
79
- case 'blob':
80
- data = (await response.blob());
81
- break;
82
- case 'arraybuffer':
83
- data = (await response.arrayBuffer());
84
- break;
85
- default:
86
- data = (await response.json());
87
- }
88
- // Validate status if custom validator provided
89
- if (cfg.validateStatus && !cfg.validateStatus(response.status)) {
90
- throw new Error(`Request failed with status ${response.status}`);
91
- }
92
- // Convert headers to object
93
- const responseHeaders = {};
94
- response.headers.forEach((value, key) => {
95
- responseHeaders[key] = value;
96
- });
97
- return {
98
- data,
99
- status: response.status,
100
- statusText: response.statusText,
101
- headers: responseHeaders,
102
- config: cfg,
103
- xbind: {
104
- used: response.usedXBind,
105
- protocol: response.transport.protocol,
106
- latency: response.transport.latency,
107
- peerDID: response.transport.peerDID,
108
- },
109
- };
110
- }
111
- // Convenience methods
112
- async function get(url, config) {
113
- return request({ ...config, url, method: 'GET' });
114
- }
115
- async function post(url, data, config) {
116
- return request({ ...config, url, method: 'POST', data });
117
- }
118
- async function put(url, data, config) {
119
- return request({ ...config, url, method: 'PUT', data });
120
- }
121
- async function patch(url, data, config) {
122
- return request({ ...config, url, method: 'PATCH', data });
123
- }
124
- async function del(url, config) {
125
- return request({ ...config, url, method: 'DELETE' });
126
- }
127
- return {
128
- request,
129
- get,
130
- post,
131
- put,
132
- patch,
133
- delete: del,
134
- };
135
- }
136
- /**
137
- * Create got-compatible HTTP client with xBind auto-upgrade
138
- *
139
- * Drop-in replacement for got that transparently upgrades to xBind.
140
- *
141
- * @returns Got-compatible client
142
- *
143
- * @example
144
- * ```typescript
145
- * import { createGotCompat } from '@private.me/xbind/http-compat';
146
- *
147
- * const got = createGotCompat();
148
- *
149
- * // Auto-upgrades to xBind if supported
150
- * const response = await got('https://api.example.com/data', {
151
- * responseType: 'json',
152
- * });
153
- * console.log('Used xBind?', response.xbind?.used);
154
- * console.log('Body:', response.body);
155
- * ```
156
- */
157
- export function createGotCompat() {
158
- async function got(url, options) {
159
- // Normalize options
160
- const opts = typeof url === 'string' ? { ...options, url } : url;
161
- const method = opts.method?.toUpperCase() ?? 'GET';
162
- const finalUrl = opts.url ?? '';
163
- // Build headers
164
- const headers = { ...opts.headers };
165
- // Build URL with search params
166
- let urlWithParams = finalUrl;
167
- if (opts.searchParams) {
168
- const params = new URLSearchParams();
169
- for (const [key, value] of Object.entries(opts.searchParams)) {
170
- params.append(key, String(value));
171
- }
172
- urlWithParams = `${finalUrl}?${params.toString()}`;
173
- }
174
- // Build request body
175
- let body;
176
- if (opts.json) {
177
- body = JSON.stringify(opts.json);
178
- headers['Content-Type'] = 'application/json';
179
- }
180
- else if (opts.body) {
181
- // Convert Buffer to string for compatibility with xfetch
182
- // SAFETY: After instanceof check, both branches produce string type
183
- body = (opts.body instanceof Buffer ? opts.body.toString() : opts.body);
184
- }
185
- // Extract timeout
186
- const timeout = typeof opts.timeout === 'number'
187
- ? opts.timeout
188
- : opts.timeout?.request;
189
- // Convert to xfetch options
190
- const xfetchOpts = {
191
- method,
192
- headers,
193
- body,
194
- timeout,
195
- forceXBind: opts.forceXBind,
196
- disableXBind: opts.disableXBind,
197
- };
198
- // Make request via xfetch
199
- const response = await xfetch(urlWithParams, xfetchOpts);
200
- // Parse response body based on responseType
201
- let responseBody;
202
- const responseType = opts.responseType ?? 'text';
203
- switch (responseType) {
204
- case 'json':
205
- responseBody = (await response.json());
206
- break;
207
- case 'text':
208
- responseBody = (await response.text());
209
- break;
210
- case 'buffer':
211
- const arrayBuffer = await response.arrayBuffer();
212
- responseBody = Buffer.from(arrayBuffer);
213
- break;
214
- default:
215
- responseBody = (await response.text());
216
- }
217
- // Convert headers to object
218
- const responseHeaders = {};
219
- response.headers.forEach((value, key) => {
220
- responseHeaders[key] = value;
221
- });
222
- return {
223
- body: responseBody,
224
- statusCode: response.status,
225
- headers: responseHeaders,
226
- url: response.url,
227
- requestUrl: urlWithParams,
228
- xbind: {
229
- used: response.usedXBind,
230
- protocol: response.transport.protocol,
231
- latency: response.transport.latency,
232
- peerDID: response.transport.peerDID,
233
- },
234
- };
235
- }
236
- // Convenience methods
237
- got.get = (url, options) => got(url, { ...options, method: 'GET' });
238
- got.post = (url, options) => got(url, { ...options, method: 'POST' });
239
- got.put = (url, options) => got(url, { ...options, method: 'PUT' });
240
- got.patch = (url, options) => got(url, { ...options, method: 'PATCH' });
241
- got.delete = (url, options) => got(url, { ...options, method: 'DELETE' });
242
- return got;
243
- }
244
- /**
245
- * Wrap existing fetch implementation with xBind auto-upgrade
246
- *
247
- * Use this to upgrade an existing fetch instance (like node-fetch, cross-fetch, etc.)
248
- *
249
- * @param fetchImpl - Fetch implementation to wrap
250
- * @returns Wrapped fetch with xBind support
251
- *
252
- * @example
253
- * ```typescript
254
- * import { wrapFetch } from '@private.me/xbind/http-compat';
255
- * import nodeFetch from 'node-fetch';
256
- *
257
- * const fetch = wrapFetch(nodeFetch);
258
- *
259
- * // Uses xBind if supported, falls back to node-fetch
260
- * const response = await fetch('https://api.example.com/data');
261
- * ```
262
- */
263
- export function wrapFetch(fetchImpl) {
264
- // Return xfetch (which already handles auto-upgrade and fallback)
265
- // The original fetchImpl is not used because xfetch uses global fetch
266
- return xfetch;
267
- }
1
+ import{xfetch}from"./xfetch.js";export function createAxiosCompat(){async function t(t){const e="string"==typeof t?{url:t}:t,a=e.method?.toUpperCase()??"GET",r=e.baseURL?new URL(e.url??"",e.baseURL).toString():e.url??"",o={...e.headers};let n,s=r;if(e.params){const t=new URLSearchParams;for(const[a,r]of Object.entries(e.params))t.append(a,String(r));s=`${r}?${t.toString()}`}e.data&&("string"==typeof e.data?n=e.data:(n=JSON.stringify(e.data),o["Content-Type"]="application/json"));const i={method:a,headers:o,body:n,timeout:e.timeout,forceXBind:e.forceXBind,disableXBind:e.disableXBind},c=await xfetch(s,i);let u;switch(e.responseType??"json"){case"json":default:u=await c.json();break;case"text":u=await c.text();break;case"blob":u=await c.blob();break;case"arraybuffer":u=await c.arrayBuffer()}if(e.validateStatus&&!e.validateStatus(c.status))throw new Error(`Request failed with status ${c.status}`);const d={};return c.headers.forEach((t,e)=>{d[e]=t}),{data:u,status:c.status,statusText:c.statusText,headers:d,config:e,xbind:{used:c.usedXBind,protocol:c.transport.protocol,latency:c.transport.latency,peerDID:c.transport.peerDID}}}return{request:t,get:async function(e,a){return t({...a,url:e,method:"GET"})},post:async function(e,a,r){return t({...r,url:e,method:"POST",data:a})},put:async function(e,a,r){return t({...r,url:e,method:"PUT",data:a})},patch:async function(e,a,r){return t({...r,url:e,method:"PATCH",data:a})},delete:async function(e,a){return t({...a,url:e,method:"DELETE"})}}}export function createGotCompat(){async function t(t,e){const a="string"==typeof t?{...e,url:t}:t,r=a.method?.toUpperCase()??"GET",o=a.url??"",n={...a.headers};let s,i=o;if(a.searchParams){const t=new URLSearchParams;for(const[e,r]of Object.entries(a.searchParams))t.append(e,String(r));i=`${o}?${t.toString()}`}a.json?(s=JSON.stringify(a.json),n["Content-Type"]="application/json"):a.body&&(s=a.body instanceof Buffer?a.body.toString():a.body);const c={method:r,headers:n,body:s,timeout:"number"==typeof a.timeout?a.timeout:a.timeout?.request,forceXBind:a.forceXBind,disableXBind:a.disableXBind},u=await xfetch(i,c);let d;switch(a.responseType??"text"){case"json":d=await u.json();break;case"text":default:d=await u.text();break;case"buffer":{const t=await u.arrayBuffer();d=Buffer.from(t);break}}const f={};return u.headers.forEach((t,e)=>{f[e]=t}),{body:d,statusCode:u.status,headers:f,url:u.url,requestUrl:i,xbind:{used:u.usedXBind,protocol:u.transport.protocol,latency:u.transport.latency,peerDID:u.transport.peerDID}}}return t.get=(e,a)=>t(e,{...a,method:"GET"}),t.post=(e,a)=>t(e,{...a,method:"POST"}),t.put=(e,a)=>t(e,{...a,method:"PUT"}),t.patch=(e,a)=>t(e,{...a,method:"PATCH"}),t.delete=(e,a)=>t(e,{...a,method:"DELETE"}),t}export function wrapFetch(){return xfetch}