req-race 0.1.0 → 1.0.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/bin/req-race.js CHANGED
@@ -15,8 +15,9 @@ Usage:
15
15
  npx req-race <url> [options]
16
16
 
17
17
  Options:
18
- --mode <mode> reverse-order | jitter | throttle-mutations (default: reverse-order)
18
+ --mode <mode> reverse-order | jitter | throttle-mutations | timeout (default: reverse-order)
19
19
  --delay <ms> Delay ms for reordered requests (default: 1000)
20
+ --timeout <ms> Timeout ms when using --mode timeout (default: 1500)
20
21
  --wait <ms> Wait ms after load to collect requests (default: 1500)
21
22
  --json Output machine-readable JSON
22
23
  -h, --help Show this help message
@@ -32,14 +33,29 @@ const getArgValue = (flag) => {
32
33
  const url = args.find((a) => !a.startsWith("-"));
33
34
  const mode = getArgValue("--mode") || "reverse-order";
34
35
  const delayMs = Number(getArgValue("--delay") ?? 1000);
36
+ const timeoutMs = Number(getArgValue("--timeout") ?? 1500);
35
37
  const waitMs = Number(getArgValue("--wait") ?? 1500);
36
38
  const jsonOutput = args.includes("--json");
37
39
 
40
+ const VALID_MODES = new Set(["reverse-order", "jitter", "throttle-mutations", "timeout"]);
41
+
38
42
  if (!url) {
39
43
  console.error("Error: Please provide a target URL, e.g. npx req-race http://localhost:5173");
40
44
  process.exit(1);
41
45
  }
42
46
 
47
+ if (!/^(https?|file):\/\//i.test(url)) {
48
+ console.error(`Error: Invalid URL "${url}". Expected http://, https://, or file:// URL.`);
49
+ process.exit(1);
50
+ }
51
+
52
+ if (!VALID_MODES.has(mode)) {
53
+ console.error(
54
+ `Error: Invalid --mode "${mode}". Expected one of: ${Array.from(VALID_MODES).join(", ")}.`
55
+ );
56
+ process.exit(1);
57
+ }
58
+
43
59
  let playwright;
44
60
  try {
45
61
  playwright = await import("playwright");
@@ -65,7 +81,7 @@ try {
65
81
  const enable = factory();
66
82
  window.__reqRace = enable(opts);
67
83
  },
68
- { source: coreSource, opts: { mode, delayMs } }
84
+ { source: coreSource, opts: { mode, delayMs, timeoutMs } }
69
85
  );
70
86
 
71
87
  await page.goto(url, { waitUntil: "networkidle" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "req-race",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "Automated stale-fetch race condition, out-of-order response chaos, and double-submit mutation tester for browsers, Playwright, and CI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type ChaosMode = "reverse-order" | "jitter" | "throttle-mutations";
1
+ export type ChaosMode = "reverse-order" | "jitter" | "throttle-mutations" | "timeout";
2
2
 
3
3
  export interface RaceStats {
4
4
  totalRequests: number;
@@ -6,6 +6,7 @@ export interface RaceStats {
6
6
  abortedCount: number;
7
7
  unabortedStaleCount: number;
8
8
  duplicateMutations: number;
9
+ timeouts: number;
9
10
  }
10
11
 
11
12
  export interface RaceLogEntry {
@@ -24,6 +25,7 @@ export interface RaceChaosOptions {
24
25
  target?: { fetch: typeof fetch };
25
26
  mode?: ChaosMode;
26
27
  delayMs?: number;
28
+ timeoutMs?: number;
27
29
  minDelayMs?: number;
28
30
  maxDelayMs?: number;
29
31
  doubleSubmitWindowMs?: number;
@@ -39,9 +41,16 @@ export interface RaceChaosController {
39
41
  resetStats: () => void;
40
42
  }
41
43
 
44
+ export interface RaceSafeFetchOptions {
45
+ normalizeKey?: (url: string, method: string) => string;
46
+ dedupeMutations?: boolean;
47
+ timeoutMs?: number;
48
+ retries?: number;
49
+ }
50
+
42
51
  export function enableFetchRaceChaos(options?: RaceChaosOptions): RaceChaosController;
43
52
  export function createRaceSafeFetch(
44
53
  fetchImpl?: typeof fetch,
45
- normalizeKey?: (url: string, method: string) => string
54
+ optionsOrNormalizeKey?: ((url: string, method: string) => string) | RaceSafeFetchOptions
46
55
  ): typeof fetch;
47
56
  export function formatRaceReport(stats: RaceStats): string;
package/src/index.js CHANGED
@@ -48,6 +48,7 @@ export function enableFetchRaceChaos(options = {}) {
48
48
  target = typeof globalThis !== "undefined" ? globalThis : null,
49
49
  mode = "reverse-order",
50
50
  delayMs = 1000,
51
+ timeoutMs = 1500,
51
52
  minDelayMs = 100,
52
53
  maxDelayMs = 900,
53
54
  doubleSubmitWindowMs = 500,
@@ -72,6 +73,7 @@ export function enableFetchRaceChaos(options = {}) {
72
73
  abortedCount: 0,
73
74
  unabortedStaleCount: 0,
74
75
  duplicateMutations: 0,
76
+ timeouts: 0,
75
77
  };
76
78
 
77
79
  let seq = 0;
@@ -154,6 +156,13 @@ export function enableFetchRaceChaos(options = {}) {
154
156
  }
155
157
 
156
158
  try {
159
+ if (mode === "timeout") {
160
+ await sleep(timeoutMs, signal);
161
+ stats.timeouts++;
162
+ onRaceDetected?.({ type: "timeout", method, key, url, timeoutMs });
163
+ throw new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError");
164
+ }
165
+
157
166
  const response = await originalFetch(input, init);
158
167
 
159
168
  // In reverse-order mode, if a newer request arrived while this one was in flight,
@@ -215,6 +224,7 @@ export function enableFetchRaceChaos(options = {}) {
215
224
  stats.abortedCount = 0;
216
225
  stats.unabortedStaleCount = 0;
217
226
  stats.duplicateMutations = 0;
227
+ stats.timeouts = 0;
218
228
  logs.length = 0;
219
229
  recentMutations.clear();
220
230
  },
@@ -223,19 +233,60 @@ export function enableFetchRaceChaos(options = {}) {
223
233
 
224
234
  /**
225
235
  * Create a race-safe fetch wrapper that automatically aborts previous in-flight
226
- * GET/HEAD requests for the same normalized key.
236
+ * GET/HEAD requests for the same normalized key, and optionally deduplicates
237
+ * concurrent identical mutations (POST/PUT/PATCH/DELETE).
227
238
  * @param {typeof fetch} [fetchImpl]
228
- * @param {(url: string, method: string) => string} [normalizeKey]
239
+ * @param {((url: string, method: string) => string) | { normalizeKey?: (url: string, method: string) => string, dedupeMutations?: boolean }} [optionsOrNormalizeKey]
229
240
  */
230
241
  export function createRaceSafeFetch(
231
242
  fetchImpl = (...args) => globalThis.fetch(...args),
232
- normalizeKey = defaultNormalizeKey
243
+ optionsOrNormalizeKey = {}
233
244
  ) {
245
+ const isFn = typeof optionsOrNormalizeKey === "function";
246
+ const normalizeKey = isFn
247
+ ? optionsOrNormalizeKey
248
+ : optionsOrNormalizeKey.normalizeKey || defaultNormalizeKey;
249
+ const dedupeMutations = isFn ? false : Boolean(optionsOrNormalizeKey.dedupeMutations);
250
+ const timeoutMs = isFn ? 0 : Number(optionsOrNormalizeKey.timeoutMs || 0);
251
+ const retries = isFn ? 0 : Number(optionsOrNormalizeKey.retries || 0);
252
+
234
253
  const controllers = new Map();
254
+ const inFlightMutations = new Map();
255
+
256
+ const runWithTimeout = async (input, init, externalSignal) => {
257
+ if (!timeoutMs || timeoutMs <= 0) {
258
+ return fetchImpl(input, init);
259
+ }
260
+ const timeoutController = new AbortController();
261
+ const onExternalAbort = () => timeoutController.abort(externalSignal.reason);
262
+ externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
263
+
264
+ let timedOut = false;
265
+ const timer = setTimeout(() => {
266
+ timedOut = true;
267
+ timeoutController.abort(new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError"));
268
+ }, timeoutMs);
269
+
270
+ try {
271
+ return await fetchImpl(input, { ...init, signal: timeoutController.signal });
272
+ } catch (err) {
273
+ if (timedOut) {
274
+ throw new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError");
275
+ }
276
+ throw err;
277
+ } finally {
278
+ clearTimeout(timer);
279
+ externalSignal?.removeEventListener("abort", onExternalAbort);
280
+ }
281
+ };
235
282
 
236
283
  return async function raceSafeFetch(input, init = {}) {
237
284
  const url = extractUrl(input);
238
- const method = (init?.method || "GET").toUpperCase();
285
+ const method = (
286
+ init?.method ||
287
+ (typeof input === "object" && input?.method) ||
288
+ "GET"
289
+ ).toUpperCase();
239
290
  const key = normalizeKey(url, method);
240
291
 
241
292
  if (method === "GET" || method === "HEAD") {
@@ -247,15 +298,33 @@ export function createRaceSafeFetch(
247
298
  controllers.set(key, controller);
248
299
 
249
300
  if (init?.signal) {
250
- init.signal.addEventListener(
251
- "abort",
252
- () => controller.abort(init.signal.reason),
253
- { once: true }
254
- );
301
+ if (init.signal.aborted) {
302
+ controller.abort(init.signal.reason);
303
+ } else {
304
+ init.signal.addEventListener(
305
+ "abort",
306
+ () => controller.abort(init.signal.reason),
307
+ { once: true }
308
+ );
309
+ }
255
310
  }
256
311
 
257
312
  try {
258
- return await fetchImpl(input, { ...init, signal: controller.signal });
313
+ let attempt = 0;
314
+ while (true) {
315
+ try {
316
+ return await runWithTimeout(
317
+ input,
318
+ { ...init, signal: controller.signal },
319
+ controller.signal
320
+ );
321
+ } catch (err) {
322
+ const isUserAbort = err?.name === "AbortError" || controller.signal.aborted;
323
+ if (isUserAbort || attempt >= retries) throw err;
324
+ attempt++;
325
+ await sleep(50 * attempt, controller.signal);
326
+ }
327
+ }
259
328
  } finally {
260
329
  if (controllers.get(key) === controller) {
261
330
  controllers.delete(key);
@@ -263,7 +332,20 @@ export function createRaceSafeFetch(
263
332
  }
264
333
  }
265
334
 
266
- return fetchImpl(input, init);
335
+ if (dedupeMutations && MUTATION_METHODS.has(method)) {
336
+ const existing = inFlightMutations.get(key);
337
+ if (existing) return existing;
338
+
339
+ const promise = Promise.resolve(runWithTimeout(input, init, init?.signal)).finally(() => {
340
+ if (inFlightMutations.get(key) === promise) {
341
+ inFlightMutations.delete(key);
342
+ }
343
+ });
344
+ inFlightMutations.set(key, promise);
345
+ return promise;
346
+ }
347
+
348
+ return runWithTimeout(input, init, init?.signal);
267
349
  };
268
350
  }
269
351
 
@@ -15,8 +15,16 @@ export interface DoubleSubmitOptions {
15
15
  windowMs?: number;
16
16
  }
17
17
 
18
+ export interface LoadingHangOptions {
19
+ url: string | RegExp;
20
+ trigger: () => Promise<void>;
21
+ loadingSelector: string;
22
+ timeoutMs?: number;
23
+ }
24
+
18
25
  export function assertNoStaleRace(page: Page, options: StaleRaceOptions): Promise<void>;
19
26
  export function assertNoDoubleSubmit(
20
27
  page: Page,
21
28
  options: DoubleSubmitOptions
22
29
  ): Promise<{ mutationCount: number }>;
30
+ export function assertNoLoadingHang(page: Page, options: LoadingHangOptions): Promise<void>;
package/src/playwright.js CHANGED
@@ -41,6 +41,14 @@ export async function assertNoStaleRace(page, options) {
41
41
  }
42
42
  }
43
43
 
44
+ function globToRegex(pattern) {
45
+ if (pattern instanceof RegExp) return pattern;
46
+ const escaped = String(pattern)
47
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
48
+ .replace(/\*/g, ".*");
49
+ return new RegExp(escaped);
50
+ }
51
+
44
52
  /**
45
53
  * Rapidly double-click a button and assert that at most `maxRequests` mutation
46
54
  * requests are fired.
@@ -49,14 +57,13 @@ export async function assertNoStaleRace(page, options) {
49
57
  */
50
58
  export async function assertNoDoubleSubmit(page, options) {
51
59
  const { button, url, maxRequests = 1, windowMs = 600 } = options;
60
+ const urlRegex = globToRegex(url);
52
61
 
53
62
  let mutationCount = 0;
54
63
  const onRequest = (req) => {
55
64
  const method = req.method().toUpperCase();
56
65
  if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
57
- const reqUrl = req.url();
58
- const matches = typeof url === "string" ? reqUrl.includes(url.replace(/\*/g, "")) : url.test(reqUrl);
59
- if (matches) mutationCount++;
66
+ if (urlRegex.test(req.url())) mutationCount++;
60
67
  }
61
68
  };
62
69
 
@@ -77,3 +84,30 @@ export async function assertNoDoubleSubmit(page, options) {
77
84
  page.off("request", onRequest);
78
85
  }
79
86
  }
87
+
88
+ /**
89
+ * Abort or stall matching requests and assert the UI does not remain stuck
90
+ * in a loading state after `timeoutMs`.
91
+ * @param {import('playwright').Page} page
92
+ * @param {object} options
93
+ */
94
+ export async function assertNoLoadingHang(page, options) {
95
+ const { url, trigger, loadingSelector, timeoutMs = 1500 } = options;
96
+ const handler = async (route) => {
97
+ await route.abort("timedout");
98
+ };
99
+
100
+ await page.route(url, handler);
101
+ try {
102
+ await trigger();
103
+ await page.waitForTimeout(timeoutMs);
104
+ const stillVisible = await page.locator(loadingSelector).first().isVisible().catch(() => false);
105
+ if (stillVisible) {
106
+ throw new Error(
107
+ `Infinite loading hang detected! "${loadingSelector}" is still visible ${timeoutMs}ms after request failure.`
108
+ );
109
+ }
110
+ } finally {
111
+ await page.unroute(url, handler);
112
+ }
113
+ }