@scenarist/express-adapter 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,45 +1,1021 @@
1
1
  # @scenarist/express-adapter
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ [![npm version](https://img.shields.io/npm/v/@scenarist/express-adapter.svg)](https://www.npmjs.com/package/@scenarist/express-adapter)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
5
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
+ Express.js adapter for [Scenarist](https://scenarist.io) - manage MSW mock scenarios in your Express applications for testing **and** development.
6
7
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
+ ## What is Scenarist?
8
9
 
9
- ## Purpose
10
+ **Scenarist** enables concurrent E2E tests to run with different backend states by switching mock scenarios at runtime via test IDs. No application restarts needed, no complex per-test mocking, just simple scenario switching.
10
11
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@scenarist/express-adapter`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
12
+ **Before Scenarist:**
13
+ ```typescript
14
+ // Every test has fragile per-test mocking
15
+ beforeEach(() => {
16
+ server.use(
17
+ http.get('/api/user', () => HttpResponse.json({ role: 'admin' }))
18
+ );
19
+ });
20
+ // Repeat 100 times across test files, hope they don't conflict
21
+ ```
15
22
 
16
- ## What is OIDC Trusted Publishing?
23
+ **With Scenarist:**
24
+ ```typescript
25
+ // Define scenario once
26
+ const adminScenario = { id: 'admin', mocks: [/* complete backend state */] };
17
27
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
28
+ // Use in any test with one line
29
+ await setScenario('test-1', 'admin');
30
+ // Test runs with complete "admin" backend state, isolated from other tests
31
+ ```
19
32
 
20
- ## Setup Instructions
33
+ ## Why Use Scenarist with Express?
21
34
 
22
- To properly configure OIDC trusted publishing for this package:
35
+ **Runtime Scenario Switching**
36
+ - Change entire backend state with one API call
37
+ - No server restarts between tests
38
+ - Instant feedback during development
23
39
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
40
+ **True Parallel Testing**
41
+ - 100+ tests run concurrently with different scenarios
42
+ - Each test ID has isolated scenario state
43
+ - No conflicts, no serialization needed
28
44
 
29
- ## DO NOT USE THIS PACKAGE
45
+ **Automatic Test ID Propagation** (Express advantage)
46
+ - AsyncLocalStorage propagates test IDs automatically
47
+ - No manual header forwarding in route handlers
48
+ - MSW handlers receive test ID transparently
30
49
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
50
+ **Reusable Scenarios**
51
+ - Define scenarios once, use across all tests
52
+ - Version control your mock scenarios
53
+ - Share scenarios across teams
36
54
 
37
- ## More Information
55
+ **Zero Boilerplate**
56
+ - One function call (`createScenarist()`) wires everything
57
+ - Middleware + endpoints + MSW automatically configured
58
+ - Just add `app.use(scenarist.middleware)` and you're done
38
59
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
60
+ ## What is this package?
42
61
 
43
- ---
62
+ This package provides a complete Express integration for Scenarist's scenario management system. With one function call, you get:
44
63
 
45
- **Maintained for OIDC setup purposes only**
64
+ - **Runtime scenario switching** via HTTP endpoints (`/__scenario__`)
65
+ - **Test isolation** using unique test IDs (`x-scenarist-test-id` header)
66
+ - **Automatic MSW integration** for request interception
67
+ - **AsyncLocalStorage** for automatic test ID propagation
68
+ - **Zero boilerplate** - everything wired automatically
69
+
70
+ ## Installation
71
+
72
+ ```bash
73
+ # npm
74
+ npm install --save-dev @scenarist/express-adapter msw
75
+
76
+ # pnpm
77
+ pnpm add -D @scenarist/express-adapter msw
78
+
79
+ # yarn
80
+ yarn add -D @scenarist/express-adapter msw
81
+ ```
82
+
83
+ **Note:** All Scenarist types (`ScenaristScenario`, `ScenaristMock`, etc.) are re-exported from `@scenarist/express-adapter` for convenience. You don't need to install `@scenarist/core` or `@scenarist/msw-adapter` separately - they're already included as dependencies.
84
+
85
+ **Peer Dependencies:**
86
+ - `express` ^4.18.0 || ^5.0.0
87
+ - `msw` ^2.0.0
88
+
89
+ ## Quick Start
90
+
91
+ ### 1. Define Scenarios
92
+
93
+ ```typescript
94
+ // test/scenarios.ts
95
+ import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/express-adapter';
96
+
97
+ const defaultScenario: ScenaristScenario = {
98
+ id: 'default',
99
+ name: 'Default Scenario',
100
+ description: 'Baseline responses for all APIs',
101
+ mocks: [
102
+ {
103
+ method: 'GET',
104
+ url: 'https://api.example.com/user',
105
+ response: {
106
+ status: 200,
107
+ body: {
108
+ id: '000',
109
+ name: 'Default User',
110
+ role: 'user',
111
+ },
112
+ },
113
+ },
114
+ ],
115
+ };
116
+
117
+ const adminUserScenario: ScenaristScenario = {
118
+ id: 'admin-user',
119
+ name: 'Admin User',
120
+ description: 'User with admin privileges',
121
+ mocks: [
122
+ {
123
+ method: 'GET',
124
+ url: 'https://api.example.com/user',
125
+ response: {
126
+ status: 200,
127
+ body: {
128
+ id: '123',
129
+ name: 'Admin User',
130
+ role: 'admin',
131
+ },
132
+ },
133
+ },
134
+ ],
135
+ };
136
+
137
+ // Export as typed scenarios object for type safety
138
+ export const scenarios = {
139
+ default: defaultScenario,
140
+ adminUser: adminUserScenario,
141
+ } as const satisfies ScenaristScenarios;
142
+ ```
143
+
144
+ ### 2. Create Scenarist Instance
145
+
146
+ ```typescript
147
+ // test/setup.ts
148
+ import { createScenarist } from '@scenarist/express-adapter';
149
+ import { scenarios } from './scenarios';
150
+
151
+ export const scenarist = createScenarist({
152
+ enabled: process.env.NODE_ENV === 'test',
153
+ scenarios, // All scenarios registered upfront
154
+ strictMode: false,
155
+ });
156
+ ```
157
+
158
+ ### 3. Add to Express App
159
+
160
+ ```typescript
161
+ // src/app.ts
162
+ import express from 'express';
163
+ import { scenarist } from '../test/setup';
164
+
165
+ const app = express();
166
+ app.use(express.json());
167
+
168
+ // Add Scenarist middleware (includes everything)
169
+ if (process.env.NODE_ENV === 'test') {
170
+ app.use(scenarist.middleware);
171
+ }
172
+
173
+ // Your application routes
174
+ app.get('/api/user', async (req, res) => {
175
+ const response = await fetch('https://api.example.com/user');
176
+ const user = await response.json();
177
+ res.json(user);
178
+ });
179
+
180
+ export { app };
181
+ ```
182
+
183
+ ### 4. Use in Tests
184
+
185
+ ```typescript
186
+ // test/api.test.ts
187
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
188
+ import request from 'supertest';
189
+ import { app } from '../src/app';
190
+ import { scenarist } from './setup';
191
+
192
+ describe('User API', () => {
193
+ beforeAll(() => scenarist.start());
194
+ afterAll(() => scenarist.stop());
195
+
196
+ it('should return admin user', async () => {
197
+ // Set scenario for this test
198
+ await request(app)
199
+ .post('/__scenario__')
200
+ .set('x-scenarist-test-id', 'admin-test')
201
+ .send({ scenario: 'admin-user' });
202
+
203
+ // Make request - MSW intercepts automatically
204
+ const response = await request(app)
205
+ .get('/api/user')
206
+ .set('x-scenarist-test-id', 'admin-test');
207
+
208
+ expect(response.status).toBe(200);
209
+ expect(response.body.role).toBe('admin');
210
+ });
211
+ });
212
+ ```
213
+
214
+ ## API Reference
215
+
216
+ ### `createScenarist(options)`
217
+
218
+ Creates a Scenarist instance with everything wired automatically.
219
+
220
+ **Parameters:**
221
+ ```typescript
222
+ type ExpressAdapterOptions<T extends ScenaristScenarios> = {
223
+ enabled: boolean; // Whether mocking is enabled
224
+ scenarios: T; // REQUIRED - scenarios object
225
+ strictMode?: boolean; // Return 501 for unmocked requests (default: false)
226
+ headers?: {
227
+ testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
228
+ };
229
+ endpoints?: {
230
+ setScenario?: string; // POST endpoint (default: '/__scenario__')
231
+ getScenario?: string; // GET endpoint (default: '/__scenario__')
232
+ };
233
+ defaultTestId?: string; // Default test ID (default: 'default-test')
234
+ registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
235
+ store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
236
+ };
237
+ ```
238
+
239
+ **Returns:**
240
+ ```typescript
241
+ type ExpressScenarist<T extends ScenaristScenarios> = {
242
+ config: ScenaristConfig; // Resolved configuration (endpoints, headers, etc.)
243
+ middleware: Router; // Express middleware (includes test ID extraction + scenario endpoints)
244
+ switchScenario: (testId: string, scenarioId: keyof T, variant?: string) => ScenaristResult<void, Error>;
245
+ getActiveScenario: (testId: string) => ActiveScenario | undefined;
246
+ getScenarioById: (scenarioId: string) => ScenaristScenario | undefined;
247
+ listScenarios: () => ReadonlyArray<ScenaristScenario>;
248
+ clearScenario: (testId: string) => void;
249
+ start: () => void; // Start MSW server
250
+ stop: () => Promise<void>; // Stop MSW server
251
+ };
252
+ ```
253
+
254
+ **Example:**
255
+ ```typescript
256
+ const scenarios = {
257
+ default: defaultScenario,
258
+ success: successScenario,
259
+ error: errorScenario,
260
+ } as const satisfies ScenaristScenarios;
261
+
262
+ const scenarist = createScenarist({
263
+ enabled: true,
264
+ scenarios,
265
+ strictMode: false,
266
+ });
267
+
268
+ app.use(scenarist.middleware);
269
+
270
+ beforeAll(() => scenarist.start());
271
+ afterAll(() => scenarist.stop());
272
+ ```
273
+
274
+ ### Scenario Endpoints
275
+
276
+ The middleware automatically exposes these endpoints:
277
+
278
+ #### `POST /__scenario__` - Set Active Scenario
279
+
280
+ **Request:**
281
+ ```typescript
282
+ {
283
+ scenario: string; // Scenario ID (required)
284
+ variant?: string; // Variant name (optional)
285
+ }
286
+ ```
287
+
288
+ **Response (200):**
289
+ ```typescript
290
+ {
291
+ success: true;
292
+ testId: string;
293
+ scenario: string;
294
+ variant?: string;
295
+ }
296
+ ```
297
+
298
+ **Example:**
299
+ ```typescript
300
+ await request(app)
301
+ .post('/__scenario__')
302
+ .set('x-scenarist-test-id', 'test-123')
303
+ .send({ scenario: 'user-logged-in' });
304
+ ```
305
+
306
+ #### `GET /__scenario__` - Get Active Scenario
307
+
308
+ **Response (200):**
309
+ ```typescript
310
+ {
311
+ testId: string;
312
+ scenarioId: string;
313
+ scenarioName?: string;
314
+ }
315
+ ```
316
+
317
+ **Response (404) - No Active Scenario:**
318
+ ```typescript
319
+ {
320
+ error: "No active scenario for this test ID";
321
+ testId: string;
322
+ }
323
+ ```
324
+
325
+ **Example:**
326
+ ```typescript
327
+ // After setting a scenario
328
+ const response = await request(app)
329
+ .get('/__scenario__')
330
+ .set('x-scenarist-test-id', 'test-123');
331
+
332
+ expect(response.status).toBe(200);
333
+ expect(response.body.scenarioId).toBe('success');
334
+
335
+ // Before setting a scenario
336
+ const response2 = await request(app)
337
+ .get('/__scenario__')
338
+ .set('x-scenarist-test-id', 'new-test');
339
+
340
+ expect(response2.status).toBe(404);
341
+ expect(response2.body.error).toBe('No active scenario for this test ID');
342
+ ```
343
+
344
+ ## Core Capabilities
345
+
346
+ Scenarist provides 20+ powerful features for E2E testing. All capabilities work seamlessly with Express via automatic test ID propagation.
347
+
348
+ ### Request Matching (6 capabilities)
349
+
350
+ **Body matching (partial match)** - Match requests based on request body fields
351
+ ```typescript
352
+ {
353
+ method: 'POST',
354
+ url: '/api/items',
355
+ match: { body: { itemId: 'premium-item' } },
356
+ response: { status: 200, body: { price: 100 } }
357
+ }
358
+ ```
359
+
360
+ **Header matching (exact match)** - Perfect for user tier testing
361
+ ```typescript
362
+ {
363
+ method: 'GET',
364
+ url: '/api/data',
365
+ match: { headers: { 'x-user-tier': 'premium' } },
366
+ response: { status: 200, body: { limit: 1000 } }
367
+ }
368
+ ```
369
+
370
+ **Query parameter matching** - Different responses for filtered requests
371
+ ```typescript
372
+ {
373
+ method: 'GET',
374
+ url: '/api/search',
375
+ match: { query: { filter: 'active' } },
376
+ response: { status: 200, body: { results: [...] } }
377
+ }
378
+ ```
379
+
380
+ **Combined matching** - Combine body + headers + query (all must pass)
381
+ **Specificity-based selection** - Most specific mock wins (no need to order carefully)
382
+ **Fallback mocks** - Mocks without match criteria act as catch-all
383
+
384
+ ### Response Sequences (4 capabilities)
385
+
386
+ **Single responses** - Return same response every time
387
+ **Response sequences (ordered)** - Return different response on each call
388
+ ```typescript
389
+ {
390
+ method: 'GET',
391
+ url: '/api/job/:id',
392
+ sequence: {
393
+ responses: [
394
+ { status: 200, body: { status: 'pending' } },
395
+ { status: 200, body: { status: 'processing' } },
396
+ { status: 200, body: { status: 'complete' } }
397
+ ],
398
+ repeat: 'last' // Stay at final response
399
+ }
400
+ }
401
+ ```
402
+
403
+ **Repeat modes** - `last` (stay at final), `cycle` (loop), `none` (exhaust)
404
+ **Sequence exhaustion with fallback** - Exhausted sequences skip to next mock
405
+
406
+ ### Stateful Mocks (6 capabilities)
407
+
408
+ **State capture from requests** - Extract values from body/headers/query
409
+ **State injection via templates** - Inject captured state using `{{state.X}}`
410
+ ```typescript
411
+ // Capture from POST
412
+ {
413
+ method: 'POST',
414
+ url: '/api/cart/items',
415
+ captureState: { 'cartItems[]': 'body.item' }, // Append to array
416
+ response: { status: 200 }
417
+ }
418
+
419
+ // Inject into GET
420
+ {
421
+ method: 'GET',
422
+ url: '/api/cart',
423
+ response: {
424
+ status: 200,
425
+ body: {
426
+ items: '{{state.cartItems}}',
427
+ count: '{{state.cartItems.length}}'
428
+ }
429
+ }
430
+ }
431
+ ```
432
+
433
+ **Array append support** - Syntax: `stateKey[]` appends to array
434
+ **Nested state paths** - Support dot notation: `user.profile.name`
435
+ **State isolation per test ID** - Each test ID has isolated state
436
+ **State reset on scenario switch** - Fresh state for each scenario
437
+
438
+ ### Core Features (4 capabilities)
439
+
440
+ **Multiple API mocking** - Mock any number of external APIs in one scenario
441
+ **Default scenario fallback** - Unmocked endpoints fall back to default scenario
442
+ **Test ID isolation** - Run 100+ tests concurrently without conflicts
443
+ **Runtime scenario switching** - Change backend state with one API call
444
+
445
+ ### Additional Features
446
+
447
+ **Path parameters** (`/users/:id`), **Wildcard URLs** (`*/api/*`), **Response delays**, **Custom headers**, **Strict mode** (fail on unmocked requests)
448
+
449
+ **Want to learn more?** See [Core Functionality Documentation](../../docs/core-functionality.md) for detailed explanations and examples.
450
+
451
+ ## Core Concepts
452
+
453
+ ### Test ID Isolation
454
+
455
+ Each request can include an `x-scenarist-test-id` header. Scenarist uses this to isolate scenarios, enabling concurrent tests with different backend states:
456
+
457
+ ```typescript
458
+ // Test 1 uses scenario A
459
+ await request(app)
460
+ .get('/api/data')
461
+ .set('x-scenarist-test-id', 'test-1'); // Uses scenario A
462
+
463
+ // Test 2 uses scenario B (runs concurrently!)
464
+ await request(app)
465
+ .get('/api/data')
466
+ .set('x-scenarist-test-id', 'test-2'); // Uses scenario B
467
+ ```
468
+
469
+ ### Automatic Test ID Propagation
470
+
471
+ **Express advantage:** Unlike frameworks without middleware (like Next.js), Express uses **AsyncLocalStorage** to automatically propagate test IDs throughout the request lifecycle.
472
+
473
+ **What this means:**
474
+ - Middleware extracts test ID from `x-scenarist-test-id` header **once**
475
+ - Test ID stored in AsyncLocalStorage for the request duration
476
+ - MSW handlers automatically access test ID from AsyncLocalStorage
477
+ - **No manual header forwarding needed** when making external API calls
478
+
479
+ **Example - No manual forwarding:**
480
+
481
+ ```typescript
482
+ // routes/products.ts
483
+ app.get('/api/products', async (req, res) => {
484
+ // Test ID automatically available to MSW via AsyncLocalStorage
485
+ // No need to manually forward headers!
486
+ const response = await fetch('http://external-api.com/products');
487
+ const products = await response.json();
488
+ res.json(products);
489
+ });
490
+ ```
491
+
492
+ **Compare to Next.js** (which requires manual forwarding):
493
+
494
+ ```typescript
495
+ // Next.js - MUST manually forward headers
496
+ const response = await fetch('http://external-api.com/products', {
497
+ headers: {
498
+ ...getScenaristHeaders(req, scenarist), // Required!
499
+ },
500
+ });
501
+ ```
502
+
503
+ **Express - NO manual forwarding needed** (AsyncLocalStorage handles it):
504
+
505
+ ```typescript
506
+ // Express - AsyncLocalStorage propagates automatically
507
+ const response = await fetch('http://external-api.com/products');
508
+ // MSW handlers receive test ID from AsyncLocalStorage
509
+ ```
510
+
511
+ **Why this works:**
512
+ - Express middleware runs before all routes
513
+ - Middleware extracts `x-scenarist-test-id` and stores in AsyncLocalStorage
514
+ - MSW dynamic handler reads from AsyncLocalStorage
515
+ - All external API calls intercepted with correct test ID
516
+
517
+ **For architectural details, see:** [ADR-0007: Framework-Specific Header Forwarding](../../docs/adrs/0007-framework-specific-header-helpers.md)
518
+
519
+ ### Automatic MSW Integration
520
+
521
+ The `createScenarist()` function automatically:
522
+ 1. Creates an MSW server with a dynamic handler
523
+ 2. Wires test ID extraction from headers via AsyncLocalStorage
524
+ 3. Sets up scenario control endpoints (POST/GET `/__scenario__`)
525
+ 4. Looks up the active scenario for each test ID
526
+ 5. Returns mocked responses based on the scenario
527
+
528
+ The `middleware` includes everything:
529
+ - Test ID extraction from `x-scenarist-test-id` header (stored in AsyncLocalStorage)
530
+ - Scenario control endpoints (`/__scenario__`)
531
+ - All wired together - just add `app.use(scenarist.middleware)`
532
+
533
+ You never see MSW code - it's all handled internally.
534
+
535
+ ### Default Scenario Fallback
536
+
537
+ If a mock isn't found in the active scenario, Scenarist automatically falls back to the `'default'` scenario (enforced via schema validation):
538
+
539
+ ```typescript
540
+ const scenarios = {
541
+ default: { // REQUIRED - must have 'default' key
542
+ id: 'default',
543
+ name: 'Default Happy Path',
544
+ description: 'Base responses for all APIs',
545
+ mocks: [
546
+ { method: 'GET', url: '*/api/users', response: { status: 200, body: [] } },
547
+ { method: 'GET', url: '*/api/orders', response: { status: 200, body: [] } },
548
+ ],
549
+ },
550
+ userError: {
551
+ id: 'user-error',
552
+ name: 'User API Error',
553
+ mocks: [
554
+ { method: 'GET', url: '*/api/users', response: { status: 500, body: { error: 'Server error' } } },
555
+ // Orders endpoint falls back to default scenario
556
+ ],
557
+ },
558
+ } as const satisfies ScenaristScenarios;
559
+
560
+ const scenarist = createScenarist({
561
+ enabled: true,
562
+ scenarios, // 'default' key is validated at runtime
563
+ });
564
+ ```
565
+
566
+ ## Type-Safe Scenario IDs
567
+
568
+ The new API provides full type safety with TypeScript autocomplete for scenario IDs:
569
+
570
+ ```typescript
571
+ // scenarios.ts - define scenarios with type constraint
572
+ import type { ScenaristScenarios } from '@scenarist/express-adapter';
573
+
574
+ export const scenarios = {
575
+ default: defaultScenario,
576
+ success: successScenario,
577
+ githubNotFound: githubNotFoundScenario,
578
+ weatherError: weatherErrorScenario,
579
+ stripeFailure: stripeFailureScenario,
580
+ } as const satisfies ScenaristScenarios;
581
+
582
+ // setup.ts - create scenarist with type parameter
583
+ import { scenarios } from './scenarios';
584
+
585
+ export const scenarist = createScenarist({
586
+ enabled: true,
587
+ scenarios, // ✅ Autocomplete + type-checked!
588
+ });
589
+
590
+ // test.ts - type-safe scenario switching
591
+ scenarist.switchScenario('test-123', 'success'); // ✅ Autocomplete works!
592
+ scenarist.switchScenario('test-123', 'invalid-name'); // ❌ TypeScript error!
593
+
594
+ await request(app)
595
+ .post(scenarist.config.endpoints.setScenario)
596
+ .set(SCENARIST_TEST_ID_HEADER, 'test-123')
597
+ .send({ scenario: 'success' }); // ✅ Type-safe!
598
+ ```
599
+
600
+ **Benefits:**
601
+ - ✅ Autocomplete for scenario IDs in your editor
602
+ - ✅ Refactor-safe (rename propagates everywhere)
603
+ - ✅ Compile-time errors for typos
604
+ - ✅ Single source of truth
605
+
606
+ ## Common Patterns
607
+
608
+ ### Pattern 1: Test Helpers
609
+
610
+ Create helper functions to reduce boilerplate:
611
+
612
+ ```typescript
613
+ // test/helpers.ts
614
+ import request from 'supertest';
615
+ import { app } from '../src/app';
616
+
617
+ export const setScenario = async (testId: string, scenario: string, variant?: string) => {
618
+ await request(app)
619
+ .post('/__scenario__')
620
+ .set('x-scenarist-test-id', testId)
621
+ .send({ scenario, variant });
622
+ };
623
+
624
+ export const makeRequest = (testId: string) => {
625
+ return request(app).set('x-scenarist-test-id', testId);
626
+ };
627
+ ```
628
+
629
+ **Usage:**
630
+ ```typescript
631
+ import { setScenario, makeRequest } from './helpers';
632
+
633
+ test('payment flow', async () => {
634
+ const testId = 'payment-test';
635
+ await setScenario(testId, 'payment-success');
636
+
637
+ const response = await makeRequest(testId).post('/api/charge');
638
+ expect(response.status).toBe(200);
639
+ });
640
+ ```
641
+
642
+ ### Pattern 2: Unique Test IDs
643
+
644
+ Generate unique test IDs automatically:
645
+
646
+ ```typescript
647
+ import { randomUUID } from 'crypto';
648
+
649
+ describe('API Tests', () => {
650
+ let testId: string;
651
+
652
+ beforeEach(() => {
653
+ testId = randomUUID();
654
+ });
655
+
656
+ it('should process payment', async () => {
657
+ await setScenario(testId, 'payment-success');
658
+ const response = await makeRequest(testId).post('/api/charge');
659
+ expect(response.status).toBe(200);
660
+ });
661
+ });
662
+ ```
663
+
664
+ ### Pattern 3: Development Workflows
665
+
666
+ Enable scenario switching during development:
667
+
668
+ ```typescript
669
+ const scenarist = createScenarist({
670
+ enabled: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test',
671
+ scenarios,
672
+ strictMode: false,
673
+ });
674
+ ```
675
+
676
+ Manually switch scenarios with curl:
677
+
678
+ ```bash
679
+ # Switch to error scenario
680
+ curl -X POST http://localhost:3000/__scenario__ \
681
+ -H "Content-Type: application/json" \
682
+ -d '{"scenario": "payment-declined"}'
683
+
684
+ # Check active scenario
685
+ curl http://localhost:3000/__scenario__
686
+ ```
687
+
688
+ ## Configuration
689
+
690
+ ### Environment-Specific
691
+
692
+ ```typescript
693
+ // Test-only
694
+ const scenarist = createScenarist({
695
+ enabled: process.env.NODE_ENV === 'test',
696
+ scenarios,
697
+ strictMode: true, // Fail if any unmocked request
698
+ });
699
+
700
+ // Development and test
701
+ const scenarist = createScenarist({
702
+ enabled: process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development',
703
+ scenarios,
704
+ strictMode: false, // Allow passthrough to real APIs
705
+ });
706
+
707
+ // Opt-in with environment variable
708
+ const scenarist = createScenarist({
709
+ enabled: process.env.ENABLE_MOCKING === 'true',
710
+ scenarios,
711
+ strictMode: false,
712
+ });
713
+ ```
714
+
715
+ ### Custom Headers and Endpoints
716
+
717
+ ```typescript
718
+ const scenarist = createScenarist({
719
+ enabled: true,
720
+ scenarios,
721
+ headers: {
722
+ testId: 'x-my-test-id',
723
+ },
724
+ endpoints: {
725
+ setScenario: '/api/scenarios/set',
726
+ getScenario: '/api/scenarios/active',
727
+ },
728
+ });
729
+ ```
730
+
731
+ ## Production Tree-Shaking
732
+
733
+ Scenarist is designed to be **completely eliminated from production bundles** when `NODE_ENV=production`. The implementation automatically disables itself and returns `undefined`, allowing bundlers to remove all Scenarist and MSW code through tree-shaking.
734
+
735
+ ### Unbundled Deployments (Most Express Apps) ✅
736
+
737
+ **For most Express applications** that deploy unbundled code directly to production (the standard pattern), tree-shaking works **automatically with zero configuration**:
738
+
739
+ ```bash
740
+ # Deploy your application
741
+ NODE_ENV=production node src/server.js
742
+ ```
743
+
744
+ **How it works:**
745
+ 1. `process.env.NODE_ENV === 'production'` evaluates to `true` at runtime
746
+ 2. `createScenarist()` returns `undefined` without loading dependencies
747
+ 3. MSW and all Scenarist code **never loads into memory**
748
+ 4. Zero performance impact, zero bundle bloat
749
+
750
+ **This is the default use case** - most Express applications don't bundle their server code.
751
+
752
+ ### Bundled Deployments (esbuild, webpack, Vite, rollup)
753
+
754
+ **For teams that bundle their Express server code**, additional bundler configuration is required to enable complete tree-shaking.
755
+
756
+ **Why configuration is needed:**
757
+
758
+ Scenarist uses **conditional package.json exports** to provide a production-specific entry point with zero dependencies:
759
+
760
+ ```json
761
+ {
762
+ "exports": {
763
+ ".": {
764
+ "production": "./dist/setup/production.js", // Zero imports
765
+ "default": "./dist/index.js" // Full implementation
766
+ }
767
+ }
768
+ }
769
+ ```
770
+
771
+ The `"production"` condition is a **custom condition** (not a Node.js built-in like `"import"` or `"require"`). Bundlers must be explicitly configured to recognize it.
772
+
773
+ **Without configuration:**
774
+ - MSW code included in bundle (~320kb)
775
+ - Code never executes (safe)
776
+ - Wastes bandwidth
777
+
778
+ **With configuration:**
779
+ - MSW code completely eliminated
780
+ - Bundle size reduced by ~52% (618kb → 298kb)
781
+ - Optimal production deployment
782
+
783
+ ### Bundler Configuration
784
+
785
+ #### esbuild
786
+
787
+ Add the `--conditions=production` flag:
788
+
789
+ ```json
790
+ {
791
+ "scripts": {
792
+ "build": "esbuild src/server.ts --bundle --platform=node --format=esm --outfile=dist/server.js --define:process.env.NODE_ENV='\"production\"' --conditions=production"
793
+ }
794
+ }
795
+ ```
796
+
797
+ #### webpack
798
+
799
+ Add `conditionNames` to resolve configuration:
800
+
801
+ ```javascript
802
+ // webpack.config.js
803
+ module.exports = {
804
+ mode: 'production',
805
+ resolve: {
806
+ conditionNames: ['production', 'import', 'require']
807
+ },
808
+ plugins: [
809
+ new webpack.DefinePlugin({
810
+ 'process.env.NODE_ENV': JSON.stringify('production')
811
+ })
812
+ ]
813
+ };
814
+ ```
815
+
816
+ #### Vite
817
+
818
+ Add `conditions` to resolve configuration:
819
+
820
+ ```javascript
821
+ // vite.config.js
822
+ export default {
823
+ resolve: {
824
+ conditions: ['production']
825
+ },
826
+ define: {
827
+ 'process.env.NODE_ENV': JSON.stringify('production')
828
+ }
829
+ };
830
+ ```
831
+
832
+ #### rollup
833
+
834
+ Add `exportConditions` to node-resolve plugin:
835
+
836
+ ```javascript
837
+ // rollup.config.js
838
+ import resolve from '@rollup/plugin-node-resolve';
839
+ import replace from '@rollup/plugin-replace';
840
+
841
+ export default {
842
+ plugins: [
843
+ resolve({
844
+ exportConditions: ['production']
845
+ }),
846
+ replace({
847
+ 'process.env.NODE_ENV': JSON.stringify('production'),
848
+ preventAssignment: true
849
+ })
850
+ ]
851
+ };
852
+ ```
853
+
854
+ ### Verifying Tree-Shaking
855
+
856
+ The Express example app includes a verification script you can adapt:
857
+
858
+ ```json
859
+ {
860
+ "scripts": {
861
+ "build:production": "esbuild src/server.ts --bundle --platform=node --format=esm --outfile=dist/server.js --external:express --define:process.env.NODE_ENV='\"production\"' --minify --conditions=production",
862
+ "verify:treeshaking": "pnpm build:production && ! grep -rE '(setupWorker|startWorker|http\\.(get|post|put|delete|patch)|HttpResponse\\.json)' dist/"
863
+ },
864
+ "devDependencies": {
865
+ "esbuild": "^0.27.0"
866
+ }
867
+ }
868
+ ```
869
+
870
+ **Run verification:**
871
+ ```bash
872
+ pnpm verify:treeshaking
873
+ ```
874
+
875
+ **Success output:**
876
+ ```
877
+ dist/server.js 298.4kb
878
+
879
+ ✨ Done in 13ms
880
+ ```
881
+
882
+ The script checks that MSW-specific implementation patterns (`setupWorker`, `HttpResponse.json`, etc.) are **not present** in the production bundle.
883
+
884
+ ### Bundle Size Comparison
885
+
886
+ **Without tree-shaking configuration:**
887
+ - Bundle size: ~618kb
888
+ - Includes: Application + Zod + MSW + Scenarist
889
+ - Status: Code included but never executes
890
+
891
+ **With tree-shaking configuration:**
892
+ - Bundle size: ~298kb (52% reduction)
893
+ - Includes: Application + Zod only
894
+ - Status: MSW and Scenarist completely eliminated
895
+
896
+ ### Trade-Offs
897
+
898
+ | Deployment Type | Configuration Required | Tree-Shaking | Bundle Impact |
899
+ |----------------|------------------------|--------------|---------------|
900
+ | **Unbundled** (standard Express) | ✅ None | ✅ Automatic | ✅ Zero (code never loads) |
901
+ | **Bundled** without config | ❌ None | ❌ Partial | ⚠️ ~320kb dead code |
902
+ | **Bundled** with config | ✅ One line | ✅ Complete | ✅ Zero (eliminated) |
903
+
904
+ **Recommendation:**
905
+ - If you're deploying unbundled code: No action needed ✅
906
+ - If you're bundling: Add the one-line bundler configuration for optimal bundle size
907
+
908
+ ## Troubleshooting
909
+
910
+ ### Scenarios switch but requests aren't mocked
911
+
912
+ **Problem:** Scenario endpoints work but external API calls go to real endpoints.
913
+
914
+ **Solution:** Ensure you've called `scenarist.start()` before tests and `scenarist.stop()` after:
915
+
916
+ ```typescript
917
+ beforeAll(() => scenarist.start()); // Starts MSW server
918
+ afterAll(() => scenarist.stop()); // Stops MSW server
919
+ ```
920
+
921
+ ### Tests see each other's scenarios
922
+
923
+ **Problem:** Different tests are seeing each other's active scenarios.
924
+
925
+ **Solution:** Ensure you're sending the `x-scenarist-test-id` header with **every** request:
926
+
927
+ ```typescript
928
+ // ❌ Wrong - missing header on second request
929
+ await setScenario('test-1', 'my-scenario');
930
+ const response = await request(app).get('/api/data'); // No test ID!
931
+
932
+ // ✅ Correct - header on all requests
933
+ await setScenario('test-1', 'my-scenario');
934
+ const response = await request(app)
935
+ .get('/api/data')
936
+ .set('x-scenarist-test-id', 'test-1');
937
+ ```
938
+
939
+ ### Scenario not found error
940
+
941
+ **Problem:** `Scenario not found` when setting scenario.
942
+
943
+ **Solution:** Ensure the scenario ID exists in your scenarios object:
944
+
945
+ ```typescript
946
+ const scenarios = {
947
+ default: defaultScenario,
948
+ myScenario: myScenario, // ✅ Registered
949
+ } as const satisfies ScenaristScenarios;
950
+
951
+ const scenarist = createScenarist({
952
+ enabled: true,
953
+ scenarios,
954
+ });
955
+
956
+ await setScenario('test-1', 'myScenario'); // ✅ Works
957
+ await setScenario('test-1', 'unknown'); // ❌ Error: Scenario not found
958
+ ```
959
+
960
+ ## TypeScript
961
+
962
+ This package is written in TypeScript and includes full type definitions.
963
+
964
+ **Exported Types:**
965
+ ```typescript
966
+ // Adapter-specific types
967
+ import type {
968
+ ExpressAdapterOptions,
969
+ ExpressScenarist,
970
+ } from '@scenarist/express-adapter';
971
+
972
+ // Core types (re-exported for convenience)
973
+ import type {
974
+ ScenaristScenario,
975
+ ScenaristMock,
976
+ ScenaristResponse,
977
+ ScenaristSequence,
978
+ ScenaristMatch,
979
+ ScenaristCaptureConfig,
980
+ ScenaristScenarios,
981
+ ScenaristConfig,
982
+ ScenaristResult,
983
+ } from '@scenarist/express-adapter';
984
+ ```
985
+
986
+ **Note:** All core types are re-exported from `@scenarist/express-adapter`, so you only need one import path for all Scenarist types.
987
+
988
+ ## Examples
989
+
990
+ See the [**Express Example App**](../../apps/express-example) for a complete working example demonstrating:
991
+
992
+ - ✅ **Runtime scenario switching** - Change API behavior without restart
993
+ - ✅ **Test ID isolation** - 20 E2E tests with concurrent scenarios
994
+ - ✅ **Default fallback** - Partial scenarios automatically falling back
995
+ - ✅ **Real API integration** - Actual Express routes calling external APIs
996
+ - ✅ **Multiple scenarios** - Success, errors, timeouts, mixed results
997
+
998
+ The example includes:
999
+ - Complete Express application with GitHub, Weather, and Stripe API integrations
1000
+ - 7 different scenario definitions
1001
+ - 20 passing E2E tests demonstrating all features
1002
+ - Comprehensive documentation and usage patterns
1003
+
1004
+ ## Documentation
1005
+
1006
+ 📖 **[Full Documentation](https://scenarist.io)** - Complete guides, API reference, and examples.
1007
+
1008
+ ## Contributing
1009
+
1010
+ See [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines.
1011
+
1012
+ ## License
1013
+
1014
+ MIT
1015
+
1016
+ ## Related Packages
1017
+
1018
+ - **[@scenarist/core](../core)** - Core scenario management
1019
+ - **[@scenarist/msw-adapter](../msw-adapter)** - MSW integration (used internally)
1020
+
1021
+ **Note:** The MSW adapter is used internally by this package. Users of `@scenarist/express-adapter` don't need to interact with it directly.