req-race 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/bin/req-race.js +84 -44
  4. package/config.schema.json +16 -0
  5. package/dist/browser/req-race.global.js +1 -0
  6. package/dist/cjs/browser.cjs +843 -0
  7. package/dist/cjs/cypress.cjs +618 -0
  8. package/dist/cjs/index.cjs +1064 -0
  9. package/dist/cjs/package.json +3 -0
  10. package/dist/cjs/playwright.cjs +257 -0
  11. package/dist/cjs/puppeteer.cjs +257 -0
  12. package/dist/esm/browser.js +813 -0
  13. package/dist/esm/cypress.js +591 -0
  14. package/dist/esm/index.js +1002 -0
  15. package/dist/esm/playwright.js +221 -0
  16. package/dist/esm/puppeteer.js +221 -0
  17. package/dist/types/browser.d.cts +9 -0
  18. package/dist/types/browser.d.ts +9 -0
  19. package/dist/types/chaos.d.cts +25 -0
  20. package/dist/types/chaos.d.ts +25 -0
  21. package/dist/types/config.d.cts +3 -0
  22. package/dist/types/config.d.ts +3 -0
  23. package/dist/types/cypress.d.cts +1 -0
  24. package/dist/types/cypress.d.ts +1 -0
  25. package/dist/types/index.d.cts +7 -0
  26. package/dist/types/index.d.ts +7 -0
  27. package/dist/types/playwright.d.cts +82 -0
  28. package/dist/types/playwright.d.ts +82 -0
  29. package/dist/types/prng.d.cts +1 -0
  30. package/dist/types/prng.d.ts +1 -0
  31. package/dist/types/puppeteer.d.cts +2 -0
  32. package/dist/types/puppeteer.d.ts +2 -0
  33. package/dist/types/reporters.d.cts +33 -0
  34. package/dist/types/reporters.d.ts +33 -0
  35. package/dist/types/safe-fetch.d.cts +24 -0
  36. package/dist/types/safe-fetch.d.ts +24 -0
  37. package/dist/types/types.d.cts +215 -0
  38. package/dist/types/types.d.ts +215 -0
  39. package/package.json +87 -13
  40. package/src/index.d.ts +0 -56
  41. package/src/index.js +0 -373
  42. package/src/playwright.d.ts +0 -30
  43. package/src/playwright.js +0 -113
@@ -0,0 +1,618 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/cypress.ts
21
+ var cypress_exports = {};
22
+ __export(cypress_exports, {
23
+ registerCypressRaceCommands: () => registerCypressRaceCommands
24
+ });
25
+ module.exports = __toCommonJS(cypress_exports);
26
+
27
+ // src/prng.ts
28
+ function createSeededRandom(seed = Date.now()) {
29
+ let h = 2166136261;
30
+ const s = String(seed);
31
+ for (let i = 0; i < s.length; i++) {
32
+ h ^= s.charCodeAt(i);
33
+ h = Math.imul(h, 16777619);
34
+ }
35
+ let state = h >>> 0;
36
+ return function nextRandom() {
37
+ state = state + 1831565813 | 0;
38
+ let t = Math.imul(state ^ state >>> 15, 1 | state);
39
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
40
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
41
+ };
42
+ }
43
+
44
+ // src/types.ts
45
+ var TimeoutError = class extends Error {
46
+ code = "ETIMEDOUT";
47
+ constructor(message = "Request timed out") {
48
+ super(message);
49
+ this.name = "TimeoutError";
50
+ }
51
+ };
52
+ var AlreadyEnabledError = class extends Error {
53
+ code = "ALREADY_ENABLED";
54
+ constructor(message = "req-race chaos is already enabled on this target. Call disable() first.") {
55
+ super(message);
56
+ this.name = "AlreadyEnabledError";
57
+ }
58
+ };
59
+ var ChaosCallbackError = class extends Error {
60
+ code = "ERR_CHAOS_CALLBACK";
61
+ constructor(message, options) {
62
+ super(message, options);
63
+ this.name = "ChaosCallbackError";
64
+ }
65
+ };
66
+ var UnknownModeError = class extends Error {
67
+ code = "ERR_UNKNOWN_MODE";
68
+ constructor(mode) {
69
+ super(`Unknown req-race mode: "${mode}".`);
70
+ this.name = "UnknownModeError";
71
+ }
72
+ };
73
+
74
+ // src/chaos.ts
75
+ var MODES = [
76
+ "reverse-order",
77
+ "jitter",
78
+ "throttle-mutations",
79
+ "timeout",
80
+ "slow",
81
+ "flaky",
82
+ "error-status",
83
+ "rate-limit",
84
+ "offline",
85
+ "hang",
86
+ "abort-mid-body",
87
+ "shuffle",
88
+ "custom"
89
+ ];
90
+ var DEFAULT_OPTIONS = {
91
+ mode: "reverse-order",
92
+ delayMs: 1e3,
93
+ timeoutMs: 1500,
94
+ minDelayMs: 100,
95
+ maxDelayMs: 900,
96
+ doubleSubmitWindowMs: 500,
97
+ errorRate: 0.3,
98
+ status: 503,
99
+ statusText: "Service Unavailable",
100
+ body: "",
101
+ headers: {},
102
+ rateLimitAfter: 3,
103
+ rateLimitWindowMs: 1e3,
104
+ retryAfterSeconds: 1,
105
+ partialBytes: 16,
106
+ shuffleWindowMs: 300,
107
+ maxLogs: 1e3
108
+ };
109
+ var MUTATION_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
110
+ var ACTIVE_TARGETS = /* @__PURE__ */ new WeakSet();
111
+ var DEFAULT_CLOCK = {
112
+ now: () => Date.now(),
113
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
114
+ clearTimeout: (id) => globalThis.clearTimeout(id)
115
+ };
116
+ function sleepWithClock(ms, clock, signal) {
117
+ return new Promise((resolve, reject) => {
118
+ if (signal?.aborted) {
119
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
120
+ return;
121
+ }
122
+ const timer = clock.setTimeout(() => {
123
+ signal?.removeEventListener("abort", onAbort);
124
+ resolve();
125
+ }, ms);
126
+ function onAbort() {
127
+ clock.clearTimeout(timer);
128
+ reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
129
+ }
130
+ signal?.addEventListener("abort", onAbort, { once: true });
131
+ });
132
+ }
133
+ function hangUntilAbort(signal) {
134
+ return new Promise((_resolve, reject) => {
135
+ if (signal?.aborted) {
136
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
137
+ return;
138
+ }
139
+ signal?.addEventListener(
140
+ "abort",
141
+ () => reject(signal.reason ?? new DOMException("Aborted", "AbortError")),
142
+ { once: true }
143
+ );
144
+ });
145
+ }
146
+ function defaultNormalizeKey(url, method) {
147
+ try {
148
+ const parsed = new URL(url, "http://localhost");
149
+ return `${method}:${parsed.pathname}`;
150
+ } catch {
151
+ return `${method}:${String(url).split("#")[0]?.split("?")[0] ?? ""}`;
152
+ }
153
+ }
154
+ function extractUrl(input) {
155
+ if (typeof input === "string") return input;
156
+ if (input instanceof URL) return input.href;
157
+ if (input && typeof input.url === "string") return input.url;
158
+ return String(input);
159
+ }
160
+ function matchesUrl(url, pattern) {
161
+ if (!pattern) return true;
162
+ if (typeof pattern === "function") return pattern(url);
163
+ if (pattern instanceof RegExp) return pattern.test(url);
164
+ return url.includes(String(pattern));
165
+ }
166
+ function validateModes(modeInput) {
167
+ const list = Array.isArray(modeInput) ? modeInput : [modeInput];
168
+ for (const m of list) {
169
+ if (!MODES.includes(m)) {
170
+ throw new UnknownModeError(String(m));
171
+ }
172
+ }
173
+ return list;
174
+ }
175
+ function makePartialBodyResponse(original, partialBytes) {
176
+ const stream = new ReadableStream({
177
+ async start(controller) {
178
+ try {
179
+ const text = await original.text();
180
+ const encoded = new TextEncoder().encode(text);
181
+ controller.enqueue(encoded.slice(0, Math.max(0, partialBytes)));
182
+ controller.error(new TypeError("network error mid-body"));
183
+ } catch (err) {
184
+ controller.error(err);
185
+ }
186
+ }
187
+ });
188
+ return new Response(stream, {
189
+ status: original.status,
190
+ statusText: original.statusText,
191
+ headers: original.headers
192
+ });
193
+ }
194
+ function enableFetchRaceChaos(options = {}) {
195
+ const target = options.target ?? (typeof globalThis !== "undefined" ? globalThis : null);
196
+ if (!target || typeof target.fetch !== "function") {
197
+ throw new Error("enableFetchRaceChaos requires a target with a fetch() function.");
198
+ }
199
+ if (ACTIVE_TARGETS.has(target)) {
200
+ throw new AlreadyEnabledError();
201
+ }
202
+ let activeModes = validateModes(options.mode ?? DEFAULT_OPTIONS.mode);
203
+ let offlineForced = false;
204
+ let enabled = true;
205
+ const seed = options.seed ?? Math.floor(Math.random() * 1e9);
206
+ const rand = createSeededRandom(seed);
207
+ const clock = options.clock ?? DEFAULT_CLOCK;
208
+ const delayMs = options.delayMs ?? DEFAULT_OPTIONS.delayMs;
209
+ const timeoutMs = options.timeoutMs ?? DEFAULT_OPTIONS.timeoutMs;
210
+ const minDelayMs = options.minDelayMs ?? DEFAULT_OPTIONS.minDelayMs;
211
+ const maxDelayMs = options.maxDelayMs ?? DEFAULT_OPTIONS.maxDelayMs;
212
+ const doubleSubmitWindowMs = options.doubleSubmitWindowMs ?? DEFAULT_OPTIONS.doubleSubmitWindowMs;
213
+ const errorRate = options.errorRate ?? DEFAULT_OPTIONS.errorRate;
214
+ const maxLogs = options.maxLogs ?? DEFAULT_OPTIONS.maxLogs;
215
+ const normalizeKey = options.normalizeKey ?? defaultNormalizeKey;
216
+ const rawOriginalFetch = target.fetch;
217
+ const originalFetch = rawOriginalFetch.bind(target);
218
+ const inFlightByKey = /* @__PURE__ */ new Map();
219
+ const recentMutations = /* @__PURE__ */ new Map();
220
+ const rateLimitWindows = /* @__PURE__ */ new Map();
221
+ const logs = [];
222
+ const stats = {
223
+ totalRequests: 0,
224
+ reorderedResponses: 0,
225
+ abortedCount: 0,
226
+ unabortedStaleCount: 0,
227
+ duplicateMutations: 0,
228
+ timeouts: 0,
229
+ failedRequests: 0,
230
+ injectedErrors: 0,
231
+ rateLimited: 0,
232
+ hungRequests: 0,
233
+ partialBodies: 0,
234
+ retriedCount: 0,
235
+ deduplicatedCount: 0,
236
+ maxConcurrentPerKey: {},
237
+ byKey: {},
238
+ seed
239
+ };
240
+ let seq = 0;
241
+ ACTIVE_TARGETS.add(target);
242
+ const pushLog = (entry) => {
243
+ logs.push(entry);
244
+ if (logs.length > maxLogs) {
245
+ logs.shift();
246
+ }
247
+ };
248
+ const nav = target.navigator;
249
+ const rawSendBeacon = nav?.sendBeacon;
250
+ if (options.patchBeacon && nav && typeof rawSendBeacon === "function") {
251
+ nav.sendBeacon = function patchedSendBeacon(url, data) {
252
+ const key = normalizeKey(url, "BEACON");
253
+ const now = clock.now();
254
+ stats.totalRequests++;
255
+ const prev = recentMutations.get(key);
256
+ if (prev && now - prev <= doubleSubmitWindowMs) {
257
+ stats.duplicateMutations++;
258
+ }
259
+ recentMutations.set(key, now);
260
+ return rawSendBeacon.call(nav, url, data);
261
+ };
262
+ }
263
+ target.fetch = async function reqRaceFetch(input, init = {}) {
264
+ const url = extractUrl(input);
265
+ const method = (init?.method || (typeof input === "object" && "method" in input ? input.method : void 0) || "GET").toUpperCase();
266
+ if (!matchesUrl(url, options.urlPattern)) {
267
+ return originalFetch(input, init);
268
+ }
269
+ if (options.methods && !options.methods.map((m) => m.toUpperCase()).includes(method)) {
270
+ return originalFetch(input, init);
271
+ }
272
+ const matchedRule = options.rules?.find(
273
+ (r) => matchesUrl(url, r.urlPattern) && (!r.methods || r.methods.map((m) => m.toUpperCase()).includes(method))
274
+ );
275
+ const modesToRun = matchedRule ? validateModes(matchedRule.mode) : activeModes;
276
+ const effDelay = matchedRule?.delayMs ?? delayMs;
277
+ const effTimeout = matchedRule?.timeoutMs ?? timeoutMs;
278
+ const effMinDelay = matchedRule?.minDelayMs ?? minDelayMs;
279
+ const effMaxDelay = matchedRule?.maxDelayMs ?? maxDelayMs;
280
+ const effErrorRate = matchedRule?.errorRate ?? errorRate;
281
+ const id = ++seq;
282
+ const key = normalizeKey(url, method);
283
+ const startedAt = clock.now();
284
+ const signal = init?.signal || (typeof input === "object" && "signal" in input ? input.signal : void 0);
285
+ stats.totalRequests++;
286
+ const keyStat = stats.byKey[key] ??= { requests: 0, reordered: 0, unabortedStale: 0 };
287
+ keyStat.requests++;
288
+ if (MUTATION_METHODS.has(method)) {
289
+ const prevTs = recentMutations.get(key);
290
+ if (prevTs !== void 0 && startedAt - prevTs <= doubleSubmitWindowMs) {
291
+ stats.duplicateMutations++;
292
+ options.onRaceDetected?.({
293
+ type: "duplicate-mutation",
294
+ method,
295
+ key,
296
+ url,
297
+ requestId: id,
298
+ detail: `Duplicate ${method} within ${startedAt - prevTs}ms`
299
+ });
300
+ }
301
+ recentMutations.set(key, startedAt);
302
+ }
303
+ const entry = {
304
+ id,
305
+ key,
306
+ method,
307
+ url,
308
+ startedAt,
309
+ endedAt: null,
310
+ delayApplied: 0,
311
+ action: "pass",
312
+ status: null,
313
+ aborted: false,
314
+ reordered: false,
315
+ staleRisk: false,
316
+ mode: modesToRun.join("+")
317
+ };
318
+ pushLog(entry);
319
+ options.onRequest?.(entry);
320
+ const activeList = inFlightByKey.get(key) ?? [];
321
+ for (const prev of activeList) {
322
+ if (!prev.signal?.aborted && !MUTATION_METHODS.has(method)) {
323
+ prev.staleRisk = true;
324
+ stats.unabortedStaleCount++;
325
+ keyStat.unabortedStale++;
326
+ options.onRaceDetected?.({
327
+ type: "unaborted-stale",
328
+ method,
329
+ key,
330
+ url,
331
+ requestId: prev.id,
332
+ supersededBy: id,
333
+ detail: `Request #${prev.id} not aborted when #${id} started`
334
+ });
335
+ }
336
+ }
337
+ const tracker = { id, signal, staleRisk: false };
338
+ activeList.push(tracker);
339
+ inFlightByKey.set(key, activeList);
340
+ stats.maxConcurrentPerKey[key] = Math.max(
341
+ stats.maxConcurrentPerKey[key] ?? 0,
342
+ activeList.length
343
+ );
344
+ try {
345
+ if (offlineForced || modesToRun.includes("offline")) {
346
+ stats.injectedErrors++;
347
+ stats.failedRequests++;
348
+ entry.action = "offline-error";
349
+ throw new TypeError("Failed to fetch (offline)");
350
+ }
351
+ if (modesToRun.includes("hang")) {
352
+ stats.hungRequests++;
353
+ entry.action = "hang";
354
+ options.onRaceDetected?.({
355
+ type: "hang",
356
+ key,
357
+ method,
358
+ url,
359
+ requestId: id,
360
+ detail: "Request hung indefinitely"
361
+ });
362
+ await hangUntilAbort(signal);
363
+ }
364
+ if (modesToRun.includes("custom") && options.chaos) {
365
+ let decision;
366
+ try {
367
+ decision = await options.chaos(
368
+ {
369
+ method,
370
+ url,
371
+ key,
372
+ headers: {},
373
+ attempt: 1,
374
+ index: id,
375
+ indexForKey: keyStat.requests,
376
+ ...signal ? { signal } : {}
377
+ },
378
+ { random: rand, now: clock.now }
379
+ );
380
+ } catch (cbErr) {
381
+ throw new ChaosCallbackError("Chaos callback threw an error.", { cause: cbErr });
382
+ }
383
+ if (decision && "hang" in decision && decision.hang) {
384
+ stats.hungRequests++;
385
+ entry.action = "custom-hang";
386
+ await hangUntilAbort(signal);
387
+ } else if (decision && "fail" in decision) {
388
+ stats.injectedErrors++;
389
+ stats.failedRequests++;
390
+ if (decision.fail === "timeout") {
391
+ stats.timeouts++;
392
+ throw new TimeoutError();
393
+ }
394
+ if (decision.fail === "abort") {
395
+ throw new DOMException("Aborted by chaos", "AbortError");
396
+ }
397
+ throw new TypeError("Failed to fetch (custom chaos)");
398
+ } else if (decision && "respond" in decision) {
399
+ stats.injectedErrors++;
400
+ entry.status = decision.respond.status;
401
+ entry.action = "custom-respond";
402
+ return new Response(decision.respond.body ?? "", {
403
+ status: decision.respond.status,
404
+ ...decision.respond.headers ? { headers: decision.respond.headers } : {}
405
+ });
406
+ } else if (decision && "delayMs" in decision) {
407
+ entry.delayApplied += decision.delayMs;
408
+ await sleepWithClock(decision.delayMs, clock, signal);
409
+ }
410
+ }
411
+ for (const m of modesToRun) {
412
+ if (m === "timeout") {
413
+ await sleepWithClock(effTimeout, clock, signal);
414
+ stats.timeouts++;
415
+ stats.failedRequests++;
416
+ entry.action = "timeout";
417
+ options.onRaceDetected?.({
418
+ type: "timeout",
419
+ key,
420
+ method,
421
+ url,
422
+ requestId: id,
423
+ detail: `Timed out after ${effTimeout}ms`
424
+ });
425
+ throw new TimeoutError(`Request timed out after ${effTimeout}ms`);
426
+ }
427
+ if (m === "rate-limit") {
428
+ const limit = options.rateLimitAfter ?? DEFAULT_OPTIONS.rateLimitAfter;
429
+ const winMs = options.rateLimitWindowMs ?? DEFAULT_OPTIONS.rateLimitWindowMs;
430
+ const now = clock.now();
431
+ const recent = (rateLimitWindows.get(key) ?? []).filter((t) => now - t <= winMs);
432
+ recent.push(now);
433
+ rateLimitWindows.set(key, recent);
434
+ if (recent.length > limit) {
435
+ stats.rateLimited++;
436
+ stats.injectedErrors++;
437
+ entry.status = 429;
438
+ entry.action = "rate-limited";
439
+ options.onRaceDetected?.({
440
+ type: "rate-limited",
441
+ key,
442
+ method,
443
+ url,
444
+ requestId: id,
445
+ detail: "429 Too Many Requests"
446
+ });
447
+ return new Response("Too Many Requests", {
448
+ status: 429,
449
+ headers: {
450
+ "Retry-After": String(options.retryAfterSeconds ?? DEFAULT_OPTIONS.retryAfterSeconds)
451
+ }
452
+ });
453
+ }
454
+ }
455
+ if (m === "flaky" && rand() < effErrorRate) {
456
+ stats.injectedErrors++;
457
+ stats.failedRequests++;
458
+ entry.action = "flaky-error";
459
+ throw new TypeError("Failed to fetch (flaky)");
460
+ }
461
+ if (m === "error-status" && rand() < effErrorRate) {
462
+ const status = matchedRule?.status ?? options.status ?? DEFAULT_OPTIONS.status;
463
+ stats.injectedErrors++;
464
+ entry.status = status;
465
+ entry.action = "error-status";
466
+ return new Response(matchedRule?.body ?? options.body ?? "", {
467
+ status,
468
+ statusText: matchedRule?.statusText ?? options.statusText ?? DEFAULT_OPTIONS.statusText,
469
+ headers: matchedRule?.headers ?? options.headers ?? {}
470
+ });
471
+ }
472
+ if (m === "slow") {
473
+ entry.delayApplied += effDelay;
474
+ await sleepWithClock(effDelay, clock, signal);
475
+ }
476
+ if (m === "jitter") {
477
+ const span = Math.max(0, effMaxDelay - effMinDelay);
478
+ const d = Math.floor(effMinDelay + rand() * span);
479
+ entry.delayApplied += d;
480
+ await sleepWithClock(d, clock, signal);
481
+ }
482
+ if (m === "shuffle") {
483
+ const d = Math.floor(rand() * (options.shuffleWindowMs ?? DEFAULT_OPTIONS.shuffleWindowMs));
484
+ entry.delayApplied += d;
485
+ await sleepWithClock(d, clock, signal);
486
+ }
487
+ if (m === "throttle-mutations" && MUTATION_METHODS.has(method)) {
488
+ entry.delayApplied += effDelay;
489
+ await sleepWithClock(effDelay, clock, signal);
490
+ }
491
+ }
492
+ let response = await originalFetch(input, init);
493
+ if (modesToRun.includes("reverse-order")) {
494
+ const listNow = inFlightByKey.get(key) ?? [];
495
+ const hasNewer = listNow.some((item) => item.id > id);
496
+ if (hasNewer && !signal?.aborted) {
497
+ entry.delayApplied += effDelay;
498
+ entry.reordered = true;
499
+ entry.action = "reordered";
500
+ stats.reorderedResponses++;
501
+ keyStat.reordered++;
502
+ await sleepWithClock(effDelay, clock, signal);
503
+ }
504
+ }
505
+ if (modesToRun.includes("abort-mid-body")) {
506
+ stats.partialBodies++;
507
+ entry.action = "abort-mid-body";
508
+ response = makePartialBodyResponse(
509
+ response,
510
+ options.partialBytes ?? DEFAULT_OPTIONS.partialBytes
511
+ );
512
+ }
513
+ entry.status = response.status ?? 200;
514
+ entry.endedAt = clock.now();
515
+ entry.staleRisk = tracker.staleRisk;
516
+ options.onResponse?.(entry);
517
+ return response;
518
+ } catch (err) {
519
+ if (err?.name === "AbortError" || signal?.aborted) {
520
+ entry.aborted = true;
521
+ stats.abortedCount++;
522
+ } else if (entry.action === "pass") {
523
+ stats.failedRequests++;
524
+ entry.error = err?.message ?? String(err);
525
+ }
526
+ entry.endedAt = clock.now();
527
+ entry.staleRisk = tracker.staleRisk;
528
+ throw err;
529
+ } finally {
530
+ const remaining = (inFlightByKey.get(key) ?? []).filter((item) => item.id !== id);
531
+ if (remaining.length > 0) {
532
+ inFlightByKey.set(key, remaining);
533
+ } else {
534
+ inFlightByKey.delete(key);
535
+ }
536
+ }
537
+ };
538
+ return {
539
+ disable() {
540
+ if (!enabled) return;
541
+ enabled = false;
542
+ target.fetch = rawOriginalFetch;
543
+ if (options.patchBeacon && nav && rawSendBeacon) {
544
+ nav.sendBeacon = rawSendBeacon;
545
+ }
546
+ ACTIVE_TARGETS.delete(target);
547
+ },
548
+ getStats() {
549
+ return {
550
+ ...stats,
551
+ maxConcurrentPerKey: { ...stats.maxConcurrentPerKey },
552
+ byKey: { ...stats.byKey }
553
+ };
554
+ },
555
+ getLogs() {
556
+ return logs.map((l) => ({ ...l }));
557
+ },
558
+ resetStats() {
559
+ stats.totalRequests = 0;
560
+ stats.reorderedResponses = 0;
561
+ stats.abortedCount = 0;
562
+ stats.unabortedStaleCount = 0;
563
+ stats.duplicateMutations = 0;
564
+ stats.timeouts = 0;
565
+ stats.failedRequests = 0;
566
+ stats.injectedErrors = 0;
567
+ stats.rateLimited = 0;
568
+ stats.hungRequests = 0;
569
+ stats.partialBodies = 0;
570
+ stats.retriedCount = 0;
571
+ stats.deduplicatedCount = 0;
572
+ stats.maxConcurrentPerKey = {};
573
+ stats.byKey = {};
574
+ logs.length = 0;
575
+ recentMutations.clear();
576
+ rateLimitWindows.clear();
577
+ },
578
+ setOffline(offline) {
579
+ offlineForced = offline;
580
+ },
581
+ setMode(mode) {
582
+ activeModes = validateModes(mode);
583
+ },
584
+ getSeed() {
585
+ return seed;
586
+ },
587
+ isEnabled() {
588
+ return enabled;
589
+ }
590
+ };
591
+ }
592
+
593
+ // src/cypress.ts
594
+ function registerCypressRaceCommands() {
595
+ const cyGlobal = globalThis;
596
+ if (!cyGlobal.Cypress?.Commands) return;
597
+ for (const [cmd, mode] of [
598
+ ["raceStale", "reverse-order"],
599
+ ["raceDoubleSubmit", "throttle-mutations"],
600
+ ["raceOffline", "offline"],
601
+ ["raceServerError", "error-status"]
602
+ ]) {
603
+ cyGlobal.Cypress.Commands.add(cmd, (opts) => {
604
+ return cyGlobal.cy.window().then(
605
+ (win) => enableFetchRaceChaos({
606
+ target: win,
607
+ mode,
608
+ ...typeof opts === "object" && opts ? opts : {}
609
+ })
610
+ );
611
+ });
612
+ }
613
+ }
614
+ registerCypressRaceCommands();
615
+ // Annotate the CommonJS export names for ESM import in node:
616
+ 0 && (module.exports = {
617
+ registerCypressRaceCommands
618
+ });