@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,50 +1 @@
1
- "use strict";
2
- /**
3
- * Express middleware for protecting trust registry endpoints with bearer auth.
4
- *
5
- * GET/HEAD requests pass through (public reads). POST/PUT/DELETE require
6
- * a valid Bearer token matching the configured admin token.
7
- *
8
- * @example
9
- * ```ts
10
- * import express from 'express';
11
- * import { createRegistryAuthMiddleware } from '@private.me/xbind';
12
- *
13
- * const app = express();
14
- * app.use('/registry', createRegistryAuthMiddleware(process.env.REGISTRY_ADMIN_TOKEN!));
15
- * ```
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.createRegistryAuthMiddleware = createRegistryAuthMiddleware;
19
- /**
20
- * Create an Express-compatible middleware that protects write operations
21
- * on registry endpoints with bearer token authentication.
22
- *
23
- * GET and HEAD requests pass through without authentication.
24
- * POST, PUT, and DELETE require `Authorization: Bearer <token>`.
25
- *
26
- * @param token - The admin token to validate against.
27
- * @returns Express middleware function.
28
- */
29
- function createRegistryAuthMiddleware(token) {
30
- return (req, res, next) => {
31
- const method = req.method.toUpperCase();
32
- if (method === 'GET' || method === 'HEAD') {
33
- next();
34
- return;
35
- }
36
- const authHeader = typeof req.headers['authorization'] === 'string'
37
- ? req.headers['authorization']
38
- : undefined;
39
- if (!authHeader || !authHeader.startsWith('Bearer ')) {
40
- res.status(401).json({ error: 'UNAUTHORIZED' });
41
- return;
42
- }
43
- const provided = authHeader.slice('Bearer '.length);
44
- if (provided !== token) {
45
- res.status(401).json({ error: 'UNAUTHORIZED' });
46
- return;
47
- }
48
- next();
49
- };
50
- }
1
+ "use strict";function createRegistryAuthMiddleware(e){return(t,r,s)=>{const i=t.method.toUpperCase();if("GET"===i||"HEAD"===i)return void s();const o="string"==typeof t.headers.authorization?t.headers.authorization:void 0;if(!o||!o.startsWith("Bearer "))return void r.status(401).json({error:"UNAUTHORIZED"});o.slice(7)===e?s():r.status(401).json({error:"UNAUTHORIZED"})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRegistryAuthMiddleware=createRegistryAuthMiddleware;
@@ -1,544 +1 @@
1
- "use strict";
2
- /**
3
- * @module retry-strategies
4
- * Configurable retry strategies for enhanced reliability.
5
- *
6
- * Provides flexible retry policies with exponential backoff, jitter, circuit breakers,
7
- * and error-specific retry logic. Designed for production-grade fault tolerance.
8
- *
9
- * @example
10
- * ```typescript
11
- * import { RetryStrategy, CircuitBreaker } from '@private.me/xbind/retry-strategies';
12
- *
13
- * // Exponential backoff with circuit breaker
14
- * const strategy = RetryStrategy.exponentialBackoff({
15
- * maxAttempts: 5,
16
- * initialDelayMs: 1000,
17
- * maxDelayMs: 30000,
18
- * multiplier: 2,
19
- * jitter: true
20
- * });
21
- *
22
- * const circuitBreaker = new CircuitBreaker({
23
- * failureThreshold: 5,
24
- * resetTimeoutMs: 60000
25
- * });
26
- * ```
27
- */
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.RetryStrategy = exports.CircuitBreaker = exports.NoRetryStrategy = exports.FixedDelayStrategy = exports.LinearBackoffStrategy = exports.ExponentialBackoffStrategy = void 0;
30
- exports.executeWithRetry = executeWithRetry;
31
- const shared_1 = require("../_deps/shared/index.js");
32
- /* ── Retry Strategy Implementations ── */
33
- /**
34
- * Exponential backoff retry strategy.
35
- *
36
- * Delay formula: min(initialDelay * multiplier^attempt, maxDelay) ± jitter
37
- *
38
- * Best for: Network requests, API calls, database operations.
39
- * Avoids overwhelming failing services with exponentially increasing delays.
40
- */
41
- class ExponentialBackoffStrategy {
42
- name = 'ExponentialBackoff';
43
- maxAttempts;
44
- initialDelayMs;
45
- maxDelayMs;
46
- multiplier;
47
- jitter;
48
- jitterFactor;
49
- retryableErrors;
50
- constructor(config = {}) {
51
- this.maxAttempts = config.maxAttempts ?? 3;
52
- this.initialDelayMs = config.initialDelayMs ?? 1000;
53
- this.maxDelayMs = config.maxDelayMs ?? 30000;
54
- this.multiplier = config.multiplier ?? 2;
55
- this.jitter = config.jitter ?? true;
56
- this.jitterFactor = config.jitterFactor ?? 0.2;
57
- this.retryableErrors = config.retryableErrors
58
- ? new Set(config.retryableErrors)
59
- : new Set(['SEND_FAILED', 'NETWORK_ERROR', 'RECIPIENT_UNREACHABLE', 'TIMEOUT']);
60
- }
61
- shouldRetry(context) {
62
- // Check if we've exceeded max attempts
63
- if (context.attempt >= this.maxAttempts) {
64
- return {
65
- shouldRetry: false,
66
- reason: `Maximum attempts (${this.maxAttempts}) exceeded`,
67
- };
68
- }
69
- // Check if error is retryable
70
- if (!this.retryableErrors.has(context.error)) {
71
- return {
72
- shouldRetry: false,
73
- reason: `Error type '${context.error}' is not retryable`,
74
- };
75
- }
76
- // Calculate exponential backoff delay
77
- const baseDelay = this.initialDelayMs * Math.pow(this.multiplier, context.attempt);
78
- const cappedDelay = Math.min(baseDelay, this.maxDelayMs);
79
- // Apply jitter if enabled
80
- const finalDelay = this.jitter ? this.applyJitter(cappedDelay) : cappedDelay;
81
- return {
82
- shouldRetry: true,
83
- delayMs: Math.round(finalDelay),
84
- reason: `Attempt ${context.attempt + 1}/${this.maxAttempts}`,
85
- };
86
- }
87
- applyJitter(delayMs) {
88
- // Use crypto.getRandomValues for secure random jitter (OWASP-compliant)
89
- const randomArray = new Uint32Array(1);
90
- crypto.getRandomValues(randomArray);
91
- const random = randomArray[0] / 0xffffffff; // Normalize to [0, 1]
92
- // Apply jitter: delay ± (delay * jitterFactor)
93
- const jitterRange = delayMs * this.jitterFactor;
94
- const jitter = (random * 2 - 1) * jitterRange; // Range: [-jitterRange, +jitterRange]
95
- return delayMs + jitter;
96
- }
97
- }
98
- exports.ExponentialBackoffStrategy = ExponentialBackoffStrategy;
99
- /**
100
- * Linear backoff retry strategy.
101
- *
102
- * Delay formula: min(initialDelay + attempt * increment, maxDelay) ± jitter
103
- *
104
- * Best for: Rate-limited APIs, gradual load recovery.
105
- * More predictable than exponential, suitable when service recovery is linear.
106
- */
107
- class LinearBackoffStrategy {
108
- name = 'LinearBackoff';
109
- maxAttempts;
110
- delayIncrementMs;
111
- initialDelayMs;
112
- maxDelayMs;
113
- jitter;
114
- jitterFactor;
115
- retryableErrors;
116
- constructor(config = {}) {
117
- this.maxAttempts = config.maxAttempts ?? 3;
118
- this.delayIncrementMs = config.delayIncrementMs ?? 1000;
119
- this.initialDelayMs = config.initialDelayMs ?? 1000;
120
- this.maxDelayMs = config.maxDelayMs ?? 30000;
121
- this.jitter = config.jitter ?? true;
122
- this.jitterFactor = config.jitterFactor ?? 0.1;
123
- this.retryableErrors = config.retryableErrors
124
- ? new Set(config.retryableErrors)
125
- : new Set(['SEND_FAILED', 'NETWORK_ERROR', 'RECIPIENT_UNREACHABLE', 'TIMEOUT']);
126
- }
127
- shouldRetry(context) {
128
- if (context.attempt >= this.maxAttempts) {
129
- return {
130
- shouldRetry: false,
131
- reason: `Maximum attempts (${this.maxAttempts}) exceeded`,
132
- };
133
- }
134
- if (!this.retryableErrors.has(context.error)) {
135
- return {
136
- shouldRetry: false,
137
- reason: `Error type '${context.error}' is not retryable`,
138
- };
139
- }
140
- // Calculate linear backoff delay
141
- const baseDelay = this.initialDelayMs + context.attempt * this.delayIncrementMs;
142
- const cappedDelay = Math.min(baseDelay, this.maxDelayMs);
143
- // Apply jitter if enabled
144
- const finalDelay = this.jitter ? this.applyJitter(cappedDelay) : cappedDelay;
145
- return {
146
- shouldRetry: true,
147
- delayMs: Math.round(finalDelay),
148
- reason: `Attempt ${context.attempt + 1}/${this.maxAttempts}`,
149
- };
150
- }
151
- applyJitter(delayMs) {
152
- const randomArray = new Uint32Array(1);
153
- crypto.getRandomValues(randomArray);
154
- const random = randomArray[0] / 0xffffffff;
155
- const jitterRange = delayMs * this.jitterFactor;
156
- const jitter = (random * 2 - 1) * jitterRange;
157
- return delayMs + jitter;
158
- }
159
- }
160
- exports.LinearBackoffStrategy = LinearBackoffStrategy;
161
- /**
162
- * Fixed delay retry strategy.
163
- *
164
- * Delay formula: delayMs ± jitter (constant for all attempts)
165
- *
166
- * Best for: Simple retry scenarios, testing.
167
- * Predictable timing, no backoff complexity.
168
- */
169
- class FixedDelayStrategy {
170
- name = 'FixedDelay';
171
- maxAttempts;
172
- delayMs;
173
- jitter;
174
- jitterFactor;
175
- retryableErrors;
176
- constructor(config = {}) {
177
- this.maxAttempts = config.maxAttempts ?? 3;
178
- this.delayMs = config.delayMs ?? 1000;
179
- this.jitter = config.jitter ?? false;
180
- this.jitterFactor = config.jitterFactor ?? 0.1;
181
- this.retryableErrors = config.retryableErrors
182
- ? new Set(config.retryableErrors)
183
- : new Set(['SEND_FAILED', 'NETWORK_ERROR', 'RECIPIENT_UNREACHABLE', 'TIMEOUT']);
184
- }
185
- shouldRetry(context) {
186
- if (context.attempt >= this.maxAttempts) {
187
- return {
188
- shouldRetry: false,
189
- reason: `Maximum attempts (${this.maxAttempts}) exceeded`,
190
- };
191
- }
192
- if (!this.retryableErrors.has(context.error)) {
193
- return {
194
- shouldRetry: false,
195
- reason: `Error type '${context.error}' is not retryable`,
196
- };
197
- }
198
- const finalDelay = this.jitter ? this.applyJitter(this.delayMs) : this.delayMs;
199
- return {
200
- shouldRetry: true,
201
- delayMs: Math.round(finalDelay),
202
- reason: `Attempt ${context.attempt + 1}/${this.maxAttempts}`,
203
- };
204
- }
205
- applyJitter(delayMs) {
206
- const randomArray = new Uint32Array(1);
207
- crypto.getRandomValues(randomArray);
208
- const random = randomArray[0] / 0xffffffff;
209
- const jitterRange = delayMs * this.jitterFactor;
210
- const jitter = (random * 2 - 1) * jitterRange;
211
- return delayMs + jitter;
212
- }
213
- }
214
- exports.FixedDelayStrategy = FixedDelayStrategy;
215
- /**
216
- * No retry strategy (fail immediately).
217
- *
218
- * Best for: Operations that must succeed on first try, testing.
219
- */
220
- class NoRetryStrategy {
221
- name = 'NoRetry';
222
- shouldRetry(_context) {
223
- return {
224
- shouldRetry: false,
225
- reason: 'No retry policy - fail immediately',
226
- };
227
- }
228
- }
229
- exports.NoRetryStrategy = NoRetryStrategy;
230
- /* ── Circuit Breaker ── */
231
- /**
232
- * Circuit breaker for preventing cascading failures.
233
- *
234
- * States:
235
- * - CLOSED: Normal operation, requests pass through
236
- * - OPEN: Circuit tripped, requests fail immediately
237
- * - HALF_OPEN: Testing recovery, limited requests allowed
238
- *
239
- * Best practices:
240
- * - Use with retry strategies for comprehensive fault tolerance
241
- * - Monitor circuit state changes for alerting
242
- * - Tune thresholds based on service characteristics
243
- *
244
- * @example
245
- * ```typescript
246
- * const breaker = new CircuitBreaker({
247
- * failureThreshold: 5,
248
- * resetTimeoutMs: 60000,
249
- * successThreshold: 2
250
- * });
251
- *
252
- * // Check before operation
253
- * if (breaker.allowRequest()) {
254
- * const result = await operation();
255
- * if (result.ok) {
256
- * breaker.recordSuccess();
257
- * } else {
258
- * breaker.recordFailure();
259
- * }
260
- * }
261
- * ```
262
- */
263
- class CircuitBreaker {
264
- state = 'CLOSED';
265
- consecutiveFailures = 0;
266
- consecutiveSuccesses = 0;
267
- openedAt;
268
- totalRequests = 0;
269
- totalFailures = 0;
270
- totalSuccesses = 0;
271
- failureTimestamps = [];
272
- failureThreshold;
273
- resetTimeoutMs;
274
- successThreshold;
275
- windowMs;
276
- constructor(config = {}) {
277
- this.failureThreshold = config.failureThreshold ?? 5;
278
- this.resetTimeoutMs = config.resetTimeoutMs ?? 60000;
279
- this.successThreshold = config.successThreshold ?? 2;
280
- this.windowMs = config.windowMs ?? 60000;
281
- }
282
- /**
283
- * Check if request should be allowed through circuit.
284
- *
285
- * @returns True if request should proceed, false if circuit is open
286
- */
287
- allowRequest() {
288
- const now = Date.now();
289
- // Clean up old failure timestamps outside the window
290
- this.failureTimestamps = this.failureTimestamps.filter(timestamp => now - timestamp < this.windowMs);
291
- // CLOSED: Allow all requests
292
- if (this.state === 'CLOSED') {
293
- return true;
294
- }
295
- // OPEN: Check if reset timeout has elapsed
296
- if (this.state === 'OPEN') {
297
- if (this.openedAt && now - this.openedAt >= this.resetTimeoutMs) {
298
- // Transition to HALF_OPEN
299
- this.state = 'HALF_OPEN';
300
- this.consecutiveSuccesses = 0;
301
- return true;
302
- }
303
- return false; // Circuit still open
304
- }
305
- // HALF_OPEN: Allow limited requests to test recovery
306
- return true;
307
- }
308
- /**
309
- * Record a successful operation.
310
- */
311
- recordSuccess() {
312
- this.totalRequests++;
313
- this.totalSuccesses++;
314
- this.consecutiveFailures = 0;
315
- if (this.state === 'HALF_OPEN') {
316
- this.consecutiveSuccesses++;
317
- // Enough successes to close circuit
318
- if (this.consecutiveSuccesses >= this.successThreshold) {
319
- this.state = 'CLOSED';
320
- this.consecutiveSuccesses = 0;
321
- this.openedAt = undefined;
322
- }
323
- }
324
- }
325
- /**
326
- * Record a failed operation.
327
- */
328
- recordFailure() {
329
- this.totalRequests++;
330
- this.totalFailures++;
331
- this.consecutiveFailures++;
332
- this.consecutiveSuccesses = 0;
333
- const now = Date.now();
334
- this.failureTimestamps.push(now);
335
- // Trip circuit if threshold exceeded
336
- if (this.state === 'CLOSED' || this.state === 'HALF_OPEN') {
337
- // Count failures within the time window
338
- const recentFailures = this.failureTimestamps.filter(timestamp => now - timestamp < this.windowMs).length;
339
- if (recentFailures >= this.failureThreshold) {
340
- this.state = 'OPEN';
341
- this.openedAt = now;
342
- }
343
- }
344
- }
345
- /**
346
- * Get current circuit breaker statistics.
347
- */
348
- getStats() {
349
- return {
350
- state: this.state,
351
- consecutiveFailures: this.consecutiveFailures,
352
- consecutiveSuccesses: this.consecutiveSuccesses,
353
- openedAt: this.openedAt,
354
- totalRequests: this.totalRequests,
355
- totalFailures: this.totalFailures,
356
- totalSuccesses: this.totalSuccesses,
357
- };
358
- }
359
- /**
360
- * Reset circuit breaker to initial state.
361
- */
362
- reset() {
363
- this.state = 'CLOSED';
364
- this.consecutiveFailures = 0;
365
- this.consecutiveSuccesses = 0;
366
- this.openedAt = undefined;
367
- this.totalRequests = 0;
368
- this.totalFailures = 0;
369
- this.totalSuccesses = 0;
370
- this.failureTimestamps = [];
371
- }
372
- /**
373
- * Force circuit to open (for testing or manual intervention).
374
- */
375
- forceOpen() {
376
- this.state = 'OPEN';
377
- this.openedAt = Date.now();
378
- }
379
- /**
380
- * Force circuit to close (for testing or manual recovery).
381
- */
382
- forceClose() {
383
- this.state = 'CLOSED';
384
- this.consecutiveFailures = 0;
385
- this.consecutiveSuccesses = 0;
386
- this.openedAt = undefined;
387
- }
388
- }
389
- exports.CircuitBreaker = CircuitBreaker;
390
- /* ── Factory Functions ── */
391
- /**
392
- * Factory for creating retry strategies with common configurations.
393
- */
394
- class RetryStrategy {
395
- /**
396
- * Create exponential backoff strategy.
397
- *
398
- * @param config - Configuration options
399
- * @returns Exponential backoff strategy
400
- */
401
- static exponentialBackoff(config) {
402
- return new ExponentialBackoffStrategy(config);
403
- }
404
- /**
405
- * Create linear backoff strategy.
406
- *
407
- * @param config - Configuration options
408
- * @returns Linear backoff strategy
409
- */
410
- static linearBackoff(config) {
411
- return new LinearBackoffStrategy(config);
412
- }
413
- /**
414
- * Create fixed delay strategy.
415
- *
416
- * @param config - Configuration options
417
- * @returns Fixed delay strategy
418
- */
419
- static fixedDelay(config) {
420
- return new FixedDelayStrategy(config);
421
- }
422
- /**
423
- * Create no retry strategy (fail immediately).
424
- *
425
- * @returns No retry strategy
426
- */
427
- static noRetry() {
428
- return new NoRetryStrategy();
429
- }
430
- /**
431
- * Create aggressive retry strategy for critical operations.
432
- *
433
- * Config: 5 attempts, 500ms initial, max 10s, exponential backoff.
434
- *
435
- * @returns Aggressive retry strategy
436
- */
437
- static aggressive() {
438
- return new ExponentialBackoffStrategy({
439
- maxAttempts: 5,
440
- initialDelayMs: 500,
441
- maxDelayMs: 10000,
442
- multiplier: 2,
443
- jitter: true,
444
- });
445
- }
446
- /**
447
- * Create conservative retry strategy for non-critical operations.
448
- *
449
- * Config: 2 attempts, 2s initial, max 5s, linear backoff.
450
- *
451
- * @returns Conservative retry strategy
452
- */
453
- static conservative() {
454
- return new LinearBackoffStrategy({
455
- maxAttempts: 2,
456
- initialDelayMs: 2000,
457
- delayIncrementMs: 1000,
458
- maxDelayMs: 5000,
459
- jitter: true,
460
- });
461
- }
462
- /**
463
- * Create default retry strategy (balanced).
464
- *
465
- * Config: 3 attempts, 1s initial, max 30s, exponential backoff.
466
- *
467
- * @returns Default retry strategy
468
- */
469
- static default() {
470
- return new ExponentialBackoffStrategy({
471
- maxAttempts: 3,
472
- initialDelayMs: 1000,
473
- maxDelayMs: 30000,
474
- multiplier: 2,
475
- jitter: true,
476
- });
477
- }
478
- }
479
- exports.RetryStrategy = RetryStrategy;
480
- /* ── Retry Executor ── */
481
- /**
482
- * Execute an operation with retry strategy and optional circuit breaker.
483
- *
484
- * @param operation - Async operation to execute
485
- * @param strategy - Retry strategy to use
486
- * @param circuitBreaker - Optional circuit breaker
487
- * @returns Result of the operation
488
- *
489
- * @example
490
- * ```typescript
491
- * const result = await executeWithRetry(
492
- * async () => transport.send(envelope, did),
493
- * RetryStrategy.exponentialBackoff(),
494
- * circuitBreaker
495
- * );
496
- * ```
497
- */
498
- async function executeWithRetry(operation, strategy, circuitBreaker) {
499
- const startTime = Date.now();
500
- let attempt = 0;
501
- let lastError = 'NETWORK_ERROR'; // Default error
502
- while (true) {
503
- // Check circuit breaker
504
- if (circuitBreaker && !circuitBreaker.allowRequest()) {
505
- return (0, shared_1.err)('SEND_FAILED');
506
- }
507
- // Execute operation
508
- const result = await operation();
509
- if (result.ok) {
510
- // Success - record and return
511
- circuitBreaker?.recordSuccess();
512
- return result;
513
- }
514
- // Failure - record error
515
- lastError = result.error;
516
- circuitBreaker?.recordFailure();
517
- // Check retry decision
518
- const elapsedMs = Date.now() - startTime;
519
- const context = {
520
- attempt,
521
- error: lastError,
522
- startTime,
523
- elapsedMs,
524
- };
525
- const decision = strategy.shouldRetry(context);
526
- if (!decision.shouldRetry) {
527
- // No more retries - return last error
528
- return (0, shared_1.err)(lastError);
529
- }
530
- // Wait before retry
531
- if (decision.delayMs && decision.delayMs > 0) {
532
- await sleep(decision.delayMs);
533
- }
534
- attempt++;
535
- }
536
- }
537
- /**
538
- * Sleep for specified milliseconds.
539
- *
540
- * @param ms - Duration in milliseconds
541
- */
542
- function sleep(ms) {
543
- return new Promise(resolve => setTimeout(resolve, ms));
544
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RetryStrategy=exports.CircuitBreaker=exports.NoRetryStrategy=exports.FixedDelayStrategy=exports.LinearBackoffStrategy=exports.ExponentialBackoffStrategy=void 0,exports.executeWithRetry=executeWithRetry;const shared_1=require("../_deps/shared/index.js");class ExponentialBackoffStrategy{name="ExponentialBackoff";maxAttempts;initialDelayMs;maxDelayMs;multiplier;jitter;jitterFactor;retryableErrors;constructor(t={}){this.maxAttempts=t.maxAttempts??3,this.initialDelayMs=t.initialDelayMs??1e3,this.maxDelayMs=t.maxDelayMs??3e4,this.multiplier=t.multiplier??2,this.jitter=t.jitter??!0,this.jitterFactor=t.jitterFactor??.2,this.retryableErrors=t.retryableErrors?new Set(t.retryableErrors):new Set(["SEND_FAILED","NETWORK_ERROR","RECIPIENT_UNREACHABLE","TIMEOUT"])}shouldRetry(t){if(t.attempt>=this.maxAttempts)return{shouldRetry:!1,reason:`Maximum attempts (${this.maxAttempts}) exceeded`};if(!this.retryableErrors.has(t.error))return{shouldRetry:!1,reason:`Error type '${t.error}' is not retryable`};const e=this.initialDelayMs*Math.pow(this.multiplier,t.attempt),s=Math.min(e,this.maxDelayMs),r=this.jitter?this.applyJitter(s):s;return{shouldRetry:!0,delayMs:Math.round(r),reason:`Attempt ${t.attempt+1}/${this.maxAttempts}`}}applyJitter(t){const e=new Uint32Array(1);crypto.getRandomValues(e);return t+(2*(e[0]/4294967295)-1)*(t*this.jitterFactor)}}exports.ExponentialBackoffStrategy=ExponentialBackoffStrategy;class LinearBackoffStrategy{name="LinearBackoff";maxAttempts;delayIncrementMs;initialDelayMs;maxDelayMs;jitter;jitterFactor;retryableErrors;constructor(t={}){this.maxAttempts=t.maxAttempts??3,this.delayIncrementMs=t.delayIncrementMs??1e3,this.initialDelayMs=t.initialDelayMs??1e3,this.maxDelayMs=t.maxDelayMs??3e4,this.jitter=t.jitter??!0,this.jitterFactor=t.jitterFactor??.1,this.retryableErrors=t.retryableErrors?new Set(t.retryableErrors):new Set(["SEND_FAILED","NETWORK_ERROR","RECIPIENT_UNREACHABLE","TIMEOUT"])}shouldRetry(t){if(t.attempt>=this.maxAttempts)return{shouldRetry:!1,reason:`Maximum attempts (${this.maxAttempts}) exceeded`};if(!this.retryableErrors.has(t.error))return{shouldRetry:!1,reason:`Error type '${t.error}' is not retryable`};const e=this.initialDelayMs+t.attempt*this.delayIncrementMs,s=Math.min(e,this.maxDelayMs),r=this.jitter?this.applyJitter(s):s;return{shouldRetry:!0,delayMs:Math.round(r),reason:`Attempt ${t.attempt+1}/${this.maxAttempts}`}}applyJitter(t){const e=new Uint32Array(1);crypto.getRandomValues(e);return t+(2*(e[0]/4294967295)-1)*(t*this.jitterFactor)}}exports.LinearBackoffStrategy=LinearBackoffStrategy;class FixedDelayStrategy{name="FixedDelay";maxAttempts;delayMs;jitter;jitterFactor;retryableErrors;constructor(t={}){this.maxAttempts=t.maxAttempts??3,this.delayMs=t.delayMs??1e3,this.jitter=t.jitter??!1,this.jitterFactor=t.jitterFactor??.1,this.retryableErrors=t.retryableErrors?new Set(t.retryableErrors):new Set(["SEND_FAILED","NETWORK_ERROR","RECIPIENT_UNREACHABLE","TIMEOUT"])}shouldRetry(t){if(t.attempt>=this.maxAttempts)return{shouldRetry:!1,reason:`Maximum attempts (${this.maxAttempts}) exceeded`};if(!this.retryableErrors.has(t.error))return{shouldRetry:!1,reason:`Error type '${t.error}' is not retryable`};const e=this.jitter?this.applyJitter(this.delayMs):this.delayMs;return{shouldRetry:!0,delayMs:Math.round(e),reason:`Attempt ${t.attempt+1}/${this.maxAttempts}`}}applyJitter(t){const e=new Uint32Array(1);crypto.getRandomValues(e);return t+(2*(e[0]/4294967295)-1)*(t*this.jitterFactor)}}exports.FixedDelayStrategy=FixedDelayStrategy;class NoRetryStrategy{name="NoRetry";shouldRetry(t){return{shouldRetry:!1,reason:"No retry policy - fail immediately"}}}exports.NoRetryStrategy=NoRetryStrategy;class CircuitBreaker{state="CLOSED";consecutiveFailures=0;consecutiveSuccesses=0;openedAt;totalRequests=0;totalFailures=0;totalSuccesses=0;failureTimestamps=[];failureThreshold;resetTimeoutMs;successThreshold;windowMs;constructor(t={}){this.failureThreshold=t.failureThreshold??5,this.resetTimeoutMs=t.resetTimeoutMs??6e4,this.successThreshold=t.successThreshold??2,this.windowMs=t.windowMs??6e4}allowRequest(){const t=Date.now();return this.failureTimestamps=this.failureTimestamps.filter(e=>t-e<this.windowMs),"CLOSED"===this.state||("OPEN"!==this.state||!!(this.openedAt&&t-this.openedAt>=this.resetTimeoutMs)&&(this.state="HALF_OPEN",this.consecutiveSuccesses=0,!0))}recordSuccess(){this.totalRequests++,this.totalSuccesses++,this.consecutiveFailures=0,"HALF_OPEN"===this.state&&(this.consecutiveSuccesses++,this.consecutiveSuccesses>=this.successThreshold&&(this.state="CLOSED",this.consecutiveSuccesses=0,this.openedAt=void 0))}recordFailure(){this.totalRequests++,this.totalFailures++,this.consecutiveFailures++,this.consecutiveSuccesses=0;const t=Date.now();if(this.failureTimestamps.push(t),"CLOSED"===this.state||"HALF_OPEN"===this.state){this.failureTimestamps.filter(e=>t-e<this.windowMs).length>=this.failureThreshold&&(this.state="OPEN",this.openedAt=t)}}getStats(){return{state:this.state,consecutiveFailures:this.consecutiveFailures,consecutiveSuccesses:this.consecutiveSuccesses,openedAt:this.openedAt,totalRequests:this.totalRequests,totalFailures:this.totalFailures,totalSuccesses:this.totalSuccesses}}reset(){this.state="CLOSED",this.consecutiveFailures=0,this.consecutiveSuccesses=0,this.openedAt=void 0,this.totalRequests=0,this.totalFailures=0,this.totalSuccesses=0,this.failureTimestamps=[]}forceOpen(){this.state="OPEN",this.openedAt=Date.now()}forceClose(){this.state="CLOSED",this.consecutiveFailures=0,this.consecutiveSuccesses=0,this.openedAt=void 0}}exports.CircuitBreaker=CircuitBreaker;class RetryStrategy{static exponentialBackoff(t){return new ExponentialBackoffStrategy(t)}static linearBackoff(t){return new LinearBackoffStrategy(t)}static fixedDelay(t){return new FixedDelayStrategy(t)}static noRetry(){return new NoRetryStrategy}static aggressive(){return new ExponentialBackoffStrategy({maxAttempts:5,initialDelayMs:500,maxDelayMs:1e4,multiplier:2,jitter:!0})}static conservative(){return new LinearBackoffStrategy({maxAttempts:2,initialDelayMs:2e3,delayIncrementMs:1e3,maxDelayMs:5e3,jitter:!0})}static default(){return new ExponentialBackoffStrategy({maxAttempts:3,initialDelayMs:1e3,maxDelayMs:3e4,multiplier:2,jitter:!0})}}async function executeWithRetry(t,e,s){const r=Date.now();let a=0,i="NETWORK_ERROR";for(;;){if(s&&!s.allowRequest())return(0,shared_1.err)("SEND_FAILED");const o=await t();if(o.ok)return s?.recordSuccess(),o;i=o.error,s?.recordFailure();const l={attempt:a,error:i,startTime:r,elapsedMs:Date.now()-r},n=e.shouldRetry(l);if(!n.shouldRetry)return(0,shared_1.err)(i);n.delayMs&&n.delayMs>0&&await sleep(n.delayMs),a++}}function sleep(t){return new Promise(e=>setTimeout(e,t))}exports.RetryStrategy=RetryStrategy;