req-race 0.2.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 +87 -31
  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 -54
  41. package/src/index.js +0 -322
  42. package/src/playwright.d.ts +0 -22
  43. package/src/playwright.js +0 -79
package/package.json CHANGED
@@ -1,30 +1,86 @@
1
1
  {
2
2
  "name": "req-race",
3
- "version": "0.2.0",
4
- "description": "Automated stale-fetch race condition, out-of-order response chaos, and double-submit mutation tester for browsers, Playwright, and CI.",
3
+ "version": "1.1.0",
4
+ "description": "Automated stale-fetch race condition, out-of-order response chaos, timeout, and double-submit mutation tester for browsers, Playwright, Puppeteer, Cypress, and CI.",
5
5
  "type": "module",
6
- "main": "./src/index.js",
7
- "types": "./src/index.d.ts",
6
+ "sideEffects": false,
7
+ "main": "./dist/cjs/index.cjs",
8
+ "module": "./dist/esm/index.js",
9
+ "types": "./dist/types/index.d.ts",
8
10
  "exports": {
9
11
  ".": {
10
- "types": "./src/index.d.ts",
11
- "default": "./src/index.js"
12
+ "import": {
13
+ "types": "./dist/types/index.d.ts",
14
+ "default": "./dist/esm/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/types/index.d.cts",
18
+ "default": "./dist/cjs/index.cjs"
19
+ }
12
20
  },
13
21
  "./playwright": {
14
- "types": "./src/playwright.d.ts",
15
- "default": "./src/playwright.js"
16
- }
22
+ "import": {
23
+ "types": "./dist/types/playwright.d.ts",
24
+ "default": "./dist/esm/playwright.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/types/playwright.d.cts",
28
+ "default": "./dist/cjs/playwright.cjs"
29
+ }
30
+ },
31
+ "./puppeteer": {
32
+ "import": {
33
+ "types": "./dist/types/puppeteer.d.ts",
34
+ "default": "./dist/esm/puppeteer.js"
35
+ },
36
+ "require": {
37
+ "types": "./dist/types/puppeteer.d.cts",
38
+ "default": "./dist/cjs/puppeteer.cjs"
39
+ }
40
+ },
41
+ "./cypress": {
42
+ "import": {
43
+ "types": "./dist/types/cypress.d.ts",
44
+ "default": "./dist/esm/cypress.js"
45
+ },
46
+ "require": {
47
+ "types": "./dist/types/cypress.d.cts",
48
+ "default": "./dist/cjs/cypress.cjs"
49
+ }
50
+ },
51
+ "./browser": {
52
+ "import": {
53
+ "types": "./dist/types/browser.d.ts",
54
+ "default": "./dist/esm/browser.js"
55
+ },
56
+ "require": {
57
+ "types": "./dist/types/browser.d.cts",
58
+ "default": "./dist/cjs/browser.cjs"
59
+ },
60
+ "default": "./dist/browser/req-race.global.js"
61
+ },
62
+ "./config.schema.json": "./config.schema.json",
63
+ "./package.json": "./package.json"
17
64
  },
18
65
  "bin": {
19
66
  "req-race": "bin/req-race.js"
20
67
  },
21
68
  "files": [
22
69
  "bin",
23
- "src",
24
- "README.md"
70
+ "dist",
71
+ "config.schema.json",
72
+ "README.md",
73
+ "docs",
74
+ "CHANGELOG.md",
75
+ "LICENSE"
25
76
  ],
26
77
  "scripts": {
27
- "test": "node --test test/*.test.js"
78
+ "build": "node scripts/build.mjs",
79
+ "typecheck": "tsc --noEmit",
80
+ "test": "node --test test/*.test.js",
81
+ "test:coverage": "npx c8 --lines 100 --branches 100 --functions 100 --statements 100 node --test test/*.test.js",
82
+ "check:pkg": "npx publint --strict && npx attw --pack . --ignore-rules no-resolution",
83
+ "prepublishOnly": "npm run build && npm run typecheck && npm test"
28
84
  },
29
85
  "keywords": [
30
86
  "fetch",
@@ -34,6 +90,8 @@
34
90
  "double-submit",
35
91
  "chaos-testing",
36
92
  "playwright",
93
+ "puppeteer",
94
+ "cypress",
37
95
  "testing",
38
96
  "cli"
39
97
  ],
@@ -43,11 +101,27 @@
43
101
  "node": ">=18.0.0"
44
102
  },
45
103
  "peerDependencies": {
46
- "playwright": ">=1.40.0"
104
+ "playwright": ">=1.40.0",
105
+ "puppeteer": ">=21.0.0",
106
+ "cypress": ">=12.0.0"
47
107
  },
48
108
  "peerDependenciesMeta": {
49
109
  "playwright": {
50
110
  "optional": true
111
+ },
112
+ "puppeteer": {
113
+ "optional": true
114
+ },
115
+ "cypress": {
116
+ "optional": true
51
117
  }
118
+ },
119
+ "devDependencies": {
120
+ "@arethetypeswrong/cli": "^0.18.5",
121
+ "@types/node": "^26.6.11",
122
+ "c8": "^12.0.0",
123
+ "esbuild": "^0.28.2",
124
+ "publint": "^0.3.25",
125
+ "typescript": "^7.0.2"
52
126
  }
53
127
  }
package/src/index.d.ts DELETED
@@ -1,54 +0,0 @@
1
- export type ChaosMode = "reverse-order" | "jitter" | "throttle-mutations" | "timeout";
2
-
3
- export interface RaceStats {
4
- totalRequests: number;
5
- reorderedResponses: number;
6
- abortedCount: number;
7
- unabortedStaleCount: number;
8
- duplicateMutations: number;
9
- timeouts: number;
10
- }
11
-
12
- export interface RaceLogEntry {
13
- id: number;
14
- method: string;
15
- key: string;
16
- url: string;
17
- startedAt: number;
18
- finishedAt: number | null;
19
- aborted: boolean;
20
- delayedMs: number;
21
- staleRisk: boolean;
22
- }
23
-
24
- export interface RaceChaosOptions {
25
- target?: { fetch: typeof fetch };
26
- mode?: ChaosMode;
27
- delayMs?: number;
28
- timeoutMs?: number;
29
- minDelayMs?: number;
30
- maxDelayMs?: number;
31
- doubleSubmitWindowMs?: number;
32
- urlPattern?: string | RegExp | null;
33
- normalizeKey?: (url: string, method: string) => string;
34
- onRaceDetected?: (event: Record<string, unknown>) => void;
35
- }
36
-
37
- export interface RaceChaosController {
38
- disable: () => void;
39
- getStats: () => RaceStats;
40
- getLogs: () => RaceLogEntry[];
41
- resetStats: () => void;
42
- }
43
-
44
- export interface RaceSafeFetchOptions {
45
- normalizeKey?: (url: string, method: string) => string;
46
- dedupeMutations?: boolean;
47
- }
48
-
49
- export function enableFetchRaceChaos(options?: RaceChaosOptions): RaceChaosController;
50
- export function createRaceSafeFetch(
51
- fetchImpl?: typeof fetch,
52
- optionsOrNormalizeKey?: ((url: string, method: string) => string) | RaceSafeFetchOptions
53
- ): typeof fetch;
54
- export function formatRaceReport(stats: RaceStats): string;
package/src/index.js DELETED
@@ -1,322 +0,0 @@
1
- /**
2
- * req-race — Automated Stale-Fetch Race Condition & Double-Submit Tester.
3
- * Zero-dependency browser & Node-compatible core.
4
- */
5
-
6
- const MUTATION_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
7
-
8
- function sleep(ms, signal) {
9
- return new Promise((resolve, reject) => {
10
- if (signal?.aborted) {
11
- reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
12
- return;
13
- }
14
- const timer = setTimeout(() => {
15
- signal?.removeEventListener("abort", onAbort);
16
- resolve();
17
- }, ms);
18
- function onAbort() {
19
- clearTimeout(timer);
20
- reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
21
- }
22
- signal?.addEventListener("abort", onAbort, { once: true });
23
- });
24
- }
25
-
26
- function defaultNormalizeKey(url, method) {
27
- try {
28
- const parsed = new URL(url, "http://localhost");
29
- return `${method}:${parsed.pathname}`;
30
- } catch {
31
- return `${method}:${String(url).split("?")[0]}`;
32
- }
33
- }
34
-
35
- function extractUrl(input) {
36
- if (typeof input === "string") return input;
37
- if (input && typeof input.url === "string") return input.url;
38
- return String(input);
39
- }
40
-
41
- /**
42
- * Enable fetch race-condition chaos and telemetry on a target (defaults to globalThis.fetch).
43
- * @param {object} [options]
44
- * @returns {{ disable: () => void, getStats: () => object, getLogs: () => Array, resetStats: () => void }}
45
- */
46
- export function enableFetchRaceChaos(options = {}) {
47
- const {
48
- target = typeof globalThis !== "undefined" ? globalThis : null,
49
- mode = "reverse-order",
50
- delayMs = 1000,
51
- timeoutMs = 1500,
52
- minDelayMs = 100,
53
- maxDelayMs = 900,
54
- doubleSubmitWindowMs = 500,
55
- urlPattern = null,
56
- normalizeKey = defaultNormalizeKey,
57
- onRaceDetected = null,
58
- } = options;
59
-
60
- if (!target || typeof target.fetch !== "function") {
61
- throw new Error("enableFetchRaceChaos requires a target with a fetch() function.");
62
- }
63
-
64
- const rawOriginalFetch = target.fetch;
65
- const originalFetch = rawOriginalFetch.bind(target);
66
- const inFlightByKey = new Map();
67
- const recentMutations = new Map();
68
- const logs = [];
69
-
70
- const stats = {
71
- totalRequests: 0,
72
- reorderedResponses: 0,
73
- abortedCount: 0,
74
- unabortedStaleCount: 0,
75
- duplicateMutations: 0,
76
- timeouts: 0,
77
- };
78
-
79
- let seq = 0;
80
-
81
- const matchesPattern = (url) => {
82
- if (!urlPattern) return true;
83
- if (urlPattern instanceof RegExp) return urlPattern.test(url);
84
- return url.includes(String(urlPattern));
85
- };
86
-
87
- target.fetch = async function reqRaceFetch(input, init = {}) {
88
- const url = extractUrl(input);
89
- const method = (init?.method || input?.method || "GET").toUpperCase();
90
-
91
- if (!matchesPattern(url)) {
92
- return originalFetch(input, init);
93
- }
94
-
95
- const id = ++seq;
96
- const key = normalizeKey(url, method);
97
- const startedAt = Date.now();
98
- const signal = init?.signal || input?.signal;
99
- stats.totalRequests++;
100
-
101
- // Detect duplicate mutations within doubleSubmitWindowMs
102
- if (MUTATION_METHODS.has(method)) {
103
- const prevTs = recentMutations.get(key);
104
- if (prevTs && startedAt - prevTs <= doubleSubmitWindowMs) {
105
- stats.duplicateMutations++;
106
- onRaceDetected?.({
107
- type: "duplicate-mutation",
108
- method,
109
- key,
110
- url,
111
- deltaMs: startedAt - prevTs,
112
- });
113
- }
114
- recentMutations.set(key, startedAt);
115
- }
116
-
117
- const entry = {
118
- id,
119
- method,
120
- key,
121
- url,
122
- startedAt,
123
- finishedAt: null,
124
- aborted: false,
125
- delayedMs: 0,
126
- staleRisk: false,
127
- signal,
128
- };
129
- logs.push(entry);
130
-
131
- const activeList = inFlightByKey.get(key) || [];
132
-
133
- // If an earlier request for this key is still in flight, flag unaborted stale risk
134
- for (const prev of activeList) {
135
- if (!prev.signal?.aborted && !MUTATION_METHODS.has(method)) {
136
- prev.staleRisk = true;
137
- stats.unabortedStaleCount++;
138
- onRaceDetected?.({
139
- type: "unaborted-overlap",
140
- method,
141
- key,
142
- earlierId: prev.id,
143
- newerId: id,
144
- });
145
- }
146
- }
147
-
148
- activeList.push(entry);
149
- inFlightByKey.set(key, activeList);
150
-
151
- let appliedDelay = 0;
152
- if (mode === "jitter") {
153
- appliedDelay = Math.floor(minDelayMs + Math.random() * Math.max(0, maxDelayMs - minDelayMs));
154
- } else if (mode === "throttle-mutations" && MUTATION_METHODS.has(method)) {
155
- appliedDelay = delayMs;
156
- }
157
-
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
-
166
- const response = await originalFetch(input, init);
167
-
168
- // In reverse-order mode, if a newer request arrived while this one was in flight,
169
- // hold this earlier response so the newer one resolves first!
170
- const listNow = inFlightByKey.get(key) || [];
171
- const hasNewer = listNow.some((item) => item.id > id);
172
- if (mode === "reverse-order" && hasNewer && !signal?.aborted) {
173
- appliedDelay = delayMs;
174
- stats.reorderedResponses++;
175
- }
176
-
177
- if (appliedDelay > 0) {
178
- entry.delayedMs = appliedDelay;
179
- await sleep(appliedDelay, signal);
180
- }
181
-
182
- entry.finishedAt = Date.now();
183
- return response;
184
- } catch (err) {
185
- if (err?.name === "AbortError" || signal?.aborted) {
186
- entry.aborted = true;
187
- stats.abortedCount++;
188
- }
189
- entry.finishedAt = Date.now();
190
- throw err;
191
- } finally {
192
- const remaining = (inFlightByKey.get(key) || []).filter((item) => item.id !== id);
193
- if (remaining.length > 0) {
194
- inFlightByKey.set(key, remaining);
195
- } else {
196
- inFlightByKey.delete(key);
197
- }
198
- }
199
- };
200
-
201
- return {
202
- disable() {
203
- target.fetch = rawOriginalFetch;
204
- },
205
- getStats() {
206
- return { ...stats };
207
- },
208
- getLogs() {
209
- return logs.map((l) => ({
210
- id: l.id,
211
- method: l.method,
212
- key: l.key,
213
- url: l.url,
214
- startedAt: l.startedAt,
215
- finishedAt: l.finishedAt,
216
- aborted: l.aborted,
217
- delayedMs: l.delayedMs,
218
- staleRisk: l.staleRisk,
219
- }));
220
- },
221
- resetStats() {
222
- stats.totalRequests = 0;
223
- stats.reorderedResponses = 0;
224
- stats.abortedCount = 0;
225
- stats.unabortedStaleCount = 0;
226
- stats.duplicateMutations = 0;
227
- stats.timeouts = 0;
228
- logs.length = 0;
229
- recentMutations.clear();
230
- },
231
- };
232
- }
233
-
234
- /**
235
- * Create a race-safe fetch wrapper that automatically aborts previous in-flight
236
- * GET/HEAD requests for the same normalized key, and optionally deduplicates
237
- * concurrent identical mutations (POST/PUT/PATCH/DELETE).
238
- * @param {typeof fetch} [fetchImpl]
239
- * @param {((url: string, method: string) => string) | { normalizeKey?: (url: string, method: string) => string, dedupeMutations?: boolean }} [optionsOrNormalizeKey]
240
- */
241
- export function createRaceSafeFetch(
242
- fetchImpl = (...args) => globalThis.fetch(...args),
243
- optionsOrNormalizeKey = {}
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
-
251
- const controllers = new Map();
252
- const inFlightMutations = new Map();
253
-
254
- return async function raceSafeFetch(input, init = {}) {
255
- const url = extractUrl(input);
256
- const method = (init?.method || "GET").toUpperCase();
257
- const key = normalizeKey(url, method);
258
-
259
- if (method === "GET" || method === "HEAD") {
260
- const prev = controllers.get(key);
261
- if (prev) {
262
- prev.abort(new DOMException("Superseded by newer request", "AbortError"));
263
- }
264
- const controller = new AbortController();
265
- controllers.set(key, controller);
266
-
267
- if (init?.signal) {
268
- init.signal.addEventListener(
269
- "abort",
270
- () => controller.abort(init.signal.reason),
271
- { once: true }
272
- );
273
- }
274
-
275
- try {
276
- return await fetchImpl(input, { ...init, signal: controller.signal });
277
- } finally {
278
- if (controllers.get(key) === controller) {
279
- controllers.delete(key);
280
- }
281
- }
282
- }
283
-
284
- if (dedupeMutations && MUTATION_METHODS.has(method)) {
285
- const existing = inFlightMutations.get(key);
286
- if (existing) return existing;
287
-
288
- const promise = Promise.resolve(fetchImpl(input, init)).finally(() => {
289
- if (inFlightMutations.get(key) === promise) {
290
- inFlightMutations.delete(key);
291
- }
292
- });
293
- inFlightMutations.set(key, promise);
294
- return promise;
295
- }
296
-
297
- return fetchImpl(input, init);
298
- };
299
- }
300
-
301
- /**
302
- * Format race-chaos statistics into a readable terminal report.
303
- * @param {object} stats
304
- * @returns {string}
305
- */
306
- export function formatRaceReport(stats) {
307
- if (!stats) return "No req-race telemetry recorded.";
308
-
309
- const hasIssues = stats.unabortedStaleCount > 0 || stats.duplicateMutations > 0;
310
- const lines = [
311
- hasIssues
312
- ? `✖ req-race detected potential race conditions:`
313
- : `✔ req-race passed (${stats.totalRequests} requests monitored):`,
314
- ` ├─ Total requests: ${stats.totalRequests}`,
315
- ` ├─ Reordered responses: ${stats.reorderedResponses}`,
316
- ` ├─ Properly aborted: ${stats.abortedCount}`,
317
- ` ├─ Unaborted stale risks: ${stats.unabortedStaleCount}`,
318
- ` └─ Duplicate mutations: ${stats.duplicateMutations}`,
319
- ];
320
-
321
- return lines.join("\n");
322
- }
@@ -1,22 +0,0 @@
1
- import type { Page } from "playwright";
2
-
3
- export interface StaleRaceOptions {
4
- url: string | RegExp;
5
- trigger: () => Promise<void>;
6
- selector: string;
7
- expectedText: string;
8
- delayMs?: number;
9
- }
10
-
11
- export interface DoubleSubmitOptions {
12
- button: string;
13
- url: string | RegExp;
14
- maxRequests?: number;
15
- windowMs?: number;
16
- }
17
-
18
- export function assertNoStaleRace(page: Page, options: StaleRaceOptions): Promise<void>;
19
- export function assertNoDoubleSubmit(
20
- page: Page,
21
- options: DoubleSubmitOptions
22
- ): Promise<{ mutationCount: number }>;
package/src/playwright.js DELETED
@@ -1,79 +0,0 @@
1
- /**
2
- * Playwright helpers for req-race:
3
- * - assertNoStaleRace: reverses response order of Request #1 behind Request #2
4
- * - assertNoDoubleSubmit: rapid double-click mutation guard assertion
5
- */
6
-
7
- /**
8
- * Assert that rapid overlapping requests do not allow a delayed earlier response
9
- * to overwrite the newer UI state.
10
- * @param {import('playwright').Page} page
11
- * @param {object} options
12
- */
13
- export async function assertNoStaleRace(page, options) {
14
- const { url, trigger, selector, expectedText, delayMs = 800 } = options;
15
-
16
- let count = 0;
17
- const handler = async (route) => {
18
- count++;
19
- const current = count;
20
- const response = await route.fetch();
21
- const body = await response.body();
22
-
23
- if (current === 1) {
24
- await new Promise((r) => setTimeout(r, delayMs));
25
- }
26
- await route.fulfill({ response, body });
27
- };
28
-
29
- await page.route(url, handler);
30
- try {
31
- await trigger();
32
- await page.waitForTimeout(delayMs + 150);
33
- const actual = await page.locator(selector).textContent();
34
- if (!actual || !actual.includes(expectedText)) {
35
- throw new Error(
36
- `Stale fetch race detected! Expected "${selector}" to include "${expectedText}", but got "${actual}".`
37
- );
38
- }
39
- } finally {
40
- await page.unroute(url, handler);
41
- }
42
- }
43
-
44
- /**
45
- * Rapidly double-click a button and assert that at most `maxRequests` mutation
46
- * requests are fired.
47
- * @param {import('playwright').Page} page
48
- * @param {object} options
49
- */
50
- export async function assertNoDoubleSubmit(page, options) {
51
- const { button, url, maxRequests = 1, windowMs = 600 } = options;
52
-
53
- let mutationCount = 0;
54
- const onRequest = (req) => {
55
- const method = req.method().toUpperCase();
56
- 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++;
60
- }
61
- };
62
-
63
- page.on("request", onRequest);
64
- try {
65
- const locator = page.locator(button).first();
66
- await locator.click();
67
- await locator.click({ force: true }).catch(() => {});
68
- await page.waitForTimeout(windowMs);
69
-
70
- if (mutationCount > maxRequests) {
71
- throw new Error(
72
- `Double-submit bug detected! Clicking "${button}" twice fired ${mutationCount} mutation requests (max allowed: ${maxRequests}).`
73
- );
74
- }
75
- return { mutationCount };
76
- } finally {
77
- page.off("request", onRequest);
78
- }
79
- }