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