@scenarist/express-adapter 0.4.15 → 0.5.1

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
@@ -203,7 +203,7 @@ export const createApp = () => {
203
203
  strictMode: false,
204
204
  });
205
205
 
206
- // Add Scenarist middleware (only if enabled)
206
+ // Add Scenarist middleware (scenarist is undefined in production builds)
207
207
  if (scenarist) {
208
208
  app.use(scenarist.middleware);
209
209
  }
@@ -277,9 +277,6 @@ type ExpressAdapterOptions<T extends ScenaristScenarios> = {
277
277
  enabled: boolean; // Whether mocking is enabled
278
278
  scenarios: T; // REQUIRED - scenarios object
279
279
  strictMode?: boolean; // Return 501 for unmocked requests (default: false)
280
- headers?: {
281
- testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
282
- };
283
280
  endpoints?: {
284
281
  setScenario?: string; // POST endpoint (default: '/__scenario__')
285
282
  getScenario?: string; // GET endpoint (default: '/__scenario__')
@@ -293,19 +290,18 @@ type ExpressAdapterOptions<T extends ScenaristScenarios> = {
293
290
  **Returns:**
294
291
 
295
292
  ```typescript
296
- Promise<ExpressScenarist<T> | undefined>;
293
+ ExpressScenarist<T> | undefined;
297
294
  ```
298
295
 
299
296
  Where `ExpressScenarist<T>` is:
300
297
 
301
298
  ```typescript
302
299
  type ExpressScenarist<T extends ScenaristScenarios> = {
303
- config: ScenaristConfig; // Resolved configuration (endpoints, headers, etc.)
300
+ config: ScenaristConfig; // Resolved configuration (endpoints, strictMode, etc.)
304
301
  middleware: Router; // Express middleware (includes test ID extraction + scenario endpoints)
305
302
  switchScenario: (
306
303
  testId: string,
307
304
  scenarioId: keyof T,
308
- variant?: string,
309
305
  ) => ScenaristResult<void, Error>;
310
306
  getActiveScenario: (testId: string) => ActiveScenario | undefined;
311
307
  getScenarioById: (scenarioId: string) => ScenaristScenario | undefined;
@@ -351,7 +347,6 @@ The middleware automatically exposes these endpoints:
351
347
  ```typescript
352
348
  {
353
349
  scenario: string; // Scenario ID (required)
354
- variant?: string; // Variant name (optional)
355
350
  }
356
351
  ```
357
352
 
@@ -361,8 +356,7 @@ The middleware automatically exposes these endpoints:
361
356
  {
362
357
  success: true;
363
358
  testId: string;
364
- scenario: string;
365
- variant?: string;
359
+ scenarioId: string;
366
360
  }
367
361
  ```
368
362
 
@@ -556,7 +550,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
556
550
 
557
551
  ### Additional Features
558
552
 
559
- **Path parameters** (`/users/:id`), **Wildcard URLs** (`*/api/*`), **Response delays**, **Custom headers**, **Strict mode** (fail on unmocked requests)
553
+ **Path parameters** (`/users/:id`), **Pathname-only URLs** (`/api/users` matches any host), **RegExp URLs** (`/\/api\//`), **Response delays**, **Custom headers**, **Strict mode** (fail on unmocked requests)
560
554
 
561
555
  **Want to learn more?** See [Core Functionality Documentation](../../docs/core-functionality.md) for detailed explanations and examples.
562
556
 
@@ -658,12 +652,12 @@ const scenarios = {
658
652
  mocks: [
659
653
  {
660
654
  method: "GET",
661
- url: "*/api/users",
655
+ url: "/api/users",
662
656
  response: { status: 200, body: [] },
663
657
  },
664
658
  {
665
659
  method: "GET",
666
- url: "*/api/orders",
660
+ url: "/api/orders",
667
661
  response: { status: 200, body: [] },
668
662
  },
669
663
  ],
@@ -671,10 +665,11 @@ const scenarios = {
671
665
  userError: {
672
666
  id: "user-error",
673
667
  name: "User API Error",
668
+ description: "Users API fails",
674
669
  mocks: [
675
670
  {
676
671
  method: "GET",
677
- url: "*/api/users",
672
+ url: "/api/users",
678
673
  response: { status: 500, body: { error: "Server error" } },
679
674
  },
680
675
  // Orders endpoint falls back to default scenario
@@ -744,19 +739,15 @@ Create helper functions to reduce boilerplate:
744
739
  import request from "supertest";
745
740
  import { app } from "../src/app";
746
741
 
747
- export const setScenario = async (
748
- testId: string,
749
- scenario: string,
750
- variant?: string,
751
- ) => {
742
+ export const setScenario = async (testId: string, scenario: string) => {
752
743
  await request(app)
753
744
  .post("/__scenario__")
754
745
  .set("x-scenarist-test-id", testId)
755
- .send({ scenario, variant });
746
+ .send({ scenario });
756
747
  };
757
748
 
758
749
  export const makeRequest = (testId: string) => {
759
- return request(app).set("x-scenarist-test-id", testId);
750
+ return request.agent(app).set("x-scenarist-test-id", testId);
760
751
  };
761
752
  ```
762
753
 
@@ -849,15 +840,12 @@ const scenarist = createScenarist({
849
840
  });
850
841
  ```
851
842
 
852
- ### Custom Headers and Endpoints
843
+ ### Custom Endpoints
853
844
 
854
845
  ```typescript
855
846
  const scenarist = createScenarist({
856
847
  enabled: true,
857
848
  scenarios,
858
- headers: {
859
- testId: "x-my-test-id",
860
- },
861
849
  endpoints: {
862
850
  setScenario: "/api/scenarios/set",
863
851
  getScenario: "/api/scenarios/active",
@@ -867,25 +855,30 @@ const scenarist = createScenarist({
867
855
 
868
856
  ## Production Tree-Shaking
869
857
 
870
- 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.
858
+ Scenarist is designed to be **completely eliminated from production** when the `production` export condition is active. The package's production entry point returns `undefined` from `createScenarist()` and imports nothing, so no Scenarist or MSW code is loaded or bundled.
871
859
 
872
- ### Unbundled Deployments (Most Express Apps) ✅
860
+ ### Unbundled Deployments (Most Express Apps)
873
861
 
874
- **For most Express applications** that deploy unbundled code directly to production (the standard pattern), tree-shaking works **automatically with zero configuration**:
862
+ **For Express applications** that deploy unbundled code directly to production, start Node with the `production` condition:
875
863
 
876
864
  ```bash
877
- # Deploy your application
878
- NODE_ENV=production node src/server.js
865
+ # Recommended: no Scenarist or MSW code is loaded
866
+ NODE_ENV=production node --conditions=production src/server.js
879
867
  ```
880
868
 
881
- **How it works:**
882
-
883
- 1. `process.env.NODE_ENV === 'production'` evaluates to `true` at runtime
869
+ 1. Node resolves `@scenarist/express-adapter` to `dist/setup/production.js` because the `production` condition is active
884
870
  2. `createScenarist()` returns `undefined` without loading dependencies
885
871
  3. MSW and all Scenarist code **never loads into memory**
886
872
  4. Zero performance impact, zero bundle bloat
887
873
 
888
- **This is the default use case** - most Express applications don't bundle their server code.
874
+ **Without the condition, the runtime guard still protects you:**
875
+
876
+ ```bash
877
+ # Scenarist is inert: createScenarist() returns undefined, /__scenario__ returns 404
878
+ NODE_ENV=production node src/server.js
879
+ ```
880
+
881
+ `NODE_ENV=production` alone does not switch entry points, so Node loads the full implementation, but `createScenarist()` checks `NODE_ENV` and returns `undefined`: no middleware, no endpoints, no interception. The adapter and MSW modules are still imported, so `msw` must be installed. If you prune dev dependencies in production, use `--conditions=production`.
889
882
 
890
883
  ### Bundled Deployments (esbuild, webpack, Vite, rollup)
891
884
 
@@ -911,7 +904,7 @@ The `"production"` condition is a **custom condition** (not a Node.js built-in l
911
904
  **Without configuration:**
912
905
 
913
906
  - MSW code included in bundle (~320kb)
914
- - Code never executes (safe)
907
+ - The full implementation is bundled; with `NODE_ENV=production` the runtime guard makes `createScenarist()` return `undefined`, so it stays inert
915
908
  - Wastes bandwidth
916
909
 
917
910
  **With configuration:**
@@ -1029,7 +1022,7 @@ The script checks that MSW-specific implementation patterns (`setupWorker`, `Htt
1029
1022
 
1030
1023
  - Bundle size: ~618kb
1031
1024
  - Includes: Application + Zod + MSW + Scenarist
1032
- - Status: Code included but never executes
1025
+ - Status: Full implementation included and active
1033
1026
 
1034
1027
  **With tree-shaking configuration:**
1035
1028
 
@@ -1039,15 +1032,16 @@ The script checks that MSW-specific implementation patterns (`setupWorker`, `Htt
1039
1032
 
1040
1033
  ### Trade-Offs
1041
1034
 
1042
- | Deployment Type | Configuration Required | Tree-Shaking | Bundle Impact |
1043
- | -------------------------------- | ---------------------- | ------------ | -------------------------- |
1044
- | **Unbundled** (standard Express) | ✅ None | ✅ Automatic | ✅ Zero (code never loads) |
1045
- | **Bundled** without config | ❌ None | ❌ Partial | ⚠️ ~320kb dead code |
1046
- | **Bundled** with config | ✅ One line | ✅ Complete | ✅ Zero (eliminated) |
1035
+ | Deployment Type | Configuration Required | Tree-Shaking | Bundle Impact |
1036
+ | -------------------------- | ---------------------- | ------------ | -------------------------- |
1037
+ | **Unbundled** with flag | ✅ One flag | ✅ Complete | ✅ Zero (code never loads) |
1038
+ | **Unbundled** without flag | ❌ None | ❌ None | ⚠️ Full implementation |
1039
+ | **Bundled** without config | ❌ None | ❌ None | ⚠️ Full implementation |
1040
+ | **Bundled** with config | ✅ One line | ✅ Complete | ✅ Zero (eliminated) |
1047
1041
 
1048
1042
  **Recommendation:**
1049
1043
 
1050
- - If you're deploying unbundled code: No action needed ✅
1044
+ - If you're deploying unbundled code: Start Node with `--conditions=production`
1051
1045
  - If you're bundling: Add the one-line bundler configuration for optimal bundle size
1052
1046
 
1053
1047
  ## Logging & Debugging
@@ -1246,7 +1240,7 @@ import type {
1246
1240
  See the [**Express Example App**](../../apps/express-example) for a complete working example demonstrating:
1247
1241
 
1248
1242
  - ✅ **Runtime scenario switching** - Change API behavior without restart
1249
- - ✅ **Test ID isolation** - 20 tests with concurrent scenarios
1243
+ - ✅ **Test ID isolation** - Concurrent tests with different scenarios
1250
1244
  - ✅ **Default fallback** - Partial scenarios automatically falling back
1251
1245
  - ✅ **Real API integration** - Actual Express routes calling external APIs
1252
1246
  - ✅ **Multiple scenarios** - Success, errors, timeouts, mixed results
@@ -1254,8 +1248,8 @@ See the [**Express Example App**](../../apps/express-example) for a complete wor
1254
1248
  The example includes:
1255
1249
 
1256
1250
  - Complete Express application with GitHub, Weather, and Stripe API integrations
1257
- - 7 different scenario definitions
1258
- - 20 passing scenario-based tests demonstrating all features
1251
+ - 25 scenario definitions
1252
+ - 100+ passing scenario-based tests demonstrating all features
1259
1253
  - Comprehensive documentation and usage patterns
1260
1254
 
1261
1255
  ## Documentation
@@ -1272,7 +1266,7 @@ MIT
1272
1266
 
1273
1267
  ## Related Packages
1274
1268
 
1275
- - **[@scenarist/core](../core)** - Core scenario management
1276
- - **[@scenarist/msw-adapter](../msw-adapter)** - MSW integration (used internally)
1269
+ - **[@scenarist/core](../../internal/core)** - Core scenario management
1270
+ - **[@scenarist/msw-adapter](../../internal/msw-adapter)** - MSW integration (used internally)
1277
1271
 
1278
1272
  **Note:** The MSW adapter is used internally by this package. Users of `@scenarist/express-adapter` don't need to interact with it directly.
@@ -19,6 +19,9 @@ export type ExpressScenarist<T extends ScenaristScenarios = ScenaristScenarios>
19
19
  /**
20
20
  * Create a Scenarist instance for Express.
21
21
  *
22
+ * Returns `undefined` when `enabled` is false: no middleware, no endpoints,
23
+ * no request interception.
24
+ *
22
25
  * This is the primary API for Express users. It wires everything automatically:
23
26
  * - MSW server with dynamic handler
24
27
  * - Test ID middleware
@@ -46,5 +49,5 @@ export type ExpressScenarist<T extends ScenaristScenarios = ScenaristScenarios>
46
49
  * scenarist.switchScenario('test-123', 'premiumUser');
47
50
  * ```
48
51
  */
49
- export declare const createScenaristImpl: <T extends ScenaristScenarios>(options: ExpressAdapterOptions<T>) => ExpressScenarist<T>;
52
+ export declare const createScenaristImpl: <T extends ScenaristScenarios>(options: ExpressAdapterOptions<T>) => ExpressScenarist<T> | undefined;
50
53
  //# sourceMappingURL=impl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/setup/impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EASL,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACxB,MAAM,iBAAiB,CAAC;AAMzB;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,CAC/B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,kBAAkB,CAAC,CAAC,CAAC,CAAC;AAE1B;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,CAC1B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,kBAAkB,EAC9D,SAAS,qBAAqB,CAAC,CAAC,CAAC,KAChC,gBAAgB,CAAC,CAAC,CAoDpB,CAAC"}
1
+ {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/setup/impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EASL,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACxB,MAAM,iBAAiB,CAAC;AAMzB;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,CAC/B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,kBAAkB,CAAC,CAAC,CAAC,CAAC;AAE1B;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,CAC1B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,kBAAkB,EAC9D,SAAS,qBAAqB,CAAC,CAAC,CAAC,KAChC,gBAAgB,CAAC,CAAC,CAAC,GAAG,SA0DxB,CAAC"}
@@ -7,6 +7,9 @@ import { createScenarioEndpoints } from "../endpoints/scenario-endpoints.js";
7
7
  /**
8
8
  * Create a Scenarist instance for Express.
9
9
  *
10
+ * Returns `undefined` when `enabled` is false: no middleware, no endpoints,
11
+ * no request interception.
12
+ *
10
13
  * This is the primary API for Express users. It wires everything automatically:
11
14
  * - MSW server with dynamic handler
12
15
  * - Test ID middleware
@@ -35,6 +38,9 @@ import { createScenarioEndpoints } from "../endpoints/scenario-endpoints.js";
35
38
  * ```
36
39
  */
37
40
  export const createScenaristImpl = (options) => {
41
+ if (!options.enabled) {
42
+ return undefined;
43
+ }
38
44
  const config = buildConfig(options);
39
45
  const logger = options.logger ?? noOpLogger;
40
46
  const registry = options.registry ?? new InMemoryScenarioRegistry();
@@ -63,6 +69,8 @@ export const createScenaristImpl = (options) => {
63
69
  getScenarioDefinition: (scenarioId) => manager.getScenarioById(scenarioId),
64
70
  strictMode: config.strictMode,
65
71
  responseSelector,
72
+ errorBehaviors: config.errorBehaviors,
73
+ logger,
66
74
  });
67
75
  const middleware = Router();
68
76
  middleware.use(createTestIdMiddleware(config));
@@ -1,32 +1,20 @@
1
+ import type { ScenaristScenarios } from "@scenarist/core";
2
+ import { type ExpressAdapterOptions, type ExpressScenarist } from "./impl.js";
1
3
  export type { ExpressAdapterOptions, ExpressScenarist } from "./impl.js";
2
4
  /**
3
- * Create a Scenarist instance for Express.
4
- *
5
- * Production tree-shaking is handled via conditional exports in package.json:
6
- * - Development/test: Uses this file (imports impl.js with full MSW setup)
7
- * - Production builds: Uses production.js (returns undefined, zero imports)
8
- *
9
- * This ensures all test code is eliminated from production bundles.
5
+ * The NODE_ENV check is defense-in-depth: unbundled `node server.js` deploys don't apply the `production` export condition, so without it the scenario endpoints would mount in production.
10
6
  *
11
7
  * @example
12
8
  * ```typescript
13
- * // src/app.ts
14
- * import { createScenarist } from '@scenarist/express-adapter';
15
- * import { scenarios } from './scenarios';
16
- *
17
9
  * export const scenarist = createScenarist({
18
- * enabled: true,
10
+ * enabled: process.env.NODE_ENV === "test",
19
11
  * scenarios,
20
12
  * });
21
13
  *
22
14
  * if (scenarist) {
23
15
  * app.use(scenarist.middleware);
24
16
  * }
25
- *
26
- * // tests/setup.ts
27
- * beforeAll(() => scenarist?.start());
28
- * afterAll(() => scenarist?.stop());
29
17
  * ```
30
18
  */
31
- export { createScenaristImpl as createScenarist } from "./impl.js";
19
+ export declare const createScenarist: <T extends ScenaristScenarios>(options: ExpressAdapterOptions<T>) => ExpressScenarist<T> | undefined;
32
20
  //# sourceMappingURL=setup-scenarist.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-scenarist.d.ts","sourceRoot":"","sources":["../../src/setup/setup-scenarist.ts"],"names":[],"mappings":"AACA,YAAY,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,mBAAmB,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"setup-scenarist.d.ts","sourceRoot":"","sources":["../../src/setup/setup-scenarist.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAEL,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EACtB,MAAM,WAAW,CAAC;AAGnB,YAAY,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,SAAS,kBAAkB,EAC1D,SAAS,qBAAqB,CAAC,CAAC,CAAC,KAChC,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAMxB,CAAC"}
@@ -1,30 +1,22 @@
1
+ import { createScenaristImpl, } from "./impl.js";
1
2
  /**
2
- * Create a Scenarist instance for Express.
3
- *
4
- * Production tree-shaking is handled via conditional exports in package.json:
5
- * - Development/test: Uses this file (imports impl.js with full MSW setup)
6
- * - Production builds: Uses production.js (returns undefined, zero imports)
7
- *
8
- * This ensures all test code is eliminated from production bundles.
3
+ * The NODE_ENV check is defense-in-depth: unbundled `node server.js` deploys don't apply the `production` export condition, so without it the scenario endpoints would mount in production.
9
4
  *
10
5
  * @example
11
6
  * ```typescript
12
- * // src/app.ts
13
- * import { createScenarist } from '@scenarist/express-adapter';
14
- * import { scenarios } from './scenarios';
15
- *
16
7
  * export const scenarist = createScenarist({
17
- * enabled: true,
8
+ * enabled: process.env.NODE_ENV === "test",
18
9
  * scenarios,
19
10
  * });
20
11
  *
21
12
  * if (scenarist) {
22
13
  * app.use(scenarist.middleware);
23
14
  * }
24
- *
25
- * // tests/setup.ts
26
- * beforeAll(() => scenarist?.start());
27
- * afterAll(() => scenarist?.stop());
28
15
  * ```
29
16
  */
30
- export { createScenaristImpl as createScenarist } from "./impl.js";
17
+ export const createScenarist = (options) => {
18
+ if (process.env.NODE_ENV === "production") {
19
+ return undefined;
20
+ }
21
+ return createScenaristImpl(options);
22
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenarist/express-adapter",
3
- "version": "0.4.15",
3
+ "version": "0.5.1",
4
4
  "description": "Express middleware adapter for Scenarist",
5
5
  "author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
6
6
  "license": "MIT",
@@ -47,8 +47,8 @@
47
47
  "LICENSE"
48
48
  ],
49
49
  "dependencies": {
50
- "@scenarist/core": "0.4.15",
51
- "@scenarist/msw-adapter": "0.4.15",
50
+ "@scenarist/core": "0.5.1",
51
+ "@scenarist/msw-adapter": "0.5.1",
52
52
  "zod": "^4.6.5"
53
53
  },
54
54
  "peerDependencies": {