@defai.digital/resilience-domain 13.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.
package/LICENSE ADDED
@@ -0,0 +1,214 @@
1
+ AutomatosX Open Source Edition - Apache License 2.0
2
+
3
+ This license applies ONLY to the AutomatosX Open Source Edition code
4
+ published on GitHub at https://github.com/defai-digital/automatosx
5
+
6
+ This license does NOT apply to:
7
+ - AutomatosX Pro Edition (proprietary software - separate EULA)
8
+ - AutomatosX Enterprise Edition (proprietary software - separate agreement)
9
+
10
+ For commercial editions, see COMMERCIAL-LICENSE.md
11
+
12
+ ===============================================================================
13
+
14
+ Apache License
15
+ Version 2.0, January 2004
16
+ http://www.apache.org/licenses/
17
+
18
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19
+
20
+ 1. Definitions.
21
+
22
+ "License" shall mean the terms and conditions for use, reproduction,
23
+ and distribution as defined by Sections 1 through 9 of this document.
24
+
25
+ "Licensor" shall mean the copyright owner or entity authorized by
26
+ the copyright owner that is granting the License.
27
+
28
+ "Legal Entity" shall mean the union of the acting entity and all
29
+ other entities that control, are controlled by, or are under common
30
+ control with that entity. For the purposes of this definition,
31
+ "control" means (i) the power, direct or indirect, to cause the
32
+ direction or management of such entity, whether by contract or
33
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34
+ outstanding shares, or (iii) beneficial ownership of such entity.
35
+
36
+ "You" (or "Your") shall mean an individual or Legal Entity
37
+ exercising permissions granted by this License.
38
+
39
+ "Source" form shall mean the preferred form for making modifications,
40
+ including but not limited to software source code, documentation
41
+ source, and configuration files.
42
+
43
+ "Object" form shall mean any form resulting from mechanical
44
+ transformation or translation of a Source form, including but
45
+ not limited to compiled object code, generated documentation,
46
+ and conversions to other media types.
47
+
48
+ "Work" shall mean the work of authorship, whether in Source or
49
+ Object form, made available under the License, as indicated by a
50
+ copyright notice that is included in or attached to the work
51
+ (an example is provided in the Appendix below).
52
+
53
+ "Derivative Works" shall mean any work, whether in Source or Object
54
+ form, that is based on (or derived from) the Work and for which the
55
+ editorial revisions, annotations, elaborations, or other modifications
56
+ represent, as a whole, an original work of authorship. For the purposes
57
+ of this License, Derivative Works shall not include works that remain
58
+ separable from, or merely link (or bind by name) to the interfaces of,
59
+ the Work and Derivative Works thereof.
60
+
61
+ "Contribution" shall mean any work of authorship, including
62
+ the original version of the Work and any modifications or additions
63
+ to that Work or Derivative Works thereof, that is intentionally
64
+ submitted to Licensor for inclusion in the Work by the copyright owner
65
+ or by an individual or Legal Entity authorized to submit on behalf of
66
+ the copyright owner. For the purposes of this definition, "submitted"
67
+ means any form of electronic, verbal, or written communication sent
68
+ to the Licensor or its representatives, including but not limited to
69
+ communication on electronic mailing lists, source code control systems,
70
+ and issue tracking systems that are managed by, or on behalf of, the
71
+ Licensor for the purpose of discussing and improving the Work, but
72
+ excluding communication that is conspicuously marked or otherwise
73
+ designated in writing by the copyright owner as "Not a Contribution."
74
+
75
+ "Contributor" shall mean Licensor and any individual or Legal Entity
76
+ on behalf of whom a Contribution has been received by Licensor and
77
+ subsequently incorporated within the Work.
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+ 3. Grant of Patent License. Subject to the terms and conditions of
87
+ this License, each Contributor hereby grants to You a perpetual,
88
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89
+ (except as stated in this section) patent license to make, have made,
90
+ use, offer to sell, sell, import, and otherwise transfer the Work,
91
+ where such license applies only to those patent claims licensable
92
+ by such Contributor that are necessarily infringed by their
93
+ Contribution(s) alone or by combination of their Contribution(s)
94
+ with the Work to which such Contribution(s) was submitted. If You
95
+ institute patent litigation against any entity (including a
96
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97
+ or a Contribution incorporated within the Work constitutes direct
98
+ or contributory patent infringement, then any patent licenses
99
+ granted to You under this License for that Work shall terminate
100
+ as of the date such litigation is filed.
101
+
102
+ 4. Redistribution. You may reproduce and distribute copies of the
103
+ Work or Derivative Works thereof in any medium, with or without
104
+ modifications, and in Source or Object form, provided that You
105
+ meet the following conditions:
106
+
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+
110
+ (b) You must cause any modified files to carry prominent notices
111
+ stating that You changed the files; and
112
+
113
+ (c) You must retain, in the Source form of any Derivative Works
114
+ that You distribute, all copyright, patent, trademark, and
115
+ attribution notices from the Source form of the Work,
116
+ excluding those notices that do not pertain to any part of
117
+ the Derivative Works; and
118
+
119
+ (d) If the Work includes a "NOTICE" text file as part of its
120
+ distribution, then any Derivative Works that You distribute must
121
+ include a readable copy of the attribution notices contained
122
+ within such NOTICE file, excluding those notices that do not
123
+ pertain to any part of the Derivative Works, in at least one
124
+ of the following places: within a NOTICE text file distributed
125
+ as part of the Derivative Works; within the Source form or
126
+ documentation, if provided along with the Derivative Works; or,
127
+ within a display generated by the Derivative Works, if and
128
+ wherever such third-party notices normally appear. The contents
129
+ of the NOTICE file are for informational purposes only and
130
+ do not modify the License. You may add Your own attribution
131
+ notices within Derivative Works that You distribute, alongside
132
+ or as an addendum to the NOTICE text from the Work, provided
133
+ that such additional attribution notices cannot be construed
134
+ as modifying the License.
135
+
136
+ You may add Your own copyright statement to Your modifications and
137
+ may provide additional or different license terms and conditions
138
+ for use, reproduction, or distribution of Your modifications, or
139
+ for any such Derivative Works as a whole, provided Your use,
140
+ reproduction, and distribution of the Work otherwise complies with
141
+ the conditions stated in this License.
142
+
143
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144
+ any Contribution intentionally submitted for inclusion in the Work
145
+ by You to the Licensor shall be under the terms and conditions of
146
+ this License, without any additional terms or conditions.
147
+ Notwithstanding the above, nothing herein shall supersede or modify
148
+ the terms of any separate license agreement you may have executed
149
+ with Licensor regarding such Contributions.
150
+
151
+ 6. Trademarks. This License does not grant permission to use the trade
152
+ names, trademarks, service marks, or product names of the Licensor,
153
+ except as required for reasonable and customary use in describing the
154
+ origin of the Work and reproducing the content of the NOTICE file.
155
+
156
+ 7. Disclaimer of Warranty. Unless required by applicable law or
157
+ agreed to in writing, Licensor provides the Work (and each
158
+ Contributor provides its Contributions) on an "AS IS" BASIS,
159
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160
+ implied, including, without limitation, any warranties or conditions
161
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162
+ PARTICULAR PURPOSE. You are solely responsible for determining the
163
+ appropriateness of using or redistributing the Work and assume any
164
+ risks associated with Your exercise of permissions under this License.
165
+
166
+ 8. Limitation of Liability. In no event and under no legal theory,
167
+ whether in tort (including negligence), contract, or otherwise,
168
+ unless required by applicable law (such as deliberate and grossly
169
+ negligent acts) or agreed to in writing, shall any Contributor be
170
+ liable to You for damages, including any direct, indirect, special,
171
+ incidental, or consequential damages of any character arising as a
172
+ result of this License or out of the use or inability to use the
173
+ Work (including but not limited to damages for loss of goodwill,
174
+ work stoppage, computer failure or malfunction, or any and all
175
+ other commercial damages or losses), even if such Contributor
176
+ has been advised of the possibility of such damages.
177
+
178
+ 9. Accepting Warranty or Additional Liability. While redistributing
179
+ the Work or Derivative Works thereof, You may choose to offer,
180
+ and charge a fee for, acceptance of support, warranty, indemnity,
181
+ or other liability obligations and/or rights consistent with this
182
+ License. However, in accepting such obligations, You may act only
183
+ on Your own behalf and on Your sole responsibility, not on behalf
184
+ of any other Contributor, and only if You agree to indemnify,
185
+ defend, and hold each Contributor harmless for any liability
186
+ incurred by, or claims asserted against, such Contributor by reason
187
+ of your accepting any such warranty or additional liability.
188
+
189
+ END OF TERMS AND CONDITIONS
190
+
191
+ APPENDIX: How to apply the Apache License to your work.
192
+
193
+ To apply the Apache License to your work, attach the following
194
+ boilerplate notice, with the fields enclosed by brackets "[]"
195
+ replaced with your own identifying information. (Don't include
196
+ the brackets!) The text should be enclosed in the appropriate
197
+ comment syntax for the file format. We also recommend that a
198
+ file or class name and description of purpose be included on the
199
+ same "printed page" as the copyright notice for easier
200
+ identification within third-party archives.
201
+
202
+ Copyright 2024-2025 DEFAI Private Limited
203
+
204
+ Licensed under the Apache License, Version 2.0 (the "License");
205
+ you may not use this file except in compliance with the License.
206
+ You may obtain a copy of the License at
207
+
208
+ http://www.apache.org/licenses/LICENSE-2.0
209
+
210
+ Unless required by applicable law or agreed to in writing, software
211
+ distributed under the License is distributed on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ See the License for the specific language governing permissions and
214
+ limitations under the License.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Internal re-export of resilience contracts
3
+ *
4
+ * This file provides a stable import path for resilience contracts
5
+ * that works in both build and test environments.
6
+ *
7
+ * It imports from the main @defai.digital/contracts and re-exports with
8
+ * the canonical names for internal use.
9
+ */
10
+ export { ResilienceCircuitBreakerStateSchema as CircuitBreakerStateSchema, ResilienceCircuitBreakerConfigSchema as CircuitBreakerConfigSchema, ResilienceCircuitBreakerStatsSchema as CircuitBreakerStatsSchema, ResilienceCircuitBreakerEventSchema as CircuitBreakerEventSchema, ResilienceCircuitBreakerErrorCodes as CircuitBreakerErrorCodes, createDefaultResilienceCircuitBreakerConfig as createDefaultCircuitBreakerConfig, createResilienceCircuitBreakerStats as createCircuitBreakerStats, type ResilienceCircuitBreakerState as CircuitBreakerState, type ResilienceCircuitBreakerConfig as CircuitBreakerConfig, type ResilienceCircuitBreakerStats as CircuitBreakerStats, type ResilienceCircuitBreakerEvent as CircuitBreakerEvent, type ResilienceCircuitBreakerErrorCode as CircuitBreakerErrorCode, RateLimiterConfigSchema, RateLimiterStatsSchema, RateLimiterAcquireResultSchema, RateLimiterErrorCodes, validateRateLimiterConfig, safeValidateRateLimiterConfig, createDefaultRateLimiterConfig, createRateLimiterStats, DEFAULT_TOKEN_WINDOW_MS, DEFAULT_CHECK_INTERVAL_MS, TIME_MULTIPLIERS, DEFAULT_TIME_RANGE_MS, type RateLimiterConfig, type RateLimiterStats, type RateLimiterAcquireResult, type RateLimiterErrorCode, LoopGuardConfigSchema, LoopGuardContextSchema, LoopGuardResultSchema, LoopGuardErrorCodes, validateLoopGuardConfig, safeValidateLoopGuardConfig, createDefaultLoopGuardConfig, createLoopGuardContext, type LoopGuardConfig, type LoopGuardContext, type LoopGuardResult, type LoopGuardErrorCode, ResourceLimitsConfigSchema, ResilienceResourceUsageSchema as ResourceUsageSchema, ResourceCheckResultSchema, ResourceRequestInfoSchema, ResourceLimitsErrorCodes, validateResourceLimitsConfig, safeValidateResourceLimitsConfig, createDefaultResourceLimitsConfig, createResilienceResourceUsage as createResourceUsage, estimateCost, type ResourceLimitsConfig, type ResilienceResourceUsage as ResourceUsage, type ResourceCheckResult, type ResourceRequestInfo, type ResourceLimitsErrorCode, MetricsTimeRangeSchema, RequestMetricSchema, ErrorMetricSchema, LatencyStatsSchema, MetricsSnapshotSchema, validateRequestMetric, validateErrorMetric, validateMetricsSnapshot, createEmptyMetricsSnapshot, createRequestMetric, createErrorMetric, type MetricsTimeRange, type RequestMetric, type ErrorMetric, type LatencyStats, type MetricsSnapshot, } from '@defai.digital/contracts';
11
+ //# sourceMappingURL=_contracts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_contracts.d.ts","sourceRoot":"","sources":["../src/_contracts.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EACL,mCAAmC,IAAI,yBAAyB,EAChE,oCAAoC,IAAI,0BAA0B,EAClE,mCAAmC,IAAI,yBAAyB,EAChE,mCAAmC,IAAI,yBAAyB,EAChE,kCAAkC,IAAI,wBAAwB,EAC9D,2CAA2C,IAAI,iCAAiC,EAChF,mCAAmC,IAAI,yBAAyB,EAChE,KAAK,6BAA6B,IAAI,mBAAmB,EACzD,KAAK,8BAA8B,IAAI,oBAAoB,EAC3D,KAAK,6BAA6B,IAAI,mBAAmB,EACzD,KAAK,6BAA6B,IAAI,mBAAmB,EACzD,KAAK,iCAAiC,IAAI,uBAAuB,EAEjE,uBAAuB,EACvB,sBAAsB,EACtB,8BAA8B,EAC9B,qBAAqB,EACrB,yBAAyB,EACzB,6BAA6B,EAC7B,8BAA8B,EAC9B,sBAAsB,EACtB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EAEzB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,2BAA2B,EAC3B,4BAA4B,EAC5B,sBAAsB,EACtB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EAEvB,0BAA0B,EAC1B,6BAA6B,IAAI,mBAAmB,EACpD,yBAAyB,EACzB,yBAAyB,EACzB,wBAAwB,EACxB,4BAA4B,EAC5B,gCAAgC,EAChC,iCAAiC,EACjC,6BAA6B,IAAI,mBAAmB,EACpD,YAAY,EACZ,KAAK,oBAAoB,EACzB,KAAK,uBAAuB,IAAI,aAAa,EAC7C,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAE5B,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,0BAA0B,EAC1B,mBAAmB,EACnB,iBAAiB,EACjB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,eAAe,GACrB,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Internal re-export of resilience contracts
3
+ *
4
+ * This file provides a stable import path for resilience contracts
5
+ * that works in both build and test environments.
6
+ *
7
+ * It imports from the main @defai.digital/contracts and re-exports with
8
+ * the canonical names for internal use.
9
+ */
10
+ // Import circuit breaker with prefixed names from main contracts
11
+ export { ResilienceCircuitBreakerStateSchema as CircuitBreakerStateSchema, ResilienceCircuitBreakerConfigSchema as CircuitBreakerConfigSchema, ResilienceCircuitBreakerStatsSchema as CircuitBreakerStatsSchema, ResilienceCircuitBreakerEventSchema as CircuitBreakerEventSchema, ResilienceCircuitBreakerErrorCodes as CircuitBreakerErrorCodes, createDefaultResilienceCircuitBreakerConfig as createDefaultCircuitBreakerConfig, createResilienceCircuitBreakerStats as createCircuitBreakerStats,
12
+ // Rate Limiter (unique names)
13
+ RateLimiterConfigSchema, RateLimiterStatsSchema, RateLimiterAcquireResultSchema, RateLimiterErrorCodes, validateRateLimiterConfig, safeValidateRateLimiterConfig, createDefaultRateLimiterConfig, createRateLimiterStats, DEFAULT_TOKEN_WINDOW_MS, DEFAULT_CHECK_INTERVAL_MS, TIME_MULTIPLIERS, DEFAULT_TIME_RANGE_MS,
14
+ // Loop Guard (unique names)
15
+ LoopGuardConfigSchema, LoopGuardContextSchema, LoopGuardResultSchema, LoopGuardErrorCodes, validateLoopGuardConfig, safeValidateLoopGuardConfig, createDefaultLoopGuardConfig, createLoopGuardContext,
16
+ // Resource Limits (unique names, but ResourceUsage renamed)
17
+ ResourceLimitsConfigSchema, ResilienceResourceUsageSchema as ResourceUsageSchema, ResourceCheckResultSchema, ResourceRequestInfoSchema, ResourceLimitsErrorCodes, validateResourceLimitsConfig, safeValidateResourceLimitsConfig, createDefaultResourceLimitsConfig, createResilienceResourceUsage as createResourceUsage, estimateCost,
18
+ // Metrics (unique names)
19
+ MetricsTimeRangeSchema, RequestMetricSchema, ErrorMetricSchema, LatencyStatsSchema, MetricsSnapshotSchema, validateRequestMetric, validateErrorMetric, validateMetricsSnapshot, createEmptyMetricsSnapshot, createRequestMetric, createErrorMetric, } from '@defai.digital/contracts';
20
+ //# sourceMappingURL=_contracts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_contracts.js","sourceRoot":"","sources":["../src/_contracts.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,iEAAiE;AACjE,OAAO,EACL,mCAAmC,IAAI,yBAAyB,EAChE,oCAAoC,IAAI,0BAA0B,EAClE,mCAAmC,IAAI,yBAAyB,EAChE,mCAAmC,IAAI,yBAAyB,EAChE,kCAAkC,IAAI,wBAAwB,EAC9D,2CAA2C,IAAI,iCAAiC,EAChF,mCAAmC,IAAI,yBAAyB;AAMhE,8BAA8B;AAC9B,uBAAuB,EACvB,sBAAsB,EACtB,8BAA8B,EAC9B,qBAAqB,EACrB,yBAAyB,EACzB,6BAA6B,EAC7B,8BAA8B,EAC9B,sBAAsB,EACtB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,qBAAqB;AAKrB,4BAA4B;AAC5B,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,2BAA2B,EAC3B,4BAA4B,EAC5B,sBAAsB;AAKtB,4DAA4D;AAC5D,0BAA0B,EAC1B,6BAA6B,IAAI,mBAAmB,EACpD,yBAAyB,EACzB,yBAAyB,EACzB,wBAAwB,EACxB,4BAA4B,EAC5B,gCAAgC,EAChC,iCAAiC,EACjC,6BAA6B,IAAI,mBAAmB,EACpD,YAAY;AAMZ,yBAAyB;AACzB,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,0BAA0B,EAC1B,mBAAmB,EACnB,iBAAiB,GAMlB,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Circuit Breaker Implementation
3
+ *
4
+ * Prevents cascade failures by stopping calls to unhealthy providers.
5
+ */
6
+ import { type CircuitBreakerState, type CircuitBreakerConfig, type CircuitBreakerStats, type CircuitBreakerEvent } from './_contracts.js';
7
+ /**
8
+ * Circuit breaker error
9
+ */
10
+ export declare class CircuitBreakerError extends Error {
11
+ readonly code: string;
12
+ constructor(code: string, message: string);
13
+ static circuitOpen(resetInMs: number): CircuitBreakerError;
14
+ }
15
+ /**
16
+ * Circuit breaker event listener
17
+ */
18
+ export type CircuitBreakerListener = (event: CircuitBreakerEvent) => void;
19
+ /**
20
+ * Circuit breaker interface
21
+ */
22
+ export interface CircuitBreaker {
23
+ /** Current state */
24
+ readonly state: CircuitBreakerState;
25
+ /** Execute function with circuit breaker protection */
26
+ execute<T>(fn: () => Promise<T>): Promise<T>;
27
+ /** Record a successful call */
28
+ recordSuccess(): void;
29
+ /** Record a failed call */
30
+ recordFailure(error?: Error): void;
31
+ /** Get current statistics */
32
+ getStats(): CircuitBreakerStats;
33
+ /** Add event listener */
34
+ onEvent(listener: CircuitBreakerListener): () => void;
35
+ /** Reset to closed state */
36
+ reset(): void;
37
+ }
38
+ /**
39
+ * Creates a circuit breaker
40
+ */
41
+ export declare function createCircuitBreaker(config?: Partial<CircuitBreakerConfig>): CircuitBreaker;
42
+ //# sourceMappingURL=circuit-breaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.d.ts","sourceRoot":"","sources":["../src/circuit-breaker.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EAIzB,MAAM,iBAAiB,CAAC;AAEzB;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;aAE1B,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAC5B,OAAO,EAAE,MAAM;IAMjB,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,mBAAmB;CAM3D;AAED;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,oBAAoB;IACpB,QAAQ,CAAC,KAAK,EAAE,mBAAmB,CAAC;IAEpC,uDAAuD;IACvD,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAE7C,+BAA+B;IAC/B,aAAa,IAAI,IAAI,CAAC;IAEtB,2BAA2B;IAC3B,aAAa,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAEnC,6BAA6B;IAC7B,QAAQ,IAAI,mBAAmB,CAAC;IAEhC,yBAAyB;IACzB,OAAO,CAAC,QAAQ,EAAE,sBAAsB,GAAG,MAAM,IAAI,CAAC;IAEtD,4BAA4B;IAC5B,KAAK,IAAI,IAAI,CAAC;CACf;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,GACrC,cAAc,CA+LhB"}
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Circuit Breaker Implementation
3
+ *
4
+ * Prevents cascade failures by stopping calls to unhealthy providers.
5
+ */
6
+ import { CircuitBreakerErrorCodes, createDefaultCircuitBreakerConfig, createCircuitBreakerStats, } from './_contracts.js';
7
+ /**
8
+ * Circuit breaker error
9
+ */
10
+ export class CircuitBreakerError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = 'CircuitBreakerError';
16
+ }
17
+ static circuitOpen(resetInMs) {
18
+ return new CircuitBreakerError(CircuitBreakerErrorCodes.CIRCUIT_OPEN, `Circuit breaker is open. Retry after ${resetInMs}ms`);
19
+ }
20
+ }
21
+ /**
22
+ * Creates a circuit breaker
23
+ */
24
+ export function createCircuitBreaker(config) {
25
+ const cfg = { ...createDefaultCircuitBreakerConfig(), ...config };
26
+ let state = 'closed';
27
+ let stats = createCircuitBreakerStats();
28
+ let failureTimestamps = [];
29
+ let openedAt = null;
30
+ let halfOpenAttempts = 0;
31
+ const listeners = new Set();
32
+ function emit(event) {
33
+ for (const listener of listeners) {
34
+ try {
35
+ listener(event);
36
+ }
37
+ catch {
38
+ // Ignore listener errors
39
+ }
40
+ }
41
+ }
42
+ function transitionTo(newState) {
43
+ if (state === newState)
44
+ return;
45
+ const event = {
46
+ type: 'state-change',
47
+ from: state,
48
+ to: newState,
49
+ timestamp: new Date().toISOString(),
50
+ };
51
+ state = newState;
52
+ stats = { ...stats, state };
53
+ if (newState === 'open') {
54
+ openedAt = Date.now();
55
+ }
56
+ else if (newState === 'half-open') {
57
+ halfOpenAttempts = 0;
58
+ }
59
+ else if (newState === 'closed') {
60
+ openedAt = null;
61
+ failureTimestamps = [];
62
+ stats = { ...stats, recentFailures: 0, halfOpenSuccesses: 0 };
63
+ }
64
+ emit(event);
65
+ }
66
+ function cleanOldFailures() {
67
+ const cutoff = Date.now() - cfg.failureWindowMs;
68
+ failureTimestamps = failureTimestamps.filter((ts) => ts > cutoff);
69
+ stats = { ...stats, recentFailures: failureTimestamps.length };
70
+ }
71
+ function shouldOpen() {
72
+ cleanOldFailures();
73
+ return failureTimestamps.length >= cfg.failureThreshold;
74
+ }
75
+ function shouldTransitionToHalfOpen() {
76
+ if (state !== 'open' || openedAt === null)
77
+ return false;
78
+ return Date.now() - openedAt >= cfg.resetTimeoutMs;
79
+ }
80
+ function checkState() {
81
+ if (state === 'open' && shouldTransitionToHalfOpen()) {
82
+ transitionTo('half-open');
83
+ }
84
+ }
85
+ return {
86
+ get state() {
87
+ checkState();
88
+ return state;
89
+ },
90
+ async execute(fn) {
91
+ checkState();
92
+ // Check if circuit is open
93
+ if (state === 'open') {
94
+ const resetInMs = openedAt
95
+ ? Math.max(0, cfg.resetTimeoutMs - (Date.now() - openedAt))
96
+ : cfg.resetTimeoutMs;
97
+ emit({
98
+ type: 'call-rejected',
99
+ reason: 'Circuit breaker is open',
100
+ timestamp: new Date().toISOString(),
101
+ });
102
+ throw CircuitBreakerError.circuitOpen(resetInMs);
103
+ }
104
+ // Check half-open attempt limit
105
+ if (state === 'half-open' && halfOpenAttempts >= cfg.halfOpenMaxAttempts) {
106
+ emit({
107
+ type: 'call-rejected',
108
+ reason: 'Half-open attempt limit reached',
109
+ timestamp: new Date().toISOString(),
110
+ });
111
+ throw CircuitBreakerError.circuitOpen(cfg.resetTimeoutMs);
112
+ }
113
+ if (state === 'half-open') {
114
+ halfOpenAttempts++;
115
+ }
116
+ const startTime = Date.now();
117
+ try {
118
+ const result = await fn();
119
+ this.recordSuccess();
120
+ emit({
121
+ type: 'call-success',
122
+ durationMs: Date.now() - startTime,
123
+ timestamp: new Date().toISOString(),
124
+ });
125
+ return result;
126
+ }
127
+ catch (error) {
128
+ this.recordFailure(error instanceof Error ? error : undefined);
129
+ emit({
130
+ type: 'call-failure',
131
+ error: error instanceof Error ? error.message : 'Unknown error',
132
+ timestamp: new Date().toISOString(),
133
+ });
134
+ throw error;
135
+ }
136
+ },
137
+ recordSuccess() {
138
+ stats = {
139
+ ...stats,
140
+ successCount: stats.successCount + 1,
141
+ lastSuccessAt: new Date().toISOString(),
142
+ };
143
+ if (state === 'half-open') {
144
+ stats = { ...stats, halfOpenSuccesses: stats.halfOpenSuccesses + 1 };
145
+ // Single success in half-open closes the circuit
146
+ transitionTo('closed');
147
+ }
148
+ },
149
+ recordFailure(_error) {
150
+ const now = Date.now();
151
+ failureTimestamps.push(now);
152
+ stats = {
153
+ ...stats,
154
+ failureCount: stats.failureCount + 1,
155
+ recentFailures: failureTimestamps.length,
156
+ lastFailureAt: new Date().toISOString(),
157
+ };
158
+ if (state === 'half-open') {
159
+ // Failure in half-open reopens the circuit
160
+ transitionTo('open');
161
+ }
162
+ else if (state === 'closed' && shouldOpen()) {
163
+ transitionTo('open');
164
+ }
165
+ },
166
+ getStats() {
167
+ checkState();
168
+ cleanOldFailures();
169
+ return {
170
+ ...stats,
171
+ state,
172
+ openedAt: openedAt ? new Date(openedAt).toISOString() : undefined,
173
+ };
174
+ },
175
+ onEvent(listener) {
176
+ listeners.add(listener);
177
+ return () => listeners.delete(listener);
178
+ },
179
+ reset() {
180
+ transitionTo('closed');
181
+ stats = createCircuitBreakerStats();
182
+ failureTimestamps = [];
183
+ openedAt = null;
184
+ halfOpenAttempts = 0;
185
+ },
186
+ };
187
+ }
188
+ //# sourceMappingURL=circuit-breaker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.js","sourceRoot":"","sources":["../src/circuit-breaker.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAKL,wBAAwB,EACxB,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAEzB;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAE1B;IADlB,YACkB,IAAY,EAC5B,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,SAAI,GAAJ,IAAI,CAAQ;QAI5B,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,SAAiB;QAClC,OAAO,IAAI,mBAAmB,CAC5B,wBAAwB,CAAC,YAAY,EACrC,wCAAwC,SAAS,IAAI,CACtD,CAAC;IACJ,CAAC;CACF;AAiCD;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAsC;IAEtC,MAAM,GAAG,GAAG,EAAE,GAAG,iCAAiC,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC;IAElE,IAAI,KAAK,GAAwB,QAAQ,CAAC;IAC1C,IAAI,KAAK,GAAG,yBAAyB,EAAE,CAAC;IACxC,IAAI,iBAAiB,GAAa,EAAE,CAAC;IACrC,IAAI,QAAQ,GAAkB,IAAI,CAAC;IACnC,IAAI,gBAAgB,GAAG,CAAC,CAAC;IACzB,MAAM,SAAS,GAAG,IAAI,GAAG,EAA0B,CAAC;IAEpD,SAAS,IAAI,CAAC,KAA0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;YACvB,KAAK,GAAG,yBAAyB,EAAE,CAAC;YACpC,iBAAiB,GAAG,EAAE,CAAC;YACvB,QAAQ,GAAG,IAAI,CAAC;YAChB,gBAAgB,GAAG,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Resilience Domain
3
+ *
4
+ * Production-ready resilience patterns for LLM operations:
5
+ * - Circuit Breaker: Prevents cascade failures
6
+ * - Rate Limiter: Token bucket rate limiting
7
+ * - Loop Guard: Prevents infinite loops
8
+ * - Resource Enforcer: Enforces token/cost/time limits
9
+ * - Metrics Collector: Basic observability
10
+ */
11
+ export { CircuitBreaker, CircuitBreakerError, CircuitBreakerListener, createCircuitBreaker, } from './circuit-breaker.js';
12
+ export { RateLimiter, RateLimiterError, createRateLimiter, } from './rate-limiter.js';
13
+ export { LoopGuard, LoopGuardError, LoopGuardWarningListener, createLoopGuard, createStrictLoopGuard, } from './loop-guard.js';
14
+ export { ResourceEnforcer, ResourceEnforcerError, createResourceEnforcer, createStrictResourceEnforcer, } from './resource-enforcer.js';
15
+ export { MetricsCollector, MetricsCollectorConfig, createMetricsCollector, getGlobalMetrics, resetGlobalMetrics, } from './metrics-collector.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,SAAS,EACT,cAAc,EACd,wBAAwB,EACxB,eAAe,EACf,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,sBAAsB,EACtB,4BAA4B,GAC7B,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Resilience Domain
3
+ *
4
+ * Production-ready resilience patterns for LLM operations:
5
+ * - Circuit Breaker: Prevents cascade failures
6
+ * - Rate Limiter: Token bucket rate limiting
7
+ * - Loop Guard: Prevents infinite loops
8
+ * - Resource Enforcer: Enforces token/cost/time limits
9
+ * - Metrics Collector: Basic observability
10
+ */
11
+ // Circuit Breaker
12
+ export { CircuitBreakerError, createCircuitBreaker, } from './circuit-breaker.js';
13
+ // Rate Limiter
14
+ export { RateLimiterError, createRateLimiter, } from './rate-limiter.js';
15
+ // Loop Guard
16
+ export { LoopGuardError, createLoopGuard, createStrictLoopGuard, } from './loop-guard.js';
17
+ // Resource Enforcer
18
+ export { ResourceEnforcerError, createResourceEnforcer, createStrictResourceEnforcer, } from './resource-enforcer.js';
19
+ // Metrics Collector
20
+ export { createMetricsCollector, getGlobalMetrics, resetGlobalMetrics, } from './metrics-collector.js';
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,kBAAkB;AAClB,OAAO,EAEL,mBAAmB,EAEnB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAE9B,eAAe;AACf,OAAO,EAEL,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAE3B,aAAa;AACb,OAAO,EAEL,cAAc,EAEd,eAAe,EACf,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAEzB,oBAAoB;AACpB,OAAO,EAEL,qBAAqB,EACrB,sBAAsB,EACtB,4BAA4B,GAC7B,MAAM,wBAAwB,CAAC;AAEhC,oBAAoB;AACpB,OAAO,EAGL,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Loop Guard Implementation
3
+ *
4
+ * Prevents infinite loops and runaway execution.
5
+ */
6
+ import { type LoopGuardConfig, type LoopGuardContext, type LoopGuardResult } from './_contracts.js';
7
+ /**
8
+ * Loop guard error
9
+ */
10
+ export declare class LoopGuardError extends Error {
11
+ readonly code: string;
12
+ readonly context?: LoopGuardContext | undefined;
13
+ constructor(code: string, message: string, context?: LoopGuardContext | undefined);
14
+ static maxIterations(context: LoopGuardContext): LoopGuardError;
15
+ static maxDuration(context: LoopGuardContext): LoopGuardError;
16
+ static contextNotFound(contextId: string): LoopGuardError;
17
+ }
18
+ /**
19
+ * Loop guard warning listener
20
+ */
21
+ export type LoopGuardWarningListener = (contextId: string, result: LoopGuardResult & {
22
+ status: 'warning';
23
+ }) => void;
24
+ /**
25
+ * Loop guard interface
26
+ */
27
+ export interface LoopGuard {
28
+ /** Start a new execution context */
29
+ startContext(contextId: string, metadata?: Record<string, unknown>): void;
30
+ /** Check iteration and get result */
31
+ checkIteration(contextId: string): LoopGuardResult;
32
+ /** End an execution context */
33
+ endContext(contextId: string): LoopGuardContext | undefined;
34
+ /** Get context info */
35
+ getContext(contextId: string): LoopGuardContext | undefined;
36
+ /** Add warning listener */
37
+ onWarning(listener: LoopGuardWarningListener): () => void;
38
+ }
39
+ /**
40
+ * Creates a loop guard
41
+ */
42
+ export declare function createLoopGuard(config?: Partial<LoopGuardConfig>): LoopGuard;
43
+ /**
44
+ * Creates a loop guard that throws on blocked
45
+ */
46
+ export declare function createStrictLoopGuard(config?: Partial<LoopGuardConfig>): LoopGuard;
47
+ //# sourceMappingURL=loop-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop-guard.d.ts","sourceRoot":"","sources":["../src/loop-guard.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,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