@scenarist/nextjs-adapter 0.1.7 → 0.1.8

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 (45) hide show
  1. package/README.md +335 -234
  2. package/dist/app/context.d.ts +1 -1
  3. package/dist/app/context.d.ts.map +1 -1
  4. package/dist/app/context.js +2 -2
  5. package/dist/app/endpoints.d.ts +1 -1
  6. package/dist/app/endpoints.d.ts.map +1 -1
  7. package/dist/app/endpoints.js +5 -5
  8. package/dist/app/helpers.d.ts +0 -10
  9. package/dist/app/helpers.d.ts.map +1 -1
  10. package/dist/app/helpers.js +18 -14
  11. package/dist/app/impl.d.ts +3 -68
  12. package/dist/app/impl.d.ts.map +1 -1
  13. package/dist/app/impl.js +3 -15
  14. package/dist/app/index.d.ts +7 -7
  15. package/dist/app/index.js +5 -5
  16. package/dist/app/production.d.ts +1 -1
  17. package/dist/app/production.d.ts.map +1 -1
  18. package/dist/app/production.js +2 -2
  19. package/dist/app/production.test.js +62 -62
  20. package/dist/app/setup.d.ts +2 -2
  21. package/dist/app/setup.js +1 -1
  22. package/dist/common/create-scenarist-base.d.ts +2 -2
  23. package/dist/common/create-scenarist-base.d.ts.map +1 -1
  24. package/dist/common/create-scenarist-base.js +7 -6
  25. package/dist/common/endpoint-handlers.d.ts +1 -1
  26. package/dist/common/endpoint-handlers.js +5 -5
  27. package/dist/pages/context.d.ts +2 -2
  28. package/dist/pages/context.d.ts.map +1 -1
  29. package/dist/pages/context.js +5 -5
  30. package/dist/pages/endpoints.d.ts +2 -2
  31. package/dist/pages/endpoints.d.ts.map +1 -1
  32. package/dist/pages/endpoints.js +5 -5
  33. package/dist/pages/helpers.d.ts +2 -7
  34. package/dist/pages/helpers.d.ts.map +1 -1
  35. package/dist/pages/helpers.js +16 -6
  36. package/dist/pages/impl.d.ts +3 -41
  37. package/dist/pages/impl.d.ts.map +1 -1
  38. package/dist/pages/impl.js +3 -10
  39. package/dist/pages/index.d.ts +7 -7
  40. package/dist/pages/index.js +5 -5
  41. package/dist/pages/production.d.ts +2 -2
  42. package/dist/pages/production.test.js +78 -70
  43. package/dist/pages/setup.d.ts +2 -2
  44. package/dist/pages/setup.js +1 -1
  45. package/package.json +5 -5
package/README.md CHANGED
@@ -12,23 +12,28 @@ Next.js adapter for [Scenarist](https://scenarist.io) - test different backend s
12
12
  ## What is this?
13
13
 
14
14
  **Before Scenarist:**
15
+
15
16
  ```typescript
16
17
  // Every test has fragile per-test mocking
17
18
  beforeEach(() => {
18
- server.use(
19
- http.get('/api/user', () => HttpResponse.json({ role: 'admin' }))
20
- );
19
+ server.use(http.get("/api/user", () => HttpResponse.json({ role: "admin" })));
21
20
  });
22
21
  // Repeat 100 times across test files, hope they don't conflict
23
22
  ```
24
23
 
25
24
  **With Scenarist:**
25
+
26
26
  ```typescript
27
27
  // Define scenario once
28
- const adminScenario = { id: 'admin', mocks: [/* complete backend state */] };
28
+ const adminScenario = {
29
+ id: "admin",
30
+ mocks: [
31
+ /* complete backend state */
32
+ ],
33
+ };
29
34
 
30
35
  // Use in any test with one line
31
- await setScenario('test-1', 'admin');
36
+ await setScenario("test-1", "admin");
32
37
  // Test runs with complete "admin" backend state, isolated from other tests
33
38
  ```
34
39
 
@@ -42,33 +47,33 @@ This package provides complete Next.js integration for Scenarist's scenario mana
42
47
 
43
48
  ## Quick Navigation
44
49
 
45
- | I want to... | Go to |
46
- |-------------|--------|
47
- | See what problems this solves | [What is this?](#what-is-this) |
48
- | Get started in 5 minutes | [Quick Start (5 Minutes)](#quick-start-5-minutes) |
49
- | Choose between routers | [Pages Router vs App Router](#pages-router-vs-app-router) |
50
- | Set up Pages Router | [Pages Router Setup](#pages-router-setup) |
51
- | Set up App Router | [App Router Setup](#app-router-setup) |
52
- | Switch scenarios in tests | [Use in Tests](#4-use-in-tests) |
53
- | Forward headers to external APIs | [Making External API Calls](#making-external-api-calls) |
54
- | Understand test isolation | [Test ID Isolation](#test-id-isolation) |
55
- | Reduce test boilerplate | [Common Patterns](#common-patterns) |
56
- | Debug issues | [Troubleshooting](#troubleshooting) |
57
- | See full API reference | [API Reference](#api-reference) |
58
- | Learn about advanced features | [Core Functionality Docs](../../docs/core-functionality.md) |
50
+ | I want to... | Go to |
51
+ | -------------------------------- | ----------------------------------------------------------- |
52
+ | See what problems this solves | [What is this?](#what-is-this) |
53
+ | Get started in 5 minutes | [Quick Start (5 Minutes)](#quick-start-5-minutes) |
54
+ | Choose between routers | [Pages Router vs App Router](#pages-router-vs-app-router) |
55
+ | Set up Pages Router | [Pages Router Setup](#pages-router-setup) |
56
+ | Set up App Router | [App Router Setup](#app-router-setup) |
57
+ | Switch scenarios in tests | [Use in Tests](#4-use-in-tests) |
58
+ | Forward headers to external APIs | [Making External API Calls](#making-external-api-calls) |
59
+ | Understand test isolation | [Test ID Isolation](#test-id-isolation) |
60
+ | Reduce test boilerplate | [Common Patterns](#common-patterns) |
61
+ | Debug issues | [Troubleshooting](#troubleshooting) |
62
+ | See full API reference | [API Reference](#api-reference) |
63
+ | Learn about advanced features | [Core Functionality Docs](../../docs/core-functionality.md) |
59
64
 
60
65
  ## 📖 Documentation
61
66
 
62
67
  **Full documentation at [scenarist.io](https://scenarist.io)**
63
68
 
64
- | Topic | Link |
65
- |-------|------|
66
- | **Why Scenarist?** | [scenarist.io/introduction/why-scenarist](https://scenarist.io/introduction/why-scenarist) |
67
- | **Getting Started (App Router)** | [scenarist.io/frameworks/nextjs-app-router/getting-started](https://scenarist.io/frameworks/nextjs-app-router/getting-started) |
68
- | **Getting Started (Pages Router)** | [scenarist.io/frameworks/nextjs-pages-router/getting-started](https://scenarist.io/frameworks/nextjs-pages-router/getting-started) |
69
- | **🎯 React Server Components Guide** | [scenarist.io/frameworks/nextjs-app-router/rsc-guide](https://scenarist.io/frameworks/nextjs-app-router/rsc-guide) |
70
- | **Parallel Testing** | [scenarist.io/testing/parallel-testing](https://scenarist.io/testing/parallel-testing) |
71
- | **Testing Philosophy** | [scenarist.io/concepts/philosophy](https://scenarist.io/concepts/philosophy) |
69
+ | Topic | Link |
70
+ | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
71
+ | **Why Scenarist?** | [scenarist.io/getting-started/why-scenarist](https://scenarist.io/getting-started/why-scenarist) |
72
+ | **Getting Started (App Router)** | [scenarist.io/frameworks/nextjs-app-router/getting-started](https://scenarist.io/frameworks/nextjs-app-router/getting-started) |
73
+ | **Getting Started (Pages Router)** | [scenarist.io/frameworks/nextjs-pages-router/getting-started](https://scenarist.io/frameworks/nextjs-pages-router/getting-started) |
74
+ | **🎯 React Server Components Guide** | [scenarist.io/frameworks/nextjs-app-router/rsc-guide](https://scenarist.io/frameworks/nextjs-app-router/rsc-guide) |
75
+ | **Parallel Testing** | [scenarist.io/testing/parallel-testing](https://scenarist.io/testing/parallel-testing) |
76
+ | **Testing Philosophy** | [scenarist.io/concepts/philosophy](https://scenarist.io/concepts/philosophy) |
72
77
 
73
78
  ## Core Capabilities
74
79
 
@@ -77,6 +82,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
77
82
  ### Request Matching (6 capabilities)
78
83
 
79
84
  **Body matching (partial match)** - Match requests based on request body fields
85
+
80
86
  ```typescript
81
87
  {
82
88
  method: 'POST',
@@ -87,6 +93,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
87
93
  ```
88
94
 
89
95
  **Header matching (exact match)** - Perfect for user tier testing
96
+
90
97
  ```typescript
91
98
  {
92
99
  method: 'GET',
@@ -105,6 +112,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
105
112
 
106
113
  **Single responses** - Return same response every time
107
114
  **Response sequences (ordered)** - Perfect for polling APIs
115
+
108
116
  ```typescript
109
117
  {
110
118
  method: 'GET',
@@ -127,6 +135,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
127
135
 
128
136
  **State capture from requests** - Extract values from body/headers/query
129
137
  **State injection via templates** - Inject captured state using `{{state.X}}`
138
+
130
139
  ```typescript
131
140
  // Capture from POST
132
141
  {
@@ -177,13 +186,13 @@ Test how your UI handles API errors without maintaining separate error mocks per
177
186
  ```typescript
178
187
  // Define once
179
188
  const errorScenario = {
180
- id: 'api-error',
181
- name: 'API Error',
182
- mocks: [{ method: 'GET', url: '*/api/*', response: { status: 500 } }]
189
+ id: "api-error",
190
+ name: "API Error",
191
+ mocks: [{ method: "GET", url: "*/api/*", response: { status: 500 } }],
183
192
  };
184
193
 
185
194
  // Use in many tests
186
- await setScenario('test-1', 'api-error');
195
+ await setScenario("test-1", "api-error");
187
196
  // All API calls return 500 for this test
188
197
  ```
189
198
 
@@ -193,13 +202,15 @@ Test slow API responses without actual network delays:
193
202
 
194
203
  ```typescript
195
204
  const slowScenario = {
196
- id: 'slow-api',
197
- name: 'Slow API',
198
- mocks: [{
199
- method: 'GET',
200
- url: '*/api/data',
201
- response: { status: 200, body: { data: [] }, delay: 3000 } // 3s delay
202
- }]
205
+ id: "slow-api",
206
+ name: "Slow API",
207
+ mocks: [
208
+ {
209
+ method: "GET",
210
+ url: "*/api/data",
211
+ response: { status: 200, body: { data: [] }, delay: 3000 }, // 3s delay
212
+ },
213
+ ],
203
214
  };
204
215
 
205
216
  // Perfect for testing loading spinners and skeleton screens
@@ -210,17 +221,27 @@ const slowScenario = {
210
221
  Test different user permission levels by switching scenarios:
211
222
 
212
223
  ```typescript
213
- const freeUserScenario = { id: 'free', mocks: [/* limited features */] };
214
- const premiumUserScenario = { id: 'premium', mocks: [/* all features */] };
224
+ const freeUserScenario = {
225
+ id: "free",
226
+ mocks: [
227
+ /* limited features */
228
+ ],
229
+ };
230
+ const premiumUserScenario = {
231
+ id: "premium",
232
+ mocks: [
233
+ /* all features */
234
+ ],
235
+ };
215
236
 
216
237
  // Test switches scenarios mid-suite - no app restart needed
217
- test('free user sees upgrade prompt', async () => {
218
- await setScenario('test-1', 'free');
238
+ test("free user sees upgrade prompt", async () => {
239
+ await setScenario("test-1", "free");
219
240
  // ... test free tier behavior
220
241
  });
221
242
 
222
- test('premium user sees all features', async () => {
223
- await setScenario('test-2', 'premium');
243
+ test("premium user sees all features", async () => {
244
+ await setScenario("test-2", "premium");
224
245
  // ... test premium tier behavior
225
246
  });
226
247
  ```
@@ -254,6 +275,7 @@ yarn add -D @scenarist/nextjs-adapter msw
254
275
  **Note:** All Scenarist types (`ScenaristScenario`, `ScenaristMock`, etc.) are re-exported from `@scenarist/nextjs-adapter` for convenience. You don't need to install `@scenarist/core` or `@scenarist/msw-adapter` separately - they're already included as dependencies.
255
276
 
256
277
  **Peer Dependencies:**
278
+
257
279
  - `next` ^14.0.0 || ^15.0.0
258
280
  - `msw` ^2.0.0
259
281
 
@@ -265,26 +287,33 @@ yarn add -D @scenarist/nextjs-adapter msw
265
287
 
266
288
  ```typescript
267
289
  // lib/scenarios.ts
268
- import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/nextjs-adapter';
290
+ import type {
291
+ ScenaristScenario,
292
+ ScenaristScenarios,
293
+ } from "@scenarist/nextjs-adapter";
269
294
 
270
295
  export const defaultScenario: ScenaristScenario = {
271
- id: 'default',
272
- name: 'Default',
273
- mocks: [{
274
- method: 'GET',
275
- url: 'https://api.example.com/user',
276
- response: { status: 200, body: { name: 'Default User', role: 'user' } }
277
- }]
296
+ id: "default",
297
+ name: "Default",
298
+ mocks: [
299
+ {
300
+ method: "GET",
301
+ url: "https://api.example.com/user",
302
+ response: { status: 200, body: { name: "Default User", role: "user" } },
303
+ },
304
+ ],
278
305
  };
279
306
 
280
307
  export const successScenario: ScenaristScenario = {
281
- id: 'success',
282
- name: 'API Success',
283
- mocks: [{
284
- method: 'GET',
285
- url: 'https://api.example.com/user',
286
- response: { status: 200, body: { name: 'Alice', role: 'user' } }
287
- }]
308
+ id: "success",
309
+ name: "API Success",
310
+ mocks: [
311
+ {
312
+ method: "GET",
313
+ url: "https://api.example.com/user",
314
+ response: { status: 200, body: { name: "Alice", role: "user" } },
315
+ },
316
+ ],
288
317
  };
289
318
 
290
319
  export const scenarios = {
@@ -297,16 +326,16 @@ export const scenarios = {
297
326
 
298
327
  ```typescript
299
328
  // lib/scenarist.ts
300
- import { createScenarist } from '@scenarist/nextjs-adapter/pages'; // or /app
301
- import { scenarios } from './scenarios';
329
+ import { createScenarist } from "@scenarist/nextjs-adapter/pages"; // or /app
330
+ import { scenarios } from "./scenarios";
302
331
 
303
332
  export const scenarist = createScenarist({
304
- enabled: process.env.NODE_ENV === 'test',
305
- scenarios, // All scenarios registered upfront
333
+ enabled: process.env.NODE_ENV === "test",
334
+ scenarios, // All scenarios registered upfront
306
335
  });
307
336
 
308
337
  // Start MSW in Node.js environment
309
- if (typeof window === 'undefined' && scenarist) {
338
+ if (typeof window === "undefined" && scenarist) {
310
339
  scenarist.start();
311
340
  }
312
341
  ```
@@ -332,8 +361,9 @@ if (typeof window === 'undefined' && scenarist) {
332
361
  ### 3. Create Scenario Endpoint
333
362
 
334
363
  **Pages Router:** Create `pages/api/__scenario__.ts`:
364
+
335
365
  ```typescript
336
- import { scenarist } from '@/lib/scenarist';
366
+ import { scenarist } from "@/lib/scenarist";
337
367
 
338
368
  // In production, scenarist is undefined due to conditional exports
339
369
  // When the default export is undefined, Next.js treats the route as non-existent
@@ -345,7 +375,7 @@ export default scenarist?.createScenarioEndpoint();
345
375
  > **Why the URL encoding?** Next.js App Router treats folders starting with `_` (underscore) as private folders that are excluded from routing. To create a URL route `/api/__scenario__`, we use `%5F` (URL-encoded underscore). This creates the actual endpoint at `http://localhost:3000/api/__scenario__`.
346
376
 
347
377
  ```typescript
348
- import { scenarist } from '@/lib/scenarist';
378
+ import { scenarist } from "@/lib/scenarist";
349
379
 
350
380
  // In production, scenarist is undefined due to conditional exports
351
381
  // When exports are undefined, Next.js treats the route as non-existent
@@ -358,33 +388,37 @@ export const GET = handler;
358
388
  ### 4. Use in Tests
359
389
 
360
390
  ```typescript
361
- import { scenarist } from '@/lib/scenarist';
391
+ import { scenarist } from "@/lib/scenarist";
362
392
 
363
393
  beforeAll(() => scenarist.start()); // Start MSW server
364
- afterAll(() => scenarist.stop()); // Stop MSW server
394
+ afterAll(() => scenarist.stop()); // Stop MSW server
365
395
 
366
- it('fetches user successfully', async () => {
396
+ it("fetches user successfully", async () => {
367
397
  // Set scenario for this test
368
- await fetch('http://localhost:3000/__scenario__', {
369
- method: 'POST',
370
- headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
371
- body: JSON.stringify({ scenario: 'success' })
398
+ await fetch("http://localhost:3000/__scenario__", {
399
+ method: "POST",
400
+ headers: {
401
+ "x-scenarist-test-id": "test-1",
402
+ "content-type": "application/json",
403
+ },
404
+ body: JSON.stringify({ scenario: "success" }),
372
405
  });
373
406
 
374
407
  // Make request - MSW intercepts automatically
375
- const response = await fetch('http://localhost:3000/api/user', {
376
- headers: { 'x-scenarist-test-id': 'test-1' }
408
+ const response = await fetch("http://localhost:3000/api/user", {
409
+ headers: { "x-scenarist-test-id": "test-1" },
377
410
  });
378
411
 
379
412
  expect(response.status).toBe(200);
380
413
  const user = await response.json();
381
- expect(user.name).toBe('Alice');
414
+ expect(user.name).toBe("Alice");
382
415
  });
383
416
  ```
384
417
 
385
418
  **That's it!** You've got runtime scenario switching.
386
419
 
387
420
  **Next steps:**
421
+
388
422
  - [Add more scenarios](#pages-router-setup) for different backend states
389
423
  - [Use test helpers](#pattern-1-test-helpers) to reduce boilerplate
390
424
  - [Learn about test isolation](#test-id-isolation) for parallel tests
@@ -394,18 +428,19 @@ it('fetches user successfully', async () => {
394
428
 
395
429
  ## Pages Router vs App Router
396
430
 
397
- | Aspect | Pages Router | App Router |
398
- |--------|-------------|------------|
399
- | **Import Path** | `@scenarist/nextjs-adapter/pages` | `@scenarist/nextjs-adapter/app` |
400
- | **Setup File** | `pages/api/__scenario__.ts` | `app/api/%5F%5Fscenario%5F%5F/route.ts` * |
401
- | **Scenario Endpoint** | `export default scenarist.createScenarioEndpoint()` | `const handler = scenarist.createScenarioEndpoint();`<br>`export const POST = handler;`<br>`export const GET = handler;` |
402
- | **Core Functionality** | ✅ Same scenarios, same behavior | ✅ Same scenarios, same behavior |
431
+ | Aspect | Pages Router | App Router |
432
+ | ---------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
433
+ | **Import Path** | `@scenarist/nextjs-adapter/pages` | `@scenarist/nextjs-adapter/app` |
434
+ | **Setup File** | `pages/api/__scenario__.ts` | `app/api/%5F%5Fscenario%5F%5F/route.ts` \* |
435
+ | **Scenario Endpoint** | `export default scenarist.createScenarioEndpoint()` | `const handler = scenarist.createScenarioEndpoint();`<br>`export const POST = handler;`<br>`export const GET = handler;` |
436
+ | **Core Functionality** | ✅ Same scenarios, same behavior | ✅ Same scenarios, same behavior |
403
437
 
404
438
  \* App Router uses `%5F%5Fscenario%5F%5F` (URL-encoded) because folders starting with `_` are treated as private folders in Next.js App Router. See [App Router Setup](#app-router-setup) for details.
405
439
 
406
440
  **Key Insight:** Choose based on your Next.js version - all Scenarist features work identically in both routers.
407
441
 
408
442
  **Detailed setup guides:**
443
+
409
444
  - **[Pages Router Setup](#pages-router-setup)** - Full walkthrough for Pages Router
410
445
  - **[App Router Setup](#app-router-setup)** - Full walkthrough for App Router
411
446
 
@@ -417,22 +452,22 @@ it('fetches user successfully', async () => {
417
452
 
418
453
  ```typescript
419
454
  // lib/scenarios/default.ts
420
- import type { ScenaristScenario } from '@scenarist/nextjs-adapter/pages';
455
+ import type { ScenaristScenario } from "@scenarist/nextjs-adapter/pages";
421
456
 
422
457
  export const defaultScenario: ScenaristScenario = {
423
- id: 'default',
424
- name: 'Default Scenario',
425
- description: 'Baseline responses for all APIs',
458
+ id: "default",
459
+ name: "Default Scenario",
460
+ description: "Baseline responses for all APIs",
426
461
  mocks: [
427
462
  {
428
- method: 'GET',
429
- url: 'https://api.example.com/user',
463
+ method: "GET",
464
+ url: "https://api.example.com/user",
430
465
  response: {
431
466
  status: 200,
432
467
  body: {
433
- id: '000',
434
- name: 'Default User',
435
- role: 'user',
468
+ id: "000",
469
+ name: "Default User",
470
+ role: "user",
436
471
  },
437
472
  },
438
473
  },
@@ -441,19 +476,19 @@ export const defaultScenario: ScenaristScenario = {
441
476
 
442
477
  // lib/scenarios/admin-user.ts
443
478
  export const adminUserScenario: ScenaristScenario = {
444
- id: 'admin-user',
445
- name: 'Admin User',
446
- description: 'User with admin privileges',
479
+ id: "admin-user",
480
+ name: "Admin User",
481
+ description: "User with admin privileges",
447
482
  mocks: [
448
483
  {
449
- method: 'GET',
450
- url: 'https://api.example.com/user',
484
+ method: "GET",
485
+ url: "https://api.example.com/user",
451
486
  response: {
452
487
  status: 200,
453
488
  body: {
454
- id: '123',
455
- name: 'Admin User',
456
- role: 'admin',
489
+ id: "123",
490
+ name: "Admin User",
491
+ role: "admin",
457
492
  },
458
493
  },
459
494
  },
@@ -465,17 +500,17 @@ export const adminUserScenario: ScenaristScenario = {
465
500
 
466
501
  ```typescript
467
502
  // lib/scenarist.ts
468
- import { createScenarist } from '@scenarist/nextjs-adapter/pages';
469
- import { scenarios } from './scenarios';
503
+ import { createScenarist } from "@scenarist/nextjs-adapter/pages";
504
+ import { scenarios } from "./scenarios";
470
505
 
471
506
  export const scenarist = createScenarist({
472
- enabled: process.env.NODE_ENV === 'test',
473
- scenarios, // All scenarios registered upfront
474
- strictMode: false, // Allow unmocked requests to pass through to real APIs
507
+ enabled: process.env.NODE_ENV === "test",
508
+ scenarios, // All scenarios registered upfront
509
+ strictMode: false, // Allow unmocked requests to pass through to real APIs
475
510
  });
476
511
 
477
512
  // Start MSW in Node.js environment
478
- if (typeof window === 'undefined' && scenarist) {
513
+ if (typeof window === "undefined" && scenarist) {
479
514
  scenarist.start();
480
515
  }
481
516
  ```
@@ -484,7 +519,7 @@ if (typeof window === 'undefined' && scenarist) {
484
519
 
485
520
  ```typescript
486
521
  // pages/api/__scenario__.ts
487
- import { scenarist } from '../../lib/scenarist';
522
+ import { scenarist } from "../../lib/scenarist";
488
523
 
489
524
  // In production, scenarist is undefined due to conditional exports
490
525
  // When the default export is undefined, Next.js treats the route as non-existent
@@ -497,31 +532,31 @@ This single line creates a Next.js API route that handles both GET and POST requ
497
532
 
498
533
  ```typescript
499
534
  // tests/api.test.ts
500
- import { describe, it, expect, beforeAll, afterAll } from 'vitest';
501
- import { scenarist } from '../lib/scenarist';
535
+ import { describe, it, expect, beforeAll, afterAll } from "vitest";
536
+ import { scenarist } from "../lib/scenarist";
502
537
 
503
- describe('User API', () => {
538
+ describe("User API", () => {
504
539
  beforeAll(() => scenarist.start());
505
540
  afterAll(() => scenarist.stop());
506
541
 
507
- it('should return admin user', async () => {
542
+ it("should return admin user", async () => {
508
543
  // Set scenario for this test
509
- await fetch('http://localhost:3000/__scenario__', {
510
- method: 'POST',
544
+ await fetch("http://localhost:3000/__scenario__", {
545
+ method: "POST",
511
546
  headers: {
512
- 'x-scenarist-test-id': 'admin-test',
513
- 'content-type': 'application/json',
547
+ "x-scenarist-test-id": "admin-test",
548
+ "content-type": "application/json",
514
549
  },
515
- body: JSON.stringify({ scenario: 'admin-user' }),
550
+ body: JSON.stringify({ scenario: "admin-user" }),
516
551
  });
517
552
 
518
553
  // Make request - MSW intercepts automatically
519
- const response = await fetch('http://localhost:3000/api/user', {
520
- headers: { 'x-scenarist-test-id': 'admin-test' },
554
+ const response = await fetch("http://localhost:3000/api/user", {
555
+ headers: { "x-scenarist-test-id": "admin-test" },
521
556
  });
522
557
 
523
558
  const user = await response.json();
524
- expect(user.role).toBe('admin');
559
+ expect(user.role).toBe("admin");
525
560
  });
526
561
  });
527
562
  ```
@@ -538,17 +573,17 @@ Same as Pages Router - see [Define Scenarios](#1-define-scenarios) above.
538
573
 
539
574
  ```typescript
540
575
  // lib/scenarist.ts
541
- import { createScenarist } from '@scenarist/nextjs-adapter/app';
542
- import { scenarios } from './scenarios';
576
+ import { createScenarist } from "@scenarist/nextjs-adapter/app";
577
+ import { scenarios } from "./scenarios";
543
578
 
544
579
  export const scenarist = createScenarist({
545
- enabled: process.env.NODE_ENV === 'test',
546
- scenarios, // All scenarios registered upfront
547
- strictMode: false, // Allow unmocked requests to pass through to real APIs
580
+ enabled: process.env.NODE_ENV === "test",
581
+ scenarios, // All scenarios registered upfront
582
+ strictMode: false, // Allow unmocked requests to pass through to real APIs
548
583
  });
549
584
 
550
585
  // Start MSW in Node.js environment
551
- if (typeof window === 'undefined' && scenarist) {
586
+ if (typeof window === "undefined" && scenarist) {
552
587
  scenarist.start();
553
588
  }
554
589
  ```
@@ -557,7 +592,7 @@ if (typeof window === 'undefined' && scenarist) {
557
592
 
558
593
  ```typescript
559
594
  // app/api/%5F%5Fscenario%5F%5F/route.ts
560
- import { scenarist } from '@/lib/scenarist';
595
+ import { scenarist } from "@/lib/scenarist";
561
596
 
562
597
  // In production, scenarist is undefined due to conditional exports
563
598
  // When exports are undefined, Next.js treats the route as non-existent
@@ -582,43 +617,52 @@ Same as Pages Router - see [Use in Tests](#4-use-in-tests) above. The scenario e
582
617
  Creates a Scenarist instance with everything wired automatically.
583
618
 
584
619
  **Import:**
620
+
585
621
  ```typescript
586
622
  // Pages Router
587
- import { createScenarist } from '@scenarist/nextjs-adapter/pages';
623
+ import { createScenarist } from "@scenarist/nextjs-adapter/pages";
588
624
 
589
625
  // App Router
590
- import { createScenarist } from '@scenarist/nextjs-adapter/app';
626
+ import { createScenarist } from "@scenarist/nextjs-adapter/app";
591
627
  ```
592
628
 
593
629
  **Parameters:**
630
+
594
631
  ```typescript
595
632
  type AdapterOptions<T extends ScenaristScenarios> = {
596
- enabled: boolean; // Whether mocking is enabled
597
- scenarios: T; // REQUIRED - scenarios object (all scenarios registered upfront)
598
- strictMode?: boolean; // Return 501 for unmocked requests (default: false)
633
+ enabled: boolean; // Whether mocking is enabled
634
+ scenarios: T; // REQUIRED - scenarios object (all scenarios registered upfront)
635
+ strictMode?: boolean; // Return 501 for unmocked requests (default: false)
599
636
  headers?: {
600
- testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
637
+ testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
601
638
  };
602
- defaultTestId?: string; // Default test ID (default: 'default-test')
603
- registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
604
- store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
605
- stateManager?: StateManager; // Custom state manager (default: InMemoryStateManager)
606
- sequenceTracker?: SequenceTracker; // Custom sequence tracker (default: InMemorySequenceTracker)
639
+ defaultTestId?: string; // Default test ID (default: 'default-test')
640
+ registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
641
+ store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
642
+ stateManager?: StateManager; // Custom state manager (default: InMemoryStateManager)
643
+ sequenceTracker?: SequenceTracker; // Custom sequence tracker (default: InMemorySequenceTracker)
607
644
  };
608
645
  ```
609
646
 
610
647
  **Returns:**
648
+
611
649
  ```typescript
612
650
  type Scenarist<T extends ScenaristScenarios> = {
613
- config: ScenaristConfig; // Resolved configuration (headers, etc.)
651
+ config: ScenaristConfig; // Resolved configuration (headers, etc.)
614
652
  createScenarioEndpoint: () => Handler; // Creates scenario endpoint handler
615
- switchScenario: (testId: string, scenarioId: ScenarioIds<T>, variant?: string) => ScenaristResult<void, Error>;
653
+ switchScenario: (
654
+ testId: string,
655
+ scenarioId: ScenarioIds<T>,
656
+ variant?: string,
657
+ ) => ScenaristResult<void, Error>;
616
658
  getActiveScenario: (testId: string) => ActiveScenario | undefined;
617
- getScenarioById: (scenarioId: ScenarioIds<T>) => ScenaristScenario | undefined;
659
+ getScenarioById: (
660
+ scenarioId: ScenarioIds<T>,
661
+ ) => ScenaristScenario | undefined;
618
662
  listScenarios: () => ReadonlyArray<ScenaristScenario>;
619
663
  clearScenario: (testId: string) => void;
620
- start: () => void; // Start MSW server
621
- stop: () => Promise<void>; // Stop MSW server
664
+ start: () => void; // Start MSW server
665
+ stop: () => Promise<void>; // Stop MSW server
622
666
  };
623
667
  ```
624
668
 
@@ -643,6 +687,7 @@ The endpoint handler exposes these operations:
643
687
  #### `POST /__scenario__` - Set Active Scenario
644
688
 
645
689
  **Request:**
690
+
646
691
  ```typescript
647
692
  {
648
693
  scenario: string; // Scenario ID (required)
@@ -651,6 +696,7 @@ The endpoint handler exposes these operations:
651
696
  ```
652
697
 
653
698
  **Response (200):**
699
+
654
700
  ```typescript
655
701
  {
656
702
  success: true;
@@ -661,20 +707,22 @@ The endpoint handler exposes these operations:
661
707
  ```
662
708
 
663
709
  **Example:**
710
+
664
711
  ```typescript
665
- await fetch('http://localhost:3000/__scenario__', {
666
- method: 'POST',
712
+ await fetch("http://localhost:3000/__scenario__", {
713
+ method: "POST",
667
714
  headers: {
668
- 'x-scenarist-test-id': 'test-123',
669
- 'content-type': 'application/json',
715
+ "x-scenarist-test-id": "test-123",
716
+ "content-type": "application/json",
670
717
  },
671
- body: JSON.stringify({ scenario: 'user-logged-in' }),
718
+ body: JSON.stringify({ scenario: "user-logged-in" }),
672
719
  });
673
720
  ```
674
721
 
675
722
  #### `GET /__scenario__` - Get Active Scenario
676
723
 
677
724
  **Response (200):**
725
+
678
726
  ```typescript
679
727
  {
680
728
  testId: string;
@@ -684,6 +732,7 @@ await fetch('http://localhost:3000/__scenario__', {
684
732
  ```
685
733
 
686
734
  **Response (404) - No Active Scenario:**
735
+
687
736
  ```typescript
688
737
  {
689
738
  error: "No active scenario for this test ID";
@@ -692,9 +741,10 @@ await fetch('http://localhost:3000/__scenario__', {
692
741
  ```
693
742
 
694
743
  **Example:**
744
+
695
745
  ```typescript
696
- const response = await fetch('http://localhost:3000/__scenario__', {
697
- headers: { 'x-scenarist-test-id': 'test-123' },
746
+ const response = await fetch("http://localhost:3000/__scenario__", {
747
+ headers: { "x-scenarist-test-id": "test-123" },
698
748
  });
699
749
 
700
750
  const data = await response.json();
@@ -720,6 +770,7 @@ headers: { 'x-scenarist-test-id': 'test-2' } // Uses scenario B
720
770
  ```
721
771
 
722
772
  Each test ID has completely isolated:
773
+
723
774
  - Active scenario selection
724
775
  - Sequence positions (for polling scenarios)
725
776
  - Captured state (for stateful mocks)
@@ -735,21 +786,22 @@ Each test ID has completely isolated:
735
786
  Use the safe helper functions provided by the adapter:
736
787
 
737
788
  **Pages Router:**
789
+
738
790
  ```typescript
739
791
  // pages/api/products.ts
740
- import type { NextApiRequest, NextApiResponse } from 'next';
741
- import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
792
+ import type { NextApiRequest, NextApiResponse } from "next";
793
+ import { getScenaristHeaders } from "@scenarist/nextjs-adapter/pages";
742
794
 
743
795
  export default async function handler(
744
796
  req: NextApiRequest,
745
- res: NextApiResponse
797
+ res: NextApiResponse,
746
798
  ) {
747
799
  // Fetch from external API with Scenarist headers forwarded
748
- const response = await fetch('http://external-api.com/products', {
800
+ const response = await fetch("http://external-api.com/products", {
749
801
  headers: {
750
- ...getScenaristHeaders(req), // ✅ Scenarist infrastructure headers
751
- 'content-type': 'application/json', // ✅ Your application headers
752
- 'x-user-tier': req.headers['x-user-tier'], // ✅ Other app-specific headers
802
+ ...getScenaristHeaders(req), // ✅ Scenarist infrastructure headers
803
+ "content-type": "application/json", // ✅ Your application headers
804
+ "x-user-tier": req.headers["x-user-tier"], // ✅ Other app-specific headers
753
805
  },
754
806
  });
755
807
 
@@ -759,15 +811,16 @@ export default async function handler(
759
811
  ```
760
812
 
761
813
  **App Router Route Handlers:**
814
+
762
815
  ```typescript
763
816
  // app/api/products/route.ts
764
- import { getScenaristHeaders } from '@scenarist/nextjs-adapter/app';
817
+ import { getScenaristHeaders } from "@scenarist/nextjs-adapter/app";
765
818
 
766
819
  export async function GET(request: Request) {
767
- const response = await fetch('http://external-api.com/products', {
820
+ const response = await fetch("http://external-api.com/products", {
768
821
  headers: {
769
822
  ...getScenaristHeaders(request),
770
- 'content-type': 'application/json',
823
+ "content-type": "application/json",
771
824
  },
772
825
  });
773
826
 
@@ -777,6 +830,7 @@ export async function GET(request: Request) {
777
830
  ```
778
831
 
779
832
  **App Router Server Components:**
833
+
780
834
  ```typescript
781
835
  // app/products/page.tsx
782
836
  import { headers } from 'next/headers';
@@ -799,16 +853,19 @@ export default async function ProductsPage() {
799
853
  ```
800
854
 
801
855
  **What these helpers do:**
856
+
802
857
  - Extract test ID from request headers (`x-scenarist-test-id` by default)
803
858
  - Respect your configured `testIdHeaderName` and `defaultTestId`
804
859
  - Return object with Scenarist headers ready to spread
805
860
  - Safe to use in production (return empty object when scenarist is undefined)
806
861
 
807
862
  **When to use which helper:**
863
+
808
864
  - **`getScenaristHeaders(request | req)`** - Route Handlers (Request object) or Pages Router API routes (NextApiRequest)
809
865
  - **`getScenaristHeadersFromReadonlyHeaders(headersList)`** - App Router Server Components (ReadonlyHeaders from `headers()`)
810
866
 
811
867
  **Key Distinction:**
868
+
812
869
  - **Scenarist headers** (`x-scenarist-test-id`) - Infrastructure for test isolation
813
870
  - **Application headers** (`x-user-tier`, `content-type`) - Your app's business logic
814
871
 
@@ -821,12 +878,14 @@ Only Scenarist headers need forwarding via helper functions. Your application he
821
878
  `createScenarist()` automatically wires MSW for request interception. You never see MSW code directly.
822
879
 
823
880
  **What it does:**
881
+
824
882
  1. Creates MSW server with dynamic handler
825
883
  2. Extracts test ID from request headers
826
884
  3. Looks up active scenario for that test ID
827
885
  4. Returns mocked responses based on scenario
828
886
 
829
887
  **Next.js-specific details:**
888
+
830
889
  - Pages Router: Uses Next.js API routes
831
890
  - App Router: Uses Web standard Request/Response
832
891
  - Both: Full test ID isolation via headers
@@ -838,20 +897,20 @@ Active scenario mocks take precedence; unmocked endpoints fall back to default s
838
897
  ```typescript
839
898
  // Default covers all endpoints
840
899
  const defaultScenario = {
841
- id: 'default',
900
+ id: "default",
842
901
  mocks: [
843
- { method: 'GET', url: '*/api/users', response: { status: 200, body: [] } },
844
- { method: 'GET', url: '*/api/orders', response: { status: 200, body: [] } },
845
- ]
902
+ { method: "GET", url: "*/api/users", response: { status: 200, body: [] } },
903
+ { method: "GET", url: "*/api/orders", response: { status: 200, body: [] } },
904
+ ],
846
905
  };
847
906
 
848
907
  // Test scenario overrides only specific endpoints
849
908
  const errorScenario = {
850
- id: 'error',
909
+ id: "error",
851
910
  mocks: [
852
- { method: 'GET', url: '*/api/users', response: { status: 500 } }
911
+ { method: "GET", url: "*/api/users", response: { status: 500 } },
853
912
  // Orders uses default scenario
854
- ]
913
+ ],
855
914
  };
856
915
  ```
857
916
 
@@ -865,18 +924,21 @@ TypeScript automatically infers scenario names from your scenarios object, provi
865
924
 
866
925
  ```typescript
867
926
  // lib/scenarios.ts
868
- import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/nextjs-adapter/pages';
927
+ import type {
928
+ ScenaristScenario,
929
+ ScenaristScenarios,
930
+ } from "@scenarist/nextjs-adapter/pages";
869
931
 
870
932
  export const scenarios = {
871
- default: { id: 'default', name: 'Default', mocks: [] },
872
- success: { id: 'success', name: 'Success', mocks: [] },
873
- error: { id: 'error', name: 'Error', mocks: [] },
874
- timeout: { id: 'timeout', name: 'Timeout', mocks: [] },
933
+ default: { id: "default", name: "Default", mocks: [] },
934
+ success: { id: "success", name: "Success", mocks: [] },
935
+ error: { id: "error", name: "Error", mocks: [] },
936
+ timeout: { id: "timeout", name: "Timeout", mocks: [] },
875
937
  } as const satisfies ScenaristScenarios;
876
938
 
877
939
  // lib/scenarist.ts
878
- import { createScenarist } from '@scenarist/nextjs-adapter/pages';
879
- import { scenarios } from './scenarios';
940
+ import { createScenarist } from "@scenarist/nextjs-adapter/pages";
941
+ import { scenarios } from "./scenarios";
880
942
 
881
943
  export const scenarist = createScenarist({
882
944
  enabled: true,
@@ -888,12 +950,12 @@ export const scenarist = createScenarist({
888
950
 
889
951
  ```typescript
890
952
  // ✅ Valid - TypeScript knows about these scenario IDs
891
- scenarist.switchScenario('test-123', 'success');
892
- scenarist.switchScenario('test-123', 'error');
893
- scenarist.switchScenario('test-123', 'timeout');
953
+ scenarist.switchScenario("test-123", "success");
954
+ scenarist.switchScenario("test-123", "error");
955
+ scenarist.switchScenario("test-123", "timeout");
894
956
 
895
957
  // ❌ TypeScript error - 'invalid-name' is not a valid scenario ID
896
- scenarist.switchScenario('test-123', 'invalid-name');
958
+ scenarist.switchScenario("test-123", "invalid-name");
897
959
  // ^^^^^^^^^^^^^^
898
960
  // Argument of type '"invalid-name"' is not assignable to parameter of type
899
961
  // '"default" | "success" | "error" | "timeout"'
@@ -903,24 +965,31 @@ scenarist.switchScenario('test-123', 'invalid-name');
903
965
 
904
966
  ```typescript
905
967
  // tests.ts
906
- import { scenarios } from './scenarios';
968
+ import { scenarios } from "./scenarios";
907
969
 
908
970
  // ✅ Type-safe scenario switching
909
- await fetch('http://localhost:3000/__scenario__', {
910
- method: 'POST',
911
- headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
912
- body: JSON.stringify({ scenario: 'success' }), // ✅ Autocomplete works!
971
+ await fetch("http://localhost:3000/__scenario__", {
972
+ method: "POST",
973
+ headers: {
974
+ "x-scenarist-test-id": "test-1",
975
+ "content-type": "application/json",
976
+ },
977
+ body: JSON.stringify({ scenario: "success" }), // ✅ Autocomplete works!
913
978
  });
914
979
 
915
980
  // Or reference by object key for refactor-safety
916
- await fetch('http://localhost:3000/__scenario__', {
917
- method: 'POST',
918
- headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
981
+ await fetch("http://localhost:3000/__scenario__", {
982
+ method: "POST",
983
+ headers: {
984
+ "x-scenarist-test-id": "test-1",
985
+ "content-type": "application/json",
986
+ },
919
987
  body: JSON.stringify({ scenario: scenarios.success.id }), // ✅ Even safer!
920
988
  });
921
989
  ```
922
990
 
923
991
  **What you get:**
992
+
924
993
  - ✅ IDE autocomplete for all scenario names
925
994
  - ✅ Compile-time errors for typos (catch bugs before runtime)
926
995
  - ✅ Refactor-safe (rename scenarios and all usages update)
@@ -935,39 +1004,48 @@ Create helper functions to reduce boilerplate:
935
1004
 
936
1005
  ```typescript
937
1006
  // tests/helpers.ts
938
- const API_BASE = 'http://localhost:3000';
1007
+ const API_BASE = "http://localhost:3000";
939
1008
 
940
- export const setScenario = async (testId: string, scenario: string, variant?: string) => {
1009
+ export const setScenario = async (
1010
+ testId: string,
1011
+ scenario: string,
1012
+ variant?: string,
1013
+ ) => {
941
1014
  await fetch(`${API_BASE}/__scenario__`, {
942
- method: 'POST',
1015
+ method: "POST",
943
1016
  headers: {
944
- 'x-scenarist-test-id': testId,
945
- 'content-type': 'application/json',
1017
+ "x-scenarist-test-id": testId,
1018
+ "content-type": "application/json",
946
1019
  },
947
1020
  body: JSON.stringify({ scenario, variant }),
948
1021
  });
949
1022
  };
950
1023
 
951
- export const makeRequest = (testId: string, path: string, options?: RequestInit) => {
1024
+ export const makeRequest = (
1025
+ testId: string,
1026
+ path: string,
1027
+ options?: RequestInit,
1028
+ ) => {
952
1029
  return fetch(`${API_BASE}${path}`, {
953
1030
  ...options,
954
1031
  headers: {
955
1032
  ...options?.headers,
956
- 'x-scenarist-test-id': testId,
1033
+ "x-scenarist-test-id": testId,
957
1034
  },
958
1035
  });
959
1036
  };
960
1037
  ```
961
1038
 
962
1039
  **Usage:**
1040
+
963
1041
  ```typescript
964
- import { setScenario, makeRequest } from './helpers';
1042
+ import { setScenario, makeRequest } from "./helpers";
965
1043
 
966
- test('payment flow', async () => {
967
- const testId = 'payment-test';
968
- await setScenario(testId, 'payment-success');
1044
+ test("payment flow", async () => {
1045
+ const testId = "payment-test";
1046
+ await setScenario(testId, "payment-success");
969
1047
 
970
- const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
1048
+ const response = await makeRequest(testId, "/api/charge", { method: "POST" });
971
1049
  expect(response.status).toBe(200);
972
1050
  });
973
1051
  ```
@@ -977,25 +1055,29 @@ test('payment flow', async () => {
977
1055
  Generate unique test IDs automatically using a factory function:
978
1056
 
979
1057
  ```typescript
980
- import { randomUUID } from 'crypto';
1058
+ import { randomUUID } from "crypto";
981
1059
 
982
- describe('API Tests', () => {
1060
+ describe("API Tests", () => {
983
1061
  // Factory function - no shared mutable state
984
1062
  const createTestId = () => randomUUID();
985
1063
 
986
- it('should process payment', async () => {
1064
+ it("should process payment", async () => {
987
1065
  const testId = createTestId(); // Fresh ID per test
988
1066
 
989
- await setScenario(testId, 'payment-success');
990
- const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
1067
+ await setScenario(testId, "payment-success");
1068
+ const response = await makeRequest(testId, "/api/charge", {
1069
+ method: "POST",
1070
+ });
991
1071
  expect(response.status).toBe(200);
992
1072
  });
993
1073
 
994
- it('should handle payment decline', async () => {
1074
+ it("should handle payment decline", async () => {
995
1075
  const testId = createTestId(); // Independent state
996
1076
 
997
- await setScenario(testId, 'payment-declined');
998
- const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
1077
+ await setScenario(testId, "payment-declined");
1078
+ const response = await makeRequest(testId, "/api/charge", {
1079
+ method: "POST",
1080
+ });
999
1081
  expect(response.status).toBe(402);
1000
1082
  });
1001
1083
  });
@@ -1013,7 +1095,8 @@ describe('API Tests', () => {
1013
1095
  // lib/scenarist.ts
1014
1096
  // ✅ CORRECT - Only enabled in safe environments
1015
1097
  const scenarist = createScenarist({
1016
- enabled: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test',
1098
+ enabled:
1099
+ process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test",
1017
1100
  scenarios,
1018
1101
  strictMode: false,
1019
1102
  });
@@ -1026,6 +1109,7 @@ const scenarist = createScenarist({
1026
1109
  ```
1027
1110
 
1028
1111
  **Production checklist:**
1112
+
1029
1113
  - ✅ `enabled` is conditional (never hardcoded `true`)
1030
1114
  - ✅ Environment checks use `process.env.NODE_ENV`
1031
1115
  - ✅ `/__scenario__` endpoints not exposed in production builds
@@ -1049,21 +1133,22 @@ curl http://localhost:3000/__scenario__
1049
1133
  ```typescript
1050
1134
  // Test-only
1051
1135
  const scenarist = createScenarist({
1052
- enabled: process.env.NODE_ENV === 'test',
1136
+ enabled: process.env.NODE_ENV === "test",
1053
1137
  scenarios,
1054
1138
  strictMode: true, // Fail if any unmocked request
1055
1139
  });
1056
1140
 
1057
1141
  // Development and test
1058
1142
  const scenarist = createScenarist({
1059
- enabled: process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development',
1143
+ enabled:
1144
+ process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development",
1060
1145
  scenarios,
1061
1146
  strictMode: false, // Allow passthrough to real APIs
1062
1147
  });
1063
1148
 
1064
1149
  // Opt-in with environment variable
1065
1150
  const scenarist = createScenarist({
1066
- enabled: process.env.ENABLE_MOCKING === 'true',
1151
+ enabled: process.env.ENABLE_MOCKING === "true",
1067
1152
  scenarios,
1068
1153
  strictMode: false,
1069
1154
  });
@@ -1074,12 +1159,14 @@ const scenarist = createScenarist({
1074
1159
  Controls behavior when no mock matches a request.
1075
1160
 
1076
1161
  **`strictMode: false` (recommended for development):**
1162
+
1077
1163
  - Unmocked requests pass through to real APIs
1078
1164
  - Useful when only mocking specific endpoints
1079
1165
  - Default scenario provides fallback for common endpoints
1080
1166
  - Best for development where you want partial mocking
1081
1167
 
1082
1168
  **`strictMode: true` (recommended for tests):**
1169
+
1083
1170
  - Unmocked requests return 501 Not Implemented
1084
1171
  - Ensures tests don't accidentally hit real APIs
1085
1172
  - Catches missing mocks early in test development
@@ -1094,7 +1181,7 @@ const minimalScenarios = {
1094
1181
  } as const satisfies ScenaristScenarios;
1095
1182
 
1096
1183
  const scenarist = createScenarist({
1097
- enabled: process.env.NODE_ENV === 'development',
1184
+ enabled: process.env.NODE_ENV === "development",
1098
1185
  scenarios: minimalScenarios,
1099
1186
  strictMode: false, // Let unmocked APIs pass through to real services
1100
1187
  });
@@ -1105,18 +1192,20 @@ const testScenarios = {
1105
1192
  } as const satisfies ScenaristScenarios;
1106
1193
 
1107
1194
  const scenarist = createScenarist({
1108
- enabled: process.env.NODE_ENV === 'test',
1195
+ enabled: process.env.NODE_ENV === "test",
1109
1196
  scenarios: testScenarios,
1110
1197
  strictMode: true, // Fail loudly if any endpoint isn't mocked
1111
1198
  });
1112
1199
  ```
1113
1200
 
1114
1201
  **When strictMode is true:**
1202
+
1115
1203
  - Request for mocked endpoint → Returns defined mock response ✅
1116
1204
  - Request for unmocked endpoint → Returns 501 Not Implemented ❌
1117
1205
  - Easy to spot missing mocks during test development
1118
1206
 
1119
1207
  **When strictMode is false:**
1208
+
1120
1209
  - Request for mocked endpoint → Returns defined mock response ✅
1121
1210
  - Request for unmocked endpoint → Passes through to real API 🌐
1122
1211
  - Useful for incremental mocking in development
@@ -1128,7 +1217,7 @@ const scenarist = createScenarist({
1128
1217
  enabled: true,
1129
1218
  scenarios,
1130
1219
  headers: {
1131
- testId: 'x-my-test-id',
1220
+ testId: "x-my-test-id",
1132
1221
  },
1133
1222
  });
1134
1223
  ```
@@ -1142,8 +1231,8 @@ const scenarist = createScenarist({
1142
1231
  **Solution:** Ensure you've called `scenarist.start()` before tests and `scenarist.stop()` after:
1143
1232
 
1144
1233
  ```typescript
1145
- beforeAll(() => scenarist.start()); // Starts MSW server
1146
- afterAll(() => scenarist.stop()); // Stops MSW server
1234
+ beforeAll(() => scenarist.start()); // Starts MSW server
1235
+ afterAll(() => scenarist.stop()); // Stops MSW server
1147
1236
  ```
1148
1237
 
1149
1238
  ### Tests see each other's scenarios
@@ -1154,13 +1243,13 @@ afterAll(() => scenarist.stop()); // Stops MSW server
1154
1243
 
1155
1244
  ```typescript
1156
1245
  // ❌ Wrong - missing header on second request
1157
- await setScenario('test-1', 'my-scenario');
1158
- const response = await fetch('http://localhost:3000/api/data'); // No test ID!
1246
+ await setScenario("test-1", "my-scenario");
1247
+ const response = await fetch("http://localhost:3000/api/data"); // No test ID!
1159
1248
 
1160
1249
  // ✅ Correct - header on all requests
1161
- await setScenario('test-1', 'my-scenario');
1162
- const response = await fetch('http://localhost:3000/api/data', {
1163
- headers: { 'x-scenarist-test-id': 'test-1' },
1250
+ await setScenario("test-1", "my-scenario");
1251
+ const response = await fetch("http://localhost:3000/api/data", {
1252
+ headers: { "x-scenarist-test-id": "test-1" },
1164
1253
  });
1165
1254
  ```
1166
1255
 
@@ -1174,17 +1263,17 @@ const response = await fetch('http://localhost:3000/api/data', {
1174
1263
  // lib/scenarios.ts
1175
1264
  export const scenarios = {
1176
1265
  default: defaultScenario,
1177
- 'my-scenario': myScenario, // ✅ Include in scenarios object
1266
+ "my-scenario": myScenario, // ✅ Include in scenarios object
1178
1267
  } as const satisfies ScenaristScenarios;
1179
1268
 
1180
1269
  // lib/scenarist.ts
1181
1270
  const scenarist = createScenarist({
1182
1271
  enabled: true,
1183
- scenarios, // All scenarios registered automatically
1272
+ scenarios, // All scenarios registered automatically
1184
1273
  });
1185
1274
 
1186
1275
  // tests
1187
- await setScenario('test-1', 'my-scenario'); // ✅ Now works
1276
+ await setScenario("test-1", "my-scenario"); // ✅ Now works
1188
1277
  ```
1189
1278
 
1190
1279
  ### TypeScript errors with Next.js types
@@ -1198,13 +1287,14 @@ await setScenario('test-1', 'my-scenario'); // ✅ Now works
1198
1287
  This package is written in TypeScript and includes full type definitions.
1199
1288
 
1200
1289
  **Exported Types:**
1290
+
1201
1291
  ```typescript
1202
1292
  // Pages Router - adapter-specific types
1203
1293
  import type {
1204
1294
  PagesAdapterOptions,
1205
1295
  PagesScenarist,
1206
1296
  PagesRequestContext,
1207
- } from '@scenarist/nextjs-adapter/pages';
1297
+ } from "@scenarist/nextjs-adapter/pages";
1208
1298
 
1209
1299
  // Pages Router - core types (re-exported for convenience)
1210
1300
  import type {
@@ -1217,14 +1307,14 @@ import type {
1217
1307
  ScenaristScenarios,
1218
1308
  ScenaristConfig,
1219
1309
  ScenaristResult,
1220
- } from '@scenarist/nextjs-adapter/pages';
1310
+ } from "@scenarist/nextjs-adapter/pages";
1221
1311
 
1222
1312
  // App Router - adapter-specific types
1223
1313
  import type {
1224
1314
  AppAdapterOptions,
1225
1315
  AppScenarist,
1226
1316
  AppRequestContext,
1227
- } from '@scenarist/nextjs-adapter/app';
1317
+ } from "@scenarist/nextjs-adapter/app";
1228
1318
 
1229
1319
  // App Router - core types (re-exported for convenience)
1230
1320
  import type {
@@ -1237,7 +1327,7 @@ import type {
1237
1327
  ScenaristScenarios,
1238
1328
  ScenaristConfig,
1239
1329
  ScenaristResult,
1240
- } from '@scenarist/nextjs-adapter/app';
1330
+ } from "@scenarist/nextjs-adapter/app";
1241
1331
  ```
1242
1332
 
1243
1333
  **Note:** All core types are re-exported from both `/pages` and `/app` subpaths for convenience. You only need one import path for all Scenarist types - just import from the subpath that matches your Next.js router.
@@ -1256,16 +1346,17 @@ If you need custom wiring for specialized use cases, you can access low-level co
1256
1346
  import {
1257
1347
  PagesRequestContext,
1258
1348
  createScenarioEndpoint,
1259
- } from '@scenarist/nextjs-adapter/pages';
1349
+ } from "@scenarist/nextjs-adapter/pages";
1260
1350
 
1261
1351
  // App Router low-level components
1262
1352
  import {
1263
1353
  AppRequestContext,
1264
1354
  createScenarioEndpoint,
1265
- } from '@scenarist/nextjs-adapter/app';
1355
+ } from "@scenarist/nextjs-adapter/app";
1266
1356
  ```
1267
1357
 
1268
1358
  **Use cases for low-level APIs:**
1359
+
1269
1360
  - Building a custom adapter for a Next.js-like framework
1270
1361
  - Integrating with non-standard request handling
1271
1362
  - Creating custom middleware chains
@@ -1295,9 +1386,11 @@ export const createScenarist = () => undefined;
1295
1386
  ### Bundle Size Impact
1296
1387
 
1297
1388
  **Before (development):**
1389
+
1298
1390
  - Scenarist adapter + Core + MSW: ~320kb
1299
1391
 
1300
1392
  **After (production with tree-shaking):**
1393
+
1301
1394
  - **0kb** - Complete elimination
1302
1395
 
1303
1396
  ### Verifying Tree-Shaking
@@ -1319,6 +1412,7 @@ This builds your app with `NODE_ENV=production` and verifies zero MSW code exist
1319
1412
  ### Bundler Configuration
1320
1413
 
1321
1414
  **Next.js (Automatic):**
1415
+
1322
1416
  - Next.js webpack/Turbopack automatically respects `NODE_ENV=production`
1323
1417
  - No configuration needed - tree-shaking works out of the box
1324
1418
 
@@ -1329,21 +1423,21 @@ If using a custom bundler, ensure it resolves the `"production"` condition:
1329
1423
  ```javascript
1330
1424
  // esbuild
1331
1425
  esbuild.build({
1332
- conditions: ['production'], // Resolves production entry points
1333
- define: { 'process.env.NODE_ENV': '"production"' },
1426
+ conditions: ["production"], // Resolves production entry points
1427
+ define: { "process.env.NODE_ENV": '"production"' },
1334
1428
  });
1335
1429
 
1336
1430
  // Webpack
1337
1431
  module.exports = {
1338
1432
  resolve: {
1339
- conditionNames: ['production', 'import'],
1433
+ conditionNames: ["production", "import"],
1340
1434
  },
1341
1435
  };
1342
1436
 
1343
1437
  // Vite
1344
1438
  export default {
1345
1439
  resolve: {
1346
- conditions: ['production'],
1440
+ conditions: ["production"],
1347
1441
  },
1348
1442
  };
1349
1443
  ```
@@ -1351,6 +1445,7 @@ export default {
1351
1445
  ### What Gets Eliminated
1352
1446
 
1353
1447
  When tree-shaking succeeds, your production bundle has:
1448
+
1354
1449
  - ❌ No MSW runtime code (`setupWorker`, `http.get`, `HttpResponse.json`)
1355
1450
  - ❌ No Scenarist core code (scenario manager, state manager, etc.)
1356
1451
  - ❌ No Zod validation schemas
@@ -1362,6 +1457,7 @@ When tree-shaking succeeds, your production bundle has:
1362
1457
  **If `verify:treeshaking` fails:**
1363
1458
 
1364
1459
  1. **Check `NODE_ENV`:** Ensure `NODE_ENV=production` during build
1460
+
1365
1461
  ```bash
1366
1462
  NODE_ENV=production next build
1367
1463
  ```
@@ -1371,6 +1467,7 @@ When tree-shaking succeeds, your production bundle has:
1371
1467
  - Custom bundlers: Add `conditions: ['production']`
1372
1468
 
1373
1469
  3. **Check dynamic imports:** Avoid dynamic imports that bypass tree-shaking
1470
+
1374
1471
  ```typescript
1375
1472
  // ❌ BAD - Bypasses tree-shaking
1376
1473
  const scenarist = await import('@scenarist/nextjs-adapter/app');
@@ -1394,13 +1491,13 @@ The adapter uses **package.json conditional exports** to provide different entry
1394
1491
  "exports": {
1395
1492
  "./app": {
1396
1493
  "types": "./dist/app/index.d.ts",
1397
- "production": "./dist/app/production.js", // Returns undefined
1398
- "import": "./dist/app/index.js" // Full implementation
1494
+ "production": "./dist/app/production.js", // Returns undefined
1495
+ "import": "./dist/app/index.js" // Full implementation
1399
1496
  },
1400
1497
  "./pages": {
1401
1498
  "types": "./dist/pages/index.d.ts",
1402
1499
  "production": "./dist/pages/production.js", // Returns undefined
1403
- "import": "./dist/pages/index.js" // Full implementation
1500
+ "import": "./dist/pages/index.js" // Full implementation
1404
1501
  }
1405
1502
  }
1406
1503
  }
@@ -1421,6 +1518,7 @@ The adapter uses **package.json conditional exports** to provide different entry
1421
1518
  **For developers:** This package has an explicit exception to the project's 100% coverage requirement.
1422
1519
 
1423
1520
  **Current Coverage:**
1521
+
1424
1522
  - Lines: 100% ✅
1425
1523
  - Statements: 100% ✅
1426
1524
  - Branches: 100% ✅
@@ -1439,6 +1537,7 @@ const handler = createDynamicHandler({
1439
1537
  ```
1440
1538
 
1441
1539
  Adapter unit tests focus on Layer 2 (translation layer):
1540
+
1442
1541
  - Request context extraction
1443
1542
  - Endpoint request/response handling
1444
1543
  - Framework-specific edge cases
@@ -1448,6 +1547,7 @@ These tests do NOT make real HTTP requests, so the handler arrow functions are n
1448
1547
  **Resolution:**
1449
1548
 
1450
1549
  Phase 0 (Next.js example app) will add integration tests that:
1550
+
1451
1551
  - Make real HTTP requests (like Express example app does with supertest)
1452
1552
  - Trigger MSW handlers
1453
1553
  - Execute the remaining arrow functions
@@ -1456,6 +1556,7 @@ Phase 0 (Next.js example app) will add integration tests that:
1456
1556
  **Precedent:**
1457
1557
 
1458
1558
  The Express adapter follows the same pattern:
1559
+
1459
1560
  - Adapter unit tests: `packages/express-adapter/tests/`
1460
1561
  - Integration tests: `apps/express-example/tests/` (with supertest)
1461
1562
  - Combined result: 100% coverage