@foundatiofx/fetchclient 1.0.0 → 1.1.0
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/esm/mod.js +3 -1
- package/esm/src/CircuitBreaker.js +356 -0
- package/esm/src/CircuitBreakerMiddleware.js +167 -0
- package/esm/src/DefaultHelpers.js +16 -0
- package/esm/src/FetchClient.js +8 -6
- package/esm/src/FetchClientCache.js +85 -8
- package/esm/src/FetchClientProvider.js +58 -3
- package/esm/src/mocks/MockHistory.js +63 -0
- package/esm/src/mocks/MockRegistry.js +267 -0
- package/esm/src/mocks/MockResponseBuilder.js +88 -0
- package/esm/src/mocks/mod.js +24 -0
- package/esm/src/mocks/types.js +1 -0
- package/package.json +12 -2
- package/readme.md +88 -233
- package/script/mod.js +9 -1
- package/script/src/CircuitBreaker.js +361 -0
- package/script/src/CircuitBreakerMiddleware.js +174 -0
- package/script/src/DefaultHelpers.js +18 -0
- package/script/src/FetchClient.js +8 -6
- package/script/src/FetchClientCache.js +85 -8
- package/script/src/FetchClientProvider.js +58 -3
- package/script/src/mocks/MockHistory.js +67 -0
- package/script/src/mocks/MockRegistry.js +271 -0
- package/script/src/mocks/MockResponseBuilder.js +92 -0
- package/script/src/mocks/mod.js +29 -0
- package/script/src/mocks/types.js +2 -0
- package/types/deps/jsr.io/@std/assert/1.0.18/almost_equals.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/assert/1.0.18/array_includes.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/assert/1.0.18/assert.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/assertion_error.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/1.0.18/equal.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/equals.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/exists.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/fail.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/false.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/greater.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/greater_or_equal.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/instance_of.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/is_error.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/less.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/less_or_equal.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/match.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/mod.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/not_equals.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/not_instance_of.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/not_match.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/not_strict_equals.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/object_match.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/rejects.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/strict_equals.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/string_includes.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/throws.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/unimplemented.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/assert/{1.0.14 → 1.0.18}/unreachable.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/internal/1.0.12/build_message.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/internal/{1.0.10 → 1.0.12}/diff.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/internal/1.0.12/diff_str.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/internal/{1.0.10 → 1.0.12}/format.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/internal/{1.0.10 → 1.0.12}/styles.d.ts.map +1 -1
- package/types/deps/jsr.io/@std/internal/1.0.12/types.d.ts.map +1 -0
- package/types/mod.d.ts +3 -1
- package/types/mod.d.ts.map +1 -1
- package/types/src/CircuitBreaker.d.ts +154 -0
- package/types/src/CircuitBreaker.d.ts.map +1 -0
- package/types/src/CircuitBreakerMiddleware.d.ts +93 -0
- package/types/src/CircuitBreakerMiddleware.d.ts.map +1 -0
- package/types/src/DefaultHelpers.d.ts +13 -0
- package/types/src/DefaultHelpers.d.ts.map +1 -1
- package/types/src/FetchClient.d.ts.map +1 -1
- package/types/src/FetchClientCache.d.ts +26 -1
- package/types/src/FetchClientCache.d.ts.map +1 -1
- package/types/src/FetchClientProvider.d.ts +24 -0
- package/types/src/FetchClientProvider.d.ts.map +1 -1
- package/types/src/RequestOptions.d.ts +6 -1
- package/types/src/RequestOptions.d.ts.map +1 -1
- package/types/src/mocks/MockHistory.d.ts +22 -0
- package/types/src/mocks/MockHistory.d.ts.map +1 -0
- package/types/src/mocks/MockRegistry.d.ts +113 -0
- package/types/src/mocks/MockRegistry.d.ts.map +1 -0
- package/types/src/mocks/MockResponseBuilder.d.ts +60 -0
- package/types/src/mocks/MockResponseBuilder.d.ts.map +1 -0
- package/types/src/mocks/mod.d.ts +26 -0
- package/types/src/mocks/mod.d.ts.map +1 -0
- package/types/src/mocks/types.d.ts +47 -0
- package/types/src/mocks/types.d.ts.map +1 -0
- package/types/src/tests/Caching.test.d.ts.map +1 -0
- package/types/src/tests/CircuitBreaker.test.d.ts.map +1 -0
- package/types/src/tests/ErrorHandling.test.d.ts.map +1 -0
- package/types/src/tests/HttpMethods.test.d.ts.map +1 -0
- package/types/src/tests/Integration.test.d.ts.map +1 -0
- package/types/src/tests/JsonParsing.test.d.ts.map +1 -0
- package/types/src/tests/Middleware.test.d.ts.map +1 -0
- package/types/src/tests/MockRegistry.test.d.ts.map +1 -0
- package/types/src/tests/Provider.test.d.ts.map +1 -0
- package/types/src/tests/RateLimit.test.d.ts.map +1 -0
- package/types/src/tests/TimeoutAbort.test.d.ts.map +1 -0
- package/types/src/tests/UrlBuilding.test.d.ts.map +1 -0
- package/types/deps/jsr.io/@std/assert/1.0.14/almost_equals.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/assert/1.0.14/array_includes.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/assert/1.0.14/assert.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/assert/1.0.14/equal.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/internal/1.0.10/build_message.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/internal/1.0.10/diff_str.d.ts.map +0 -1
- package/types/deps/jsr.io/@std/internal/1.0.10/types.d.ts.map +0 -1
- package/types/src/FetchClient.test.d.ts.map +0 -1
- package/types/src/RateLimit.test.d.ts.map +0 -1
|
@@ -6,19 +6,36 @@ exports.FetchClientCache = void 0;
|
|
|
6
6
|
*/
|
|
7
7
|
class FetchClientCache {
|
|
8
8
|
cache = new Map();
|
|
9
|
+
tagIndex = new Map();
|
|
9
10
|
/**
|
|
10
11
|
* Sets a response in the cache with the specified key.
|
|
11
12
|
* @param key - The cache key.
|
|
12
13
|
* @param response - The response to be cached.
|
|
13
14
|
* @param cacheDuration - The duration for which the response should be cached (in milliseconds).
|
|
15
|
+
* @param tags - Optional tags for grouping and invalidating cache entries.
|
|
14
16
|
*/
|
|
15
|
-
set(key, response, cacheDuration) {
|
|
16
|
-
this.
|
|
17
|
+
set(key, response, cacheDuration, tags) {
|
|
18
|
+
const hash = this.getHash(key);
|
|
19
|
+
const normalizedTags = tags ?? [];
|
|
20
|
+
// Remove old tag associations if entry exists
|
|
21
|
+
const existingEntry = this.cache.get(hash);
|
|
22
|
+
if (existingEntry) {
|
|
23
|
+
this.removeTagAssociations(hash, existingEntry.tags);
|
|
24
|
+
}
|
|
25
|
+
this.cache.set(hash, {
|
|
17
26
|
key,
|
|
27
|
+
tags: normalizedTags,
|
|
18
28
|
lastAccess: new Date(),
|
|
19
29
|
expires: new Date(Date.now() + (cacheDuration ?? 60000)),
|
|
20
30
|
response,
|
|
21
31
|
});
|
|
32
|
+
// Add new tag associations
|
|
33
|
+
for (const tag of normalizedTags) {
|
|
34
|
+
if (!this.tagIndex.has(tag)) {
|
|
35
|
+
this.tagIndex.set(tag, new Set());
|
|
36
|
+
}
|
|
37
|
+
this.tagIndex.get(tag).add(hash);
|
|
38
|
+
}
|
|
22
39
|
}
|
|
23
40
|
/**
|
|
24
41
|
* Retrieves a response from the cache with the specified key.
|
|
@@ -26,12 +43,14 @@ class FetchClientCache {
|
|
|
26
43
|
* @returns The cached response, or null if the response is not found or has expired.
|
|
27
44
|
*/
|
|
28
45
|
get(key) {
|
|
29
|
-
const
|
|
46
|
+
const hash = this.getHash(key);
|
|
47
|
+
const cacheEntry = this.cache.get(hash);
|
|
30
48
|
if (!cacheEntry) {
|
|
31
49
|
return null;
|
|
32
50
|
}
|
|
33
51
|
if (cacheEntry.expires < new Date()) {
|
|
34
|
-
this.
|
|
52
|
+
this.removeTagAssociations(hash, cacheEntry.tags);
|
|
53
|
+
this.cache.delete(hash);
|
|
35
54
|
return null;
|
|
36
55
|
}
|
|
37
56
|
cacheEntry.lastAccess = new Date();
|
|
@@ -43,7 +62,12 @@ class FetchClientCache {
|
|
|
43
62
|
* @returns True if the response was successfully deleted, false otherwise.
|
|
44
63
|
*/
|
|
45
64
|
delete(key) {
|
|
46
|
-
|
|
65
|
+
const hash = this.getHash(key);
|
|
66
|
+
const entry = this.cache.get(hash);
|
|
67
|
+
if (entry) {
|
|
68
|
+
this.removeTagAssociations(hash, entry.tags);
|
|
69
|
+
}
|
|
70
|
+
return this.cache.delete(hash);
|
|
47
71
|
}
|
|
48
72
|
/**
|
|
49
73
|
* Deletes all responses from the cache that have keys beginning with the specified key.
|
|
@@ -52,15 +76,56 @@ class FetchClientCache {
|
|
|
52
76
|
*/
|
|
53
77
|
deleteAll(prefix) {
|
|
54
78
|
let count = 0;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
79
|
+
const prefixHash = this.getHash(prefix);
|
|
80
|
+
for (const [hash, entry] of this.cache.entries()) {
|
|
81
|
+
if (hash.startsWith(prefixHash)) {
|
|
82
|
+
this.removeTagAssociations(hash, entry.tags);
|
|
83
|
+
if (this.cache.delete(hash)) {
|
|
84
|
+
count++;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return count;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Deletes all responses from the cache that have the specified tag.
|
|
92
|
+
* @param tag - The cache tag.
|
|
93
|
+
* @returns The number of responses that were deleted.
|
|
94
|
+
*/
|
|
95
|
+
deleteByTag(tag) {
|
|
96
|
+
const hashes = this.tagIndex.get(tag);
|
|
97
|
+
if (!hashes) {
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
let count = 0;
|
|
101
|
+
for (const hash of hashes) {
|
|
102
|
+
const entry = this.cache.get(hash);
|
|
103
|
+
if (entry) {
|
|
104
|
+
// Remove this entry's associations from all its tags
|
|
105
|
+
this.removeTagAssociations(hash, entry.tags);
|
|
106
|
+
if (this.cache.delete(hash)) {
|
|
58
107
|
count++;
|
|
59
108
|
}
|
|
60
109
|
}
|
|
61
110
|
}
|
|
62
111
|
return count;
|
|
63
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* Gets all tags currently in use in the cache.
|
|
115
|
+
* @returns An array of all cache tags.
|
|
116
|
+
*/
|
|
117
|
+
getTags() {
|
|
118
|
+
return Array.from(this.tagIndex.keys()).filter((tag) => this.tagIndex.get(tag).size > 0);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Gets the tags associated with a cache entry.
|
|
122
|
+
* @param key - The cache key.
|
|
123
|
+
* @returns The tags associated with the entry, or an empty array if not found.
|
|
124
|
+
*/
|
|
125
|
+
getEntryTags(key) {
|
|
126
|
+
const entry = this.cache.get(this.getHash(key));
|
|
127
|
+
return entry?.tags ?? [];
|
|
128
|
+
}
|
|
64
129
|
/**
|
|
65
130
|
* Checks if a response exists in the cache with the specified key.
|
|
66
131
|
* @param key - The cache key.
|
|
@@ -81,6 +146,7 @@ class FetchClientCache {
|
|
|
81
146
|
*/
|
|
82
147
|
clear() {
|
|
83
148
|
this.cache.clear();
|
|
149
|
+
this.tagIndex.clear();
|
|
84
150
|
}
|
|
85
151
|
getHash(key) {
|
|
86
152
|
if (key instanceof Array) {
|
|
@@ -88,5 +154,16 @@ class FetchClientCache {
|
|
|
88
154
|
}
|
|
89
155
|
return key;
|
|
90
156
|
}
|
|
157
|
+
removeTagAssociations(hash, tags) {
|
|
158
|
+
for (const tag of tags) {
|
|
159
|
+
const hashes = this.tagIndex.get(tag);
|
|
160
|
+
if (hashes) {
|
|
161
|
+
hashes.delete(hash);
|
|
162
|
+
if (hashes.size === 0) {
|
|
163
|
+
this.tagIndex.delete(tag);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
91
168
|
}
|
|
92
169
|
exports.FetchClientCache = FetchClientCache;
|
|
@@ -7,6 +7,8 @@ const FetchClientCache_js_1 = require("./FetchClientCache.js");
|
|
|
7
7
|
const ObjectEvent_js_1 = require("./ObjectEvent.js");
|
|
8
8
|
const RateLimitMiddleware_js_1 = require("./RateLimitMiddleware.js");
|
|
9
9
|
const RateLimiter_js_1 = require("./RateLimiter.js");
|
|
10
|
+
const CircuitBreakerMiddleware_js_1 = require("./CircuitBreakerMiddleware.js");
|
|
11
|
+
const CircuitBreaker_js_1 = require("./CircuitBreaker.js");
|
|
10
12
|
/**
|
|
11
13
|
* Represents a provider for creating instances of the FetchClient class with shared default options and cache.
|
|
12
14
|
*/
|
|
@@ -15,6 +17,9 @@ class FetchClientProvider {
|
|
|
15
17
|
#fetch;
|
|
16
18
|
#cache;
|
|
17
19
|
#rateLimitMiddleware;
|
|
20
|
+
#rateLimitMiddlewareFunc;
|
|
21
|
+
#circuitBreakerMiddleware;
|
|
22
|
+
#circuitBreakerMiddlewareFunc;
|
|
18
23
|
#counter = new Counter_js_1.Counter();
|
|
19
24
|
#onLoading = new ObjectEvent_js_1.ObjectEvent();
|
|
20
25
|
/**
|
|
@@ -171,7 +176,8 @@ class FetchClientProvider {
|
|
|
171
176
|
*/
|
|
172
177
|
useRateLimit(options) {
|
|
173
178
|
this.#rateLimitMiddleware = new RateLimitMiddleware_js_1.RateLimitMiddleware(options);
|
|
174
|
-
this
|
|
179
|
+
this.#rateLimitMiddlewareFunc = this.#rateLimitMiddleware.middleware();
|
|
180
|
+
this.useMiddleware(this.#rateLimitMiddlewareFunc);
|
|
175
181
|
}
|
|
176
182
|
/**
|
|
177
183
|
* Enables rate limiting for all FetchClient instances created by this provider.
|
|
@@ -182,7 +188,8 @@ class FetchClientProvider {
|
|
|
182
188
|
...options,
|
|
183
189
|
getGroupFunc: RateLimiter_js_1.groupByDomain,
|
|
184
190
|
});
|
|
185
|
-
this
|
|
191
|
+
this.#rateLimitMiddlewareFunc = this.#rateLimitMiddleware.middleware();
|
|
192
|
+
this.useMiddleware(this.#rateLimitMiddlewareFunc);
|
|
186
193
|
}
|
|
187
194
|
/**
|
|
188
195
|
* Gets the rate limiter instance used for rate limiting.
|
|
@@ -195,8 +202,56 @@ class FetchClientProvider {
|
|
|
195
202
|
* Removes the rate limiting middleware from all FetchClient instances created by this provider.
|
|
196
203
|
*/
|
|
197
204
|
removeRateLimit() {
|
|
205
|
+
const middlewareFunc = this.#rateLimitMiddlewareFunc;
|
|
198
206
|
this.#rateLimitMiddleware = undefined;
|
|
199
|
-
this.#
|
|
207
|
+
this.#rateLimitMiddlewareFunc = undefined;
|
|
208
|
+
if (middlewareFunc) {
|
|
209
|
+
this.#options.middleware = this.#options.middleware?.filter((m) => m !== middlewareFunc);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Enables circuit breaker for all FetchClient instances created by this provider.
|
|
214
|
+
* The circuit breaker monitors failures and blocks requests when a service is failing,
|
|
215
|
+
* allowing time for recovery.
|
|
216
|
+
* @param options - The circuit breaker configuration options.
|
|
217
|
+
*/
|
|
218
|
+
useCircuitBreaker(options) {
|
|
219
|
+
this.#circuitBreakerMiddleware = new CircuitBreakerMiddleware_js_1.CircuitBreakerMiddleware(options);
|
|
220
|
+
this.#circuitBreakerMiddlewareFunc = this.#circuitBreakerMiddleware
|
|
221
|
+
.middleware();
|
|
222
|
+
this.useMiddleware(this.#circuitBreakerMiddlewareFunc);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Enables per-domain circuit breaker for all FetchClient instances created by this provider.
|
|
226
|
+
* Each domain gets its own circuit breaker, so failures on one domain don't affect others.
|
|
227
|
+
* @param options - The circuit breaker configuration options.
|
|
228
|
+
*/
|
|
229
|
+
usePerDomainCircuitBreaker(options) {
|
|
230
|
+
this.#circuitBreakerMiddleware = new CircuitBreakerMiddleware_js_1.CircuitBreakerMiddleware({
|
|
231
|
+
...options,
|
|
232
|
+
getGroupFunc: CircuitBreaker_js_1.groupByDomain,
|
|
233
|
+
});
|
|
234
|
+
this.#circuitBreakerMiddlewareFunc = this.#circuitBreakerMiddleware
|
|
235
|
+
.middleware();
|
|
236
|
+
this.useMiddleware(this.#circuitBreakerMiddlewareFunc);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Gets the circuit breaker instance.
|
|
240
|
+
* @returns The circuit breaker instance, or undefined if not enabled.
|
|
241
|
+
*/
|
|
242
|
+
get circuitBreaker() {
|
|
243
|
+
return this.#circuitBreakerMiddleware?.circuitBreaker;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Removes the circuit breaker middleware from all FetchClient instances created by this provider.
|
|
247
|
+
*/
|
|
248
|
+
removeCircuitBreaker() {
|
|
249
|
+
const middlewareFunc = this.#circuitBreakerMiddlewareFunc;
|
|
250
|
+
this.#circuitBreakerMiddleware = undefined;
|
|
251
|
+
this.#circuitBreakerMiddlewareFunc = undefined;
|
|
252
|
+
if (middlewareFunc) {
|
|
253
|
+
this.#options.middleware = this.#options.middleware?.filter((m) => m !== middlewareFunc);
|
|
254
|
+
}
|
|
200
255
|
}
|
|
201
256
|
}
|
|
202
257
|
exports.FetchClientProvider = FetchClientProvider;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MockHistoryImpl = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Implementation of MockHistory that tracks recorded requests.
|
|
6
|
+
*/
|
|
7
|
+
class MockHistoryImpl {
|
|
8
|
+
#get = [];
|
|
9
|
+
#post = [];
|
|
10
|
+
#put = [];
|
|
11
|
+
#patch = [];
|
|
12
|
+
#delete = [];
|
|
13
|
+
#all = [];
|
|
14
|
+
get get() {
|
|
15
|
+
return [...this.#get];
|
|
16
|
+
}
|
|
17
|
+
get post() {
|
|
18
|
+
return [...this.#post];
|
|
19
|
+
}
|
|
20
|
+
get put() {
|
|
21
|
+
return [...this.#put];
|
|
22
|
+
}
|
|
23
|
+
get patch() {
|
|
24
|
+
return [...this.#patch];
|
|
25
|
+
}
|
|
26
|
+
get delete() {
|
|
27
|
+
return [...this.#delete];
|
|
28
|
+
}
|
|
29
|
+
get all() {
|
|
30
|
+
return [...this.#all];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Records a request in the history.
|
|
34
|
+
*/
|
|
35
|
+
record(request) {
|
|
36
|
+
this.#all.push(request);
|
|
37
|
+
switch (request.method.toUpperCase()) {
|
|
38
|
+
case "GET":
|
|
39
|
+
this.#get.push(request);
|
|
40
|
+
break;
|
|
41
|
+
case "POST":
|
|
42
|
+
this.#post.push(request);
|
|
43
|
+
break;
|
|
44
|
+
case "PUT":
|
|
45
|
+
this.#put.push(request);
|
|
46
|
+
break;
|
|
47
|
+
case "PATCH":
|
|
48
|
+
this.#patch.push(request);
|
|
49
|
+
break;
|
|
50
|
+
case "DELETE":
|
|
51
|
+
this.#delete.push(request);
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Clears all recorded history.
|
|
57
|
+
*/
|
|
58
|
+
clear() {
|
|
59
|
+
this.#get = [];
|
|
60
|
+
this.#post = [];
|
|
61
|
+
this.#put = [];
|
|
62
|
+
this.#patch = [];
|
|
63
|
+
this.#delete = [];
|
|
64
|
+
this.#all = [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.MockHistoryImpl = MockHistoryImpl;
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MockRegistry = void 0;
|
|
4
|
+
const MockHistory_js_1 = require("./MockHistory.js");
|
|
5
|
+
const MockResponseBuilder_js_1 = require("./MockResponseBuilder.js");
|
|
6
|
+
/**
|
|
7
|
+
* A registry for defining mock responses that can be installed on a
|
|
8
|
+
* FetchClient or FetchClientProvider, or used as a standalone fetch replacement.
|
|
9
|
+
*
|
|
10
|
+
* @example Install on FetchClientProvider
|
|
11
|
+
* ```typescript
|
|
12
|
+
* const mocks = new MockRegistry();
|
|
13
|
+
* mocks.onGet('/api/users').reply(200, [{ id: 1 }]);
|
|
14
|
+
*
|
|
15
|
+
* const provider = new FetchClientProvider();
|
|
16
|
+
* mocks.install(provider);
|
|
17
|
+
*
|
|
18
|
+
* const client = provider.getFetchClient();
|
|
19
|
+
* const response = await client.getJSON('/api/users');
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* @example Use as standalone fetch replacement
|
|
23
|
+
* ```typescript
|
|
24
|
+
* const mocks = new MockRegistry();
|
|
25
|
+
* mocks.onGet('/api/users').reply(200, [{ id: 1 }]);
|
|
26
|
+
*
|
|
27
|
+
* // Use directly as fetch
|
|
28
|
+
* const response = await mocks.fetch('/api/users');
|
|
29
|
+
*
|
|
30
|
+
* // Or pass to any library expecting a fetch function
|
|
31
|
+
* const client = new SomeHttpClient({ fetch: mocks.fetch });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
class MockRegistry {
|
|
35
|
+
#mocks = [];
|
|
36
|
+
#history = new MockHistory_js_1.MockHistoryImpl();
|
|
37
|
+
#target = null;
|
|
38
|
+
#originalFetch = undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Creates a mock for GET requests matching the given URL.
|
|
41
|
+
* @param url - URL string or RegExp to match
|
|
42
|
+
*/
|
|
43
|
+
onGet(url) {
|
|
44
|
+
return this.#addMock("GET", url);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Creates a mock for POST requests matching the given URL.
|
|
48
|
+
* @param url - URL string or RegExp to match
|
|
49
|
+
*/
|
|
50
|
+
onPost(url) {
|
|
51
|
+
return this.#addMock("POST", url);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Creates a mock for PUT requests matching the given URL.
|
|
55
|
+
* @param url - URL string or RegExp to match
|
|
56
|
+
*/
|
|
57
|
+
onPut(url) {
|
|
58
|
+
return this.#addMock("PUT", url);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Creates a mock for PATCH requests matching the given URL.
|
|
62
|
+
* @param url - URL string or RegExp to match
|
|
63
|
+
*/
|
|
64
|
+
onPatch(url) {
|
|
65
|
+
return this.#addMock("PATCH", url);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Creates a mock for DELETE requests matching the given URL.
|
|
69
|
+
* @param url - URL string or RegExp to match
|
|
70
|
+
*/
|
|
71
|
+
onDelete(url) {
|
|
72
|
+
return this.#addMock("DELETE", url);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Creates a mock for any HTTP method matching the given URL.
|
|
76
|
+
* @param url - URL string or RegExp to match
|
|
77
|
+
*/
|
|
78
|
+
onAny(url) {
|
|
79
|
+
return this.#addMock(null, url);
|
|
80
|
+
}
|
|
81
|
+
#addMock(method, url) {
|
|
82
|
+
const mock = {
|
|
83
|
+
method,
|
|
84
|
+
url,
|
|
85
|
+
status: 200,
|
|
86
|
+
once: false,
|
|
87
|
+
passthrough: false,
|
|
88
|
+
timeout: false,
|
|
89
|
+
};
|
|
90
|
+
this.#mocks.push(mock);
|
|
91
|
+
return new MockResponseBuilder_js_1.MockResponseBuilder(mock, this);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Installs the mock registry on a FetchClient or FetchClientProvider.
|
|
95
|
+
* Replaces the fetch implementation to intercept requests.
|
|
96
|
+
*
|
|
97
|
+
* @param target - The FetchClient or FetchClientProvider to install on
|
|
98
|
+
* @throws Error if already installed on another target
|
|
99
|
+
*/
|
|
100
|
+
install(target) {
|
|
101
|
+
if (this.#target) {
|
|
102
|
+
throw new Error("MockRegistry is already installed. Call restore() first.");
|
|
103
|
+
}
|
|
104
|
+
// If target is FetchClient, use its provider
|
|
105
|
+
const provider = "provider" in target && typeof target.provider !== "undefined"
|
|
106
|
+
? target.provider
|
|
107
|
+
: target;
|
|
108
|
+
this.#target = provider;
|
|
109
|
+
this.#originalFetch = provider.fetch;
|
|
110
|
+
// Replace fetch with our mock handler
|
|
111
|
+
provider.fetch = ((input, init) => {
|
|
112
|
+
return this.#handleRequest(input, init);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Restores the original fetch implementation.
|
|
117
|
+
*/
|
|
118
|
+
restore() {
|
|
119
|
+
if (!this.#target)
|
|
120
|
+
return;
|
|
121
|
+
this.#target.fetch = this.#originalFetch;
|
|
122
|
+
this.#target = null;
|
|
123
|
+
this.#originalFetch = undefined;
|
|
124
|
+
}
|
|
125
|
+
async #handleRequest(input, init) {
|
|
126
|
+
const signal = init?.signal;
|
|
127
|
+
// Check if already aborted
|
|
128
|
+
if (signal?.aborted) {
|
|
129
|
+
throw signal.reason;
|
|
130
|
+
}
|
|
131
|
+
const request = new Request(input, init);
|
|
132
|
+
this.#history.record(request);
|
|
133
|
+
const mock = this.#match(request);
|
|
134
|
+
if (!mock) {
|
|
135
|
+
// No mock found - call original fetch or global fetch
|
|
136
|
+
if (this.#originalFetch) {
|
|
137
|
+
return this.#originalFetch(input, init);
|
|
138
|
+
}
|
|
139
|
+
return fetch(input, init);
|
|
140
|
+
}
|
|
141
|
+
if (mock.passthrough) {
|
|
142
|
+
if (this.#originalFetch) {
|
|
143
|
+
return this.#originalFetch(input, init);
|
|
144
|
+
}
|
|
145
|
+
return fetch(input, init);
|
|
146
|
+
}
|
|
147
|
+
if (mock.delay) {
|
|
148
|
+
await this.#delayWithAbort(mock.delay, signal);
|
|
149
|
+
}
|
|
150
|
+
// Check again after delay
|
|
151
|
+
if (signal?.aborted) {
|
|
152
|
+
throw signal.reason;
|
|
153
|
+
}
|
|
154
|
+
if (mock.networkError) {
|
|
155
|
+
throw new TypeError(mock.networkError);
|
|
156
|
+
}
|
|
157
|
+
if (mock.timeout) {
|
|
158
|
+
throw new DOMException("The operation was aborted.", "TimeoutError");
|
|
159
|
+
}
|
|
160
|
+
// Build mock response
|
|
161
|
+
const headers = new Headers(mock.headers);
|
|
162
|
+
if (mock.data !== undefined && !headers.has("Content-Type")) {
|
|
163
|
+
headers.set("Content-Type", "application/json");
|
|
164
|
+
}
|
|
165
|
+
return new Response(mock.data !== undefined ? JSON.stringify(mock.data) : null, { status: mock.status, headers });
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Delay that respects abort signals.
|
|
169
|
+
*/
|
|
170
|
+
#delayWithAbort(ms, signal) {
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
const timeoutId = setTimeout(resolve, ms);
|
|
173
|
+
if (signal) {
|
|
174
|
+
const abortHandler = () => {
|
|
175
|
+
clearTimeout(timeoutId);
|
|
176
|
+
reject(signal.reason);
|
|
177
|
+
};
|
|
178
|
+
if (signal.aborted) {
|
|
179
|
+
clearTimeout(timeoutId);
|
|
180
|
+
reject(signal.reason);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
#match(request) {
|
|
188
|
+
for (let i = 0; i < this.#mocks.length; i++) {
|
|
189
|
+
const mock = this.#mocks[i];
|
|
190
|
+
// Check method
|
|
191
|
+
if (mock.method && mock.method !== request.method)
|
|
192
|
+
continue;
|
|
193
|
+
// Check URL
|
|
194
|
+
const url = request.url;
|
|
195
|
+
if (mock.url instanceof RegExp) {
|
|
196
|
+
if (!mock.url.test(url))
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
// Match if URL ends with the pattern or contains it
|
|
201
|
+
if (!url.endsWith(mock.url) && !url.includes(mock.url))
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
// Check headers if specified
|
|
205
|
+
if (mock.headerMatchers) {
|
|
206
|
+
let headersMatch = true;
|
|
207
|
+
for (const [key, value] of Object.entries(mock.headerMatchers)) {
|
|
208
|
+
if (request.headers.get(key) !== value) {
|
|
209
|
+
headersMatch = false;
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (!headersMatch)
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
// Found a match - remove if once
|
|
217
|
+
if (mock.once) {
|
|
218
|
+
this.#mocks.splice(i, 1);
|
|
219
|
+
}
|
|
220
|
+
return mock;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Gets the recorded request history.
|
|
226
|
+
*/
|
|
227
|
+
get history() {
|
|
228
|
+
return this.#history;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Gets the mock fetch function for standalone use.
|
|
232
|
+
* This allows using MockRegistry with any code that accepts a fetch function.
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```typescript
|
|
236
|
+
* const mocks = new MockRegistry();
|
|
237
|
+
* mocks.onGet('/api/data').reply(200, { value: 42 });
|
|
238
|
+
*
|
|
239
|
+
* // Use directly
|
|
240
|
+
* const response = await mocks.fetch('/api/data');
|
|
241
|
+
*
|
|
242
|
+
* // Or pass to other libraries
|
|
243
|
+
* const client = new SomeClient({ fetch: mocks.fetch });
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
get fetch() {
|
|
247
|
+
return ((input, init) => {
|
|
248
|
+
return this.#handleRequest(input, init);
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Clears all mocks and history.
|
|
253
|
+
*/
|
|
254
|
+
reset() {
|
|
255
|
+
this.resetMocks();
|
|
256
|
+
this.resetHistory();
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Clears all mocks but keeps history.
|
|
260
|
+
*/
|
|
261
|
+
resetMocks() {
|
|
262
|
+
this.#mocks = [];
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Clears history but keeps mocks.
|
|
266
|
+
*/
|
|
267
|
+
resetHistory() {
|
|
268
|
+
this.#history.clear();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
exports.MockRegistry = MockRegistry;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MockResponseBuilder = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Fluent builder for configuring mock responses.
|
|
6
|
+
* @template T The type of the registry (for chaining)
|
|
7
|
+
*/
|
|
8
|
+
class MockResponseBuilder {
|
|
9
|
+
#mock;
|
|
10
|
+
#registry;
|
|
11
|
+
constructor(mock, registry) {
|
|
12
|
+
this.#mock = mock;
|
|
13
|
+
this.#registry = registry;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Sets the response status, data, and optional headers.
|
|
17
|
+
* @param status - HTTP status code
|
|
18
|
+
* @param data - Response data (will be JSON stringified)
|
|
19
|
+
* @param headers - Optional response headers
|
|
20
|
+
* @returns The registry for chaining
|
|
21
|
+
*/
|
|
22
|
+
reply(status, data, headers) {
|
|
23
|
+
this.#mock.status = status;
|
|
24
|
+
this.#mock.data = data;
|
|
25
|
+
this.#mock.headers = headers;
|
|
26
|
+
return this.#registry;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Sets a one-time response that is removed after the first match.
|
|
30
|
+
* @param status - HTTP status code
|
|
31
|
+
* @param data - Response data (will be JSON stringified)
|
|
32
|
+
* @param headers - Optional response headers
|
|
33
|
+
* @returns The registry for chaining
|
|
34
|
+
*/
|
|
35
|
+
replyOnce(status, data, headers) {
|
|
36
|
+
this.#mock.once = true;
|
|
37
|
+
return this.reply(status, data, headers);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Simulates a network error by throwing a TypeError.
|
|
41
|
+
* @param message - Error message (default: "Network error")
|
|
42
|
+
* @returns The registry for chaining
|
|
43
|
+
*/
|
|
44
|
+
networkError(message = "Network error") {
|
|
45
|
+
this.#mock.networkError = message;
|
|
46
|
+
return this.#registry;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Simulates a timeout by throwing a TimeoutError.
|
|
50
|
+
* @returns The registry for chaining
|
|
51
|
+
*/
|
|
52
|
+
timeout() {
|
|
53
|
+
this.#mock.timeout = true;
|
|
54
|
+
return this.#registry;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Passes the request through to the real fetch implementation.
|
|
58
|
+
* @returns The registry for chaining
|
|
59
|
+
*/
|
|
60
|
+
passthrough() {
|
|
61
|
+
this.#mock.passthrough = true;
|
|
62
|
+
return this.#registry;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Adds header matching requirements for this mock.
|
|
66
|
+
* @param headers - Headers that must be present and match
|
|
67
|
+
* @returns This builder for further configuration
|
|
68
|
+
*/
|
|
69
|
+
withHeaders(headers) {
|
|
70
|
+
this.#mock.headerMatchers = headers;
|
|
71
|
+
return this;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Adds body matching requirements for this mock.
|
|
75
|
+
* @param body - Exact body to match, or a predicate function
|
|
76
|
+
* @returns This builder for further configuration
|
|
77
|
+
*/
|
|
78
|
+
withBody(body) {
|
|
79
|
+
this.#mock.bodyMatcher = body;
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Adds a delay before returning the response.
|
|
84
|
+
* @param ms - Delay in milliseconds
|
|
85
|
+
* @returns This builder for further configuration
|
|
86
|
+
*/
|
|
87
|
+
delay(ms) {
|
|
88
|
+
this.#mock.delay = ms;
|
|
89
|
+
return this;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.MockResponseBuilder = MockResponseBuilder;
|