@scenarist/nextjs-adapter 0.4.14 → 0.5.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
@@ -179,7 +179,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
179
179
 
180
180
  ### Additional Features
181
181
 
182
- **Path parameters** (`/users/:id`), **Wildcard URLs** (`*/api/*`), **Response delays**, **Custom headers**, **Strict mode** (fail on unmocked requests)
182
+ **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)
183
183
 
184
184
  **Want to learn more?** See [Core Functionality Documentation](../../docs/core-functionality.md) for detailed explanations and examples.
185
185
 
@@ -194,7 +194,7 @@ Test how your UI handles API errors without maintaining separate error mocks per
194
194
  const errorScenario = {
195
195
  id: "api-error",
196
196
  name: "API Error",
197
- mocks: [{ method: "GET", url: "*/api/*", response: { status: 500 } }],
197
+ mocks: [{ method: "GET", url: /\/api\//, response: { status: 500 } }],
198
198
  };
199
199
 
200
200
  // Use in many tests
@@ -213,7 +213,7 @@ const slowScenario = {
213
213
  mocks: [
214
214
  {
215
215
  method: "GET",
216
- url: "*/api/data",
216
+ url: "/api/data",
217
217
  response: { status: 200, body: { data: [] }, delay: 3000 }, // 3s delay
218
218
  },
219
219
  ],
@@ -282,7 +282,7 @@ yarn add -D @scenarist/nextjs-adapter msw
282
282
 
283
283
  **Peer Dependencies:**
284
284
 
285
- - `next` ^14.0.0 || ^15.0.0
285
+ - `next` ^14.0.0 || ^15.0.0 || ^16.0.0
286
286
  - `msw` ^2.0.0
287
287
 
288
288
  ## Quick Start (5 Minutes)
@@ -301,6 +301,7 @@ import type {
301
301
  export const defaultScenario: ScenaristScenario = {
302
302
  id: "default",
303
303
  name: "Default",
304
+ description: "Baseline responses",
304
305
  mocks: [
305
306
  {
306
307
  method: "GET",
@@ -313,6 +314,7 @@ export const defaultScenario: ScenaristScenario = {
313
314
  export const successScenario: ScenaristScenario = {
314
315
  id: "success",
315
316
  name: "API Success",
317
+ description: "User API succeeds",
316
318
  mocks: [
317
319
  {
318
320
  method: "GET",
@@ -336,7 +338,7 @@ import { createScenarist } from "@scenarist/nextjs-adapter/pages"; // or /app
336
338
  import { scenarios } from "./scenarios";
337
339
 
338
340
  export const scenarist = createScenarist({
339
- enabled: process.env.NODE_ENV === "test",
341
+ enabled: true,
340
342
  scenarios, // All scenarios registered upfront
341
343
  });
342
344
 
@@ -376,11 +378,15 @@ if (typeof window === "undefined" && scenarist) {
376
378
  **Pages Router:** Create `pages/api/__scenario__.ts`:
377
379
 
378
380
  ```typescript
381
+ import type { NextApiRequest, NextApiResponse } from "next";
379
382
  import { scenarist } from "@/lib/scenarist";
380
383
 
381
- // In production, scenarist is undefined due to conditional exports
382
- // When the default export is undefined, Next.js treats the route as non-existent
383
- export default scenarist?.createScenarioEndpoint();
384
+ // In production, scenarist is undefined due to conditional exports.
385
+ // Next.js requires a default export function, so fall back to a 405 handler.
386
+ export default scenarist?.createScenarioEndpoint() ??
387
+ ((_req: NextApiRequest, res: NextApiResponse) => {
388
+ res.status(405).end();
389
+ });
384
390
  ```
385
391
 
386
392
  **App Router:** Create `app/api/%5F%5Fscenario%5F%5F/route.ts`:
@@ -391,7 +397,7 @@ export default scenarist?.createScenarioEndpoint();
391
397
  import { scenarist } from "@/lib/scenarist";
392
398
 
393
399
  // In production, scenarist is undefined due to conditional exports
394
- // When exports are undefined, Next.js treats the route as non-existent
400
+ // When the exports are undefined, the route answers 405 Method Not Allowed
395
401
  const handler = scenarist?.createScenarioEndpoint();
396
402
 
397
403
  export const POST = handler;
@@ -408,7 +414,7 @@ afterAll(() => scenarist.stop()); // Stop MSW server
408
414
 
409
415
  it("fetches user successfully", async () => {
410
416
  // Set scenario for this test
411
- await fetch("http://localhost:3000/__scenario__", {
417
+ await fetch("http://localhost:3000/api/__scenario__", {
412
418
  method: "POST",
413
419
  headers: {
414
420
  "x-scenarist-test-id": "test-1",
@@ -445,7 +451,7 @@ it("fetches user successfully", async () => {
445
451
  | ---------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
446
452
  | **Import Path** | `@scenarist/nextjs-adapter/pages` | `@scenarist/nextjs-adapter/app` |
447
453
  | **Setup File** | `pages/api/__scenario__.ts` | `app/api/%5F%5Fscenario%5F%5F/route.ts` \* |
448
- | **Scenario Endpoint** | `export default scenarist.createScenarioEndpoint()` | `const handler = scenarist.createScenarioEndpoint();`<br>`export const POST = handler;`<br>`export const GET = handler;` |
454
+ | **Scenario Endpoint** | `export default scenarist?.createScenarioEndpoint() ?? fallback` | `const handler = scenarist?.createScenarioEndpoint();`<br>`export const POST = handler;`<br>`export const GET = handler;` |
449
455
  | **Core Functionality** | ✅ Same scenarios, same behavior | ✅ Same scenarios, same behavior |
450
456
 
451
457
  \* 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.
@@ -517,7 +523,7 @@ import { createScenarist } from "@scenarist/nextjs-adapter/pages";
517
523
  import { scenarios } from "./scenarios";
518
524
 
519
525
  export const scenarist = createScenarist({
520
- enabled: process.env.NODE_ENV === "test",
526
+ enabled: true,
521
527
  scenarios, // All scenarios registered upfront
522
528
  strictMode: false, // Allow unmocked requests to pass through to real APIs
523
529
  });
@@ -532,11 +538,15 @@ if (typeof window === "undefined" && scenarist) {
532
538
 
533
539
  ```typescript
534
540
  // pages/api/__scenario__.ts
541
+ import type { NextApiRequest, NextApiResponse } from "next";
535
542
  import { scenarist } from "../../lib/scenarist";
536
543
 
537
- // In production, scenarist is undefined due to conditional exports
538
- // When the default export is undefined, Next.js treats the route as non-existent
539
- export default scenarist?.createScenarioEndpoint();
544
+ // In production, scenarist is undefined due to conditional exports.
545
+ // Next.js requires a default export function, so fall back to a 405 handler.
546
+ export default scenarist?.createScenarioEndpoint() ??
547
+ ((_req: NextApiRequest, res: NextApiResponse) => {
548
+ res.status(405).end();
549
+ });
540
550
  ```
541
551
 
542
552
  This single line creates a Next.js API route that handles both GET and POST requests for scenario management.
@@ -554,7 +564,7 @@ describe("User API", () => {
554
564
 
555
565
  it("should return admin user", async () => {
556
566
  // Set scenario for this test
557
- await fetch("http://localhost:3000/__scenario__", {
567
+ await fetch("http://localhost:3000/api/__scenario__", {
558
568
  method: "POST",
559
569
  headers: {
560
570
  "x-scenarist-test-id": "admin-test",
@@ -590,7 +600,7 @@ import { createScenarist } from "@scenarist/nextjs-adapter/app";
590
600
  import { scenarios } from "./scenarios";
591
601
 
592
602
  export const scenarist = createScenarist({
593
- enabled: process.env.NODE_ENV === "test",
603
+ enabled: true,
594
604
  scenarios, // All scenarios registered upfront
595
605
  strictMode: false, // Allow unmocked requests to pass through to real APIs
596
606
  });
@@ -608,7 +618,7 @@ if (typeof window === "undefined" && scenarist) {
608
618
  import { scenarist } from "@/lib/scenarist";
609
619
 
610
620
  // In production, scenarist is undefined due to conditional exports
611
- // When exports are undefined, Next.js treats the route as non-existent
621
+ // When the exports are undefined, the route answers 405 Method Not Allowed
612
622
  const handler = scenarist?.createScenarioEndpoint();
613
623
 
614
624
  export const POST = handler;
@@ -646,9 +656,6 @@ type AdapterOptions<T extends ScenaristScenarios> = {
646
656
  enabled: boolean; // Whether mocking is enabled
647
657
  scenarios: T; // REQUIRED - scenarios object (all scenarios registered upfront)
648
658
  strictMode?: boolean; // Return 501 for unmocked requests (default: false)
649
- headers?: {
650
- testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
651
- };
652
659
  defaultTestId?: string; // Default test ID (default: 'default-test')
653
660
  registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
654
661
  store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
@@ -661,12 +668,11 @@ type AdapterOptions<T extends ScenaristScenarios> = {
661
668
 
662
669
  ```typescript
663
670
  type Scenarist<T extends ScenaristScenarios> = {
664
- config: ScenaristConfig; // Resolved configuration (headers, etc.)
671
+ config: ScenaristConfig; // Resolved configuration (strictMode, defaultTestId, etc.)
665
672
  createScenarioEndpoint: () => Handler; // Creates scenario endpoint handler
666
673
  switchScenario: (
667
674
  testId: string,
668
675
  scenarioId: ScenarioIds<T>,
669
- variant?: string,
670
676
  ) => ScenaristResult<void, Error>;
671
677
  getActiveScenario: (testId: string) => ActiveScenario | undefined;
672
678
  getScenarioById: (
@@ -684,11 +690,15 @@ type Scenarist<T extends ScenaristScenarios> = {
684
690
  Unlike Express, Next.js doesn't have global middleware. Instead, you manually create the scenario endpoint using `createScenarioEndpoint()`:
685
691
 
686
692
  ```typescript
687
- // Pages Router - single default export
688
- export default scenarist.createScenarioEndpoint();
693
+ // Pages Router - single default export, with a 405 fallback because
694
+ // scenarist is undefined in production builds or when enabled is false
695
+ export default scenarist?.createScenarioEndpoint() ??
696
+ ((_req: NextApiRequest, res: NextApiResponse) => {
697
+ res.status(405).end();
698
+ });
689
699
 
690
- // App Router - explicit method exports
691
- const handler = scenarist.createScenarioEndpoint();
700
+ // App Router - explicit method exports (undefined in production builds or when enabled is false, so the route answers 405)
701
+ const handler = scenarist?.createScenarioEndpoint();
692
702
  export const POST = handler;
693
703
  export const GET = handler;
694
704
  ```
@@ -697,14 +707,13 @@ export const GET = handler;
697
707
 
698
708
  The endpoint handler exposes these operations:
699
709
 
700
- #### `POST /__scenario__` - Set Active Scenario
710
+ #### `POST /api/__scenario__` - Set Active Scenario
701
711
 
702
712
  **Request:**
703
713
 
704
714
  ```typescript
705
715
  {
706
716
  scenario: string; // Scenario ID (required)
707
- variant?: string; // Variant name (optional)
708
717
  }
709
718
  ```
710
719
 
@@ -715,14 +724,13 @@ The endpoint handler exposes these operations:
715
724
  success: true;
716
725
  testId: string;
717
726
  scenarioId: string;
718
- variant?: string;
719
727
  }
720
728
  ```
721
729
 
722
730
  **Example:**
723
731
 
724
732
  ```typescript
725
- await fetch("http://localhost:3000/__scenario__", {
733
+ await fetch("http://localhost:3000/api/__scenario__", {
726
734
  method: "POST",
727
735
  headers: {
728
736
  "x-scenarist-test-id": "test-123",
@@ -732,7 +740,7 @@ await fetch("http://localhost:3000/__scenario__", {
732
740
  });
733
741
  ```
734
742
 
735
- #### `GET /__scenario__` - Get Active Scenario
743
+ #### `GET /api/__scenario__` - Get Active Scenario
736
744
 
737
745
  **Response (200):**
738
746
 
@@ -756,7 +764,7 @@ await fetch("http://localhost:3000/__scenario__", {
756
764
  **Example:**
757
765
 
758
766
  ```typescript
759
- const response = await fetch("http://localhost:3000/__scenario__", {
767
+ const response = await fetch("http://localhost:3000/api/__scenario__", {
760
768
  headers: { "x-scenarist-test-id": "test-123" },
761
769
  });
762
770
 
@@ -764,7 +772,7 @@ const data = await response.json();
764
772
  console.log(data.scenarioId); // 'user-logged-in'
765
773
  ```
766
774
 
767
- #### `GET /__scenarist__/state` - Debug State Endpoint
775
+ #### `GET /api/__scenarist__/state` - Debug State Endpoint
768
776
 
769
777
  Inspect the current test state for debugging. Useful when testing multi-stage flows with `afterResponse.setState`.
770
778
 
@@ -780,7 +788,7 @@ Inspect the current test state for debugging. Useful when testing multi-stage fl
780
788
  **Example:**
781
789
 
782
790
  ```typescript
783
- const response = await fetch("http://localhost:3000/__scenarist__/state", {
791
+ const response = await fetch("http://localhost:3000/api/__scenarist__/state", {
784
792
  headers: { "x-scenarist-test-id": "test-123" },
785
793
  });
786
794
 
@@ -794,9 +802,15 @@ console.log(data.state); // { submitted: true, phase: "review" }
794
802
 
795
803
  ```typescript
796
804
  // pages/api/__scenarist__/state.ts
805
+ import type { NextApiRequest, NextApiResponse } from "next";
797
806
  import { scenarist } from "@/lib/scenarist";
798
807
 
799
- export default scenarist?.createStateEndpoint();
808
+ // In production, scenarist is undefined due to conditional exports.
809
+ // Next.js requires a default export function, so fall back to a 405 handler.
810
+ export default scenarist?.createStateEndpoint() ??
811
+ ((_req: NextApiRequest, res: NextApiResponse) => {
812
+ res.status(405).end();
813
+ });
800
814
  ```
801
815
 
802
816
  **App Router:**
@@ -919,7 +933,7 @@ export default async function ProductsPage() {
919
933
  **What these helpers do:**
920
934
 
921
935
  - Extract test ID from request headers (`x-scenarist-test-id` by default)
922
- - Respect your configured `testIdHeaderName` and `defaultTestId`
936
+ - Respect your configured `defaultTestId`
923
937
  - Return object with Scenarist headers ready to spread
924
938
  - Safe to use in production (return empty object when scenarist is undefined)
925
939
 
@@ -963,8 +977,8 @@ Active scenario mocks take precedence; unmocked endpoints fall back to default s
963
977
  const defaultScenario = {
964
978
  id: "default",
965
979
  mocks: [
966
- { method: "GET", url: "*/api/users", response: { status: 200, body: [] } },
967
- { method: "GET", url: "*/api/orders", response: { status: 200, body: [] } },
980
+ { method: "GET", url: "/api/users", response: { status: 200, body: [] } },
981
+ { method: "GET", url: "/api/orders", response: { status: 200, body: [] } },
968
982
  ],
969
983
  };
970
984
 
@@ -972,7 +986,7 @@ const defaultScenario = {
972
986
  const errorScenario = {
973
987
  id: "error",
974
988
  mocks: [
975
- { method: "GET", url: "*/api/users", response: { status: 500 } },
989
+ { method: "GET", url: "/api/users", response: { status: 500 } },
976
990
  // Orders uses default scenario
977
991
  ],
978
992
  };
@@ -982,7 +996,7 @@ const errorScenario = {
982
996
 
983
997
  ## Type-Safe Scenario IDs
984
998
 
985
- TypeScript automatically infers scenario names from your scenarios object, providing autocomplete and compile-time safety.
999
+ The `satisfies ScenaristScenarios` constraint type-checks every scenario definition. For autocomplete and compile-time checking of scenario IDs in tests, pass the same scenarios object to `withScenarios()` from `@scenarist/playwright-helpers`.
986
1000
 
987
1001
  ### How It Works
988
1002
 
@@ -994,10 +1008,10 @@ import type {
994
1008
  } from "@scenarist/nextjs-adapter/pages";
995
1009
 
996
1010
  export const scenarios = {
997
- default: { id: "default", name: "Default", mocks: [] },
998
- success: { id: "success", name: "Success", mocks: [] },
999
- error: { id: "error", name: "Error", mocks: [] },
1000
- timeout: { id: "timeout", name: "Timeout", mocks: [] },
1011
+ default: { id: "default", name: "Default", description: "", mocks: [] },
1012
+ success: { id: "success", name: "Success", description: "", mocks: [] },
1013
+ error: { id: "error", name: "Error", description: "", mocks: [] },
1014
+ timeout: { id: "timeout", name: "Timeout", description: "", mocks: [] },
1001
1015
  } as const satisfies ScenaristScenarios;
1002
1016
 
1003
1017
  // lib/scenarist.ts
@@ -1013,18 +1027,25 @@ export const scenarist = createScenarist({
1013
1027
  ### Type Safety Benefits
1014
1028
 
1015
1029
  ```typescript
1016
- // ✅ Valid - TypeScript knows about these scenario IDs
1017
- scenarist.switchScenario("test-123", "success");
1018
- scenarist.switchScenario("test-123", "error");
1019
- scenarist.switchScenario("test-123", "timeout");
1030
+ // tests/fixtures.ts
1031
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
1032
+ import { scenarios } from "../lib/scenarios";
1020
1033
 
1021
- // ❌ TypeScript error - 'invalid-name' is not a valid scenario ID
1022
- scenarist.switchScenario("test-123", "invalid-name");
1023
- // ^^^^^^^^^^^^^^
1024
- // Argument of type '"invalid-name"' is not assignable to parameter of type
1025
- // '"default" | "success" | "error" | "timeout"'
1034
+ export const test = withScenarios(scenarios);
1035
+ export { expect };
1036
+
1037
+ // tests/example.spec.ts
1038
+ test("switches scenario", async ({ page, switchScenario }) => {
1039
+ // ✅ Valid - TypeScript knows about these scenario IDs
1040
+ await switchScenario(page, "success");
1041
+
1042
+ // ❌ TypeScript error - 'invalid-name' is not a valid scenario ID
1043
+ await switchScenario(page, "invalid-name");
1044
+ });
1026
1045
  ```
1027
1046
 
1047
+ **Note:** `scenarist.switchScenario()` on the Next.js adapter instance accepts any `string` scenario ID; an unknown ID returns an error result at runtime rather than a compile-time error.
1048
+
1028
1049
  ### In Tests
1029
1050
 
1030
1051
  ```typescript
@@ -1032,7 +1053,7 @@ scenarist.switchScenario("test-123", "invalid-name");
1032
1053
  import { scenarios } from "./scenarios";
1033
1054
 
1034
1055
  // ✅ Type-safe scenario switching
1035
- await fetch("http://localhost:3000/__scenario__", {
1056
+ await fetch("http://localhost:3000/api/__scenario__", {
1036
1057
  method: "POST",
1037
1058
  headers: {
1038
1059
  "x-scenarist-test-id": "test-1",
@@ -1042,7 +1063,7 @@ await fetch("http://localhost:3000/__scenario__", {
1042
1063
  });
1043
1064
 
1044
1065
  // Or reference by object key for refactor-safety
1045
- await fetch("http://localhost:3000/__scenario__", {
1066
+ await fetch("http://localhost:3000/api/__scenario__", {
1046
1067
  method: "POST",
1047
1068
  headers: {
1048
1069
  "x-scenarist-test-id": "test-1",
@@ -1070,18 +1091,14 @@ Create helper functions to reduce boilerplate:
1070
1091
  // tests/helpers.ts
1071
1092
  const API_BASE = "http://localhost:3000";
1072
1093
 
1073
- export const setScenario = async (
1074
- testId: string,
1075
- scenario: string,
1076
- variant?: string,
1077
- ) => {
1078
- await fetch(`${API_BASE}/__scenario__`, {
1094
+ export const setScenario = async (testId: string, scenario: string) => {
1095
+ await fetch(`${API_BASE}/api/__scenario__`, {
1079
1096
  method: "POST",
1080
1097
  headers: {
1081
1098
  "x-scenarist-test-id": testId,
1082
1099
  "content-type": "application/json",
1083
1100
  },
1084
- body: JSON.stringify({ scenario, variant }),
1101
+ body: JSON.stringify({ scenario }),
1085
1102
  });
1086
1103
  };
1087
1104
 
@@ -1151,65 +1168,43 @@ describe("API Tests", () => {
1151
1168
 
1152
1169
  **⚠️ Security Warning:** Only enable scenario endpoints in development/test environments, **NEVER in production**.
1153
1170
 
1154
- **Why?** The `/__scenario__` endpoint allows arbitrary mock switching, which could be exploited in production to bypass security, fake data, or cause unexpected behavior.
1155
-
1156
- **Safe configuration:**
1157
-
1158
- ```typescript
1159
- // lib/scenarist.ts
1160
- // ✅ CORRECT - Only enabled in safe environments
1161
- const scenarist = createScenarist({
1162
- enabled:
1163
- process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test",
1164
- scenarios,
1165
- strictMode: false,
1166
- });
1171
+ **Why?** The `/api/__scenario__` endpoint allows arbitrary mock switching, which could be exploited in production to bypass security, fake data, or cause unexpected behavior.
1167
1172
 
1168
- // ❌ WRONG - Dangerous in production
1169
- const scenarist = createScenarist({
1170
- enabled: true, // Always on, including production!
1171
- scenarios,
1172
- });
1173
- ```
1173
+ **How production is protected:** production builds resolve `@scenarist/nextjs-adapter/app` and `/pages` to entry points where `createScenarist()` returns `undefined`, so the scenario route has no working handler (App Router route handlers are undefined and answer 405; Pages Router routes use a 405 fallback) (see [Production Tree-Shaking](#production-tree-shaking)). `createScenarist()` also returns `undefined` when `enabled` is `false`, so the same holds in development and test.
1174
1174
 
1175
1175
  **Production checklist:**
1176
1176
 
1177
- - ✅ `enabled` is conditional (never hardcoded `true`)
1178
- - ✅ Environment checks use `process.env.NODE_ENV`
1179
- - ✅ `/__scenario__` endpoints not exposed in production builds
1177
+ - ✅ App Router route files use `scenarist?.createScenarioEndpoint()`, so their handlers are undefined in production
1178
+ - ✅ Pages Router route files add a 405 fallback (`scenarist?.createScenarioEndpoint() ?? fallback`), because Next.js requires a default export function
1179
+ - ✅ Production builds run with `NODE_ENV=production` (`next build`)
1180
+ - ✅ `/api/__scenario__` endpoints not exposed in production builds
1180
1181
 
1181
1182
  **During development**, manually switch scenarios with curl:
1182
1183
 
1183
1184
  ```bash
1184
1185
  # Switch to error scenario
1185
- curl -X POST http://localhost:3000/__scenario__ \
1186
+ curl -X POST http://localhost:3000/api/__scenario__ \
1186
1187
  -H "Content-Type: application/json" \
1187
1188
  -d '{"scenario": "payment-declined"}'
1188
1189
 
1189
1190
  # Check active scenario
1190
- curl http://localhost:3000/__scenario__
1191
+ curl http://localhost:3000/api/__scenario__
1191
1192
  ```
1192
1193
 
1193
1194
  ## Configuration
1194
1195
 
1195
1196
  ### Environment-Specific
1196
1197
 
1198
+ Next.js replaces `process.env.NODE_ENV` in your code with `'development'` under `next dev` and `'production'` under `next build`, even when you start it with `NODE_ENV=test`. Gating `enabled` on `process.env.NODE_ENV === "test"` therefore never passes and disables Scenarist. Use `enabled: true`: production builds resolve the `production` export condition, so `createScenarist()` returns `undefined` there anyway.
1199
+
1197
1200
  ```typescript
1198
- // Test-only
1201
+ // Recommended: active under next dev, absent from production builds
1199
1202
  const scenarist = createScenarist({
1200
- enabled: process.env.NODE_ENV === "test",
1203
+ enabled: true,
1201
1204
  scenarios,
1202
1205
  strictMode: true, // Fail if any unmocked request
1203
1206
  });
1204
1207
 
1205
- // Development and test
1206
- const scenarist = createScenarist({
1207
- enabled:
1208
- process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development",
1209
- scenarios,
1210
- strictMode: false, // Allow passthrough to real APIs
1211
- });
1212
-
1213
1208
  // Opt-in with environment variable
1214
1209
  const scenarist = createScenarist({
1215
1210
  enabled: process.env.ENABLE_MOCKING === "true",
@@ -1256,7 +1251,7 @@ const testScenarios = {
1256
1251
  } as const satisfies ScenaristScenarios;
1257
1252
 
1258
1253
  const scenarist = createScenarist({
1259
- enabled: process.env.NODE_ENV === "test",
1254
+ enabled: true,
1260
1255
  scenarios: testScenarios,
1261
1256
  strictMode: true, // Fail loudly if any endpoint isn't mocked
1262
1257
  });
@@ -1274,18 +1269,6 @@ const scenarist = createScenarist({
1274
1269
  - Request for unmocked endpoint → Passes through to real API 🌐
1275
1270
  - Useful for incremental mocking in development
1276
1271
 
1277
- ### Custom Headers
1278
-
1279
- ```typescript
1280
- const scenarist = createScenarist({
1281
- enabled: true,
1282
- scenarios,
1283
- headers: {
1284
- testId: "x-my-test-id",
1285
- },
1286
- });
1287
- ```
1288
-
1289
1272
  ## Logging & Debugging
1290
1273
 
1291
1274
  Scenarist includes a flexible logging system for debugging scenario matching, state management, and request handling. Logging is **disabled by default** and must be explicitly enabled. For comprehensive documentation including log categories, custom loggers, and Vitest configuration, see the [full logging guide](https://scenarist.io/reference/logging).
@@ -1306,7 +1289,7 @@ import {
1306
1289
  } from "@scenarist/nextjs-adapter/pages";
1307
1290
 
1308
1291
  export const scenarist = createScenarist({
1309
- enabled: process.env.NODE_ENV === "test",
1292
+ enabled: true,
1310
1293
  scenarios,
1311
1294
 
1312
1295
  // Enable logging with pretty format
@@ -1348,7 +1331,7 @@ const parseLogFormat = (value: string | undefined): LogFormat =>
1348
1331
  LOG_FORMATS.includes(value as LogFormat) ? (value as LogFormat) : "pretty";
1349
1332
 
1350
1333
  export const scenarist = createScenarist({
1351
- enabled: process.env.NODE_ENV === "test",
1334
+ enabled: true,
1352
1335
  scenarios,
1353
1336
 
1354
1337
  // Enable via SCENARIST_LOG=1 environment variable
@@ -1461,7 +1444,7 @@ await setScenario("test-1", "my-scenario"); // ✅ Now works
1461
1444
 
1462
1445
  **Problem:** Type errors with Next.js request/response types.
1463
1446
 
1464
- **Solution:** Ensure your `next` peer dependency version matches the adapter's supported versions (^14.0.0 || ^15.0.0).
1447
+ **Solution:** Ensure your `next` peer dependency version matches the adapter's supported versions (^14.0.0 || ^15.0.0 || ^16.0.0).
1465
1448
 
1466
1449
  ## TypeScript
1467
1450
 
@@ -1555,7 +1538,7 @@ import {
1555
1538
 
1556
1539
  ### How It Works
1557
1540
 
1558
- When `NODE_ENV=production`, bundlers (Next.js webpack/Turbopack, esbuild, Vite, etc.) automatically resolve to production entry points that return `undefined` with **zero imports**:
1541
+ When the bundler resolves the `"production"` export condition (Next.js production builds do this automatically; custom bundlers need configuring, see below), imports resolve to production entry points that return `undefined` with **zero imports**:
1559
1542
 
1560
1543
  ```typescript
1561
1544
  // Production build imports this instead:
@@ -1702,8 +1685,8 @@ MIT
1702
1685
 
1703
1686
  ## Related Packages
1704
1687
 
1705
- - **[@scenarist/core](../core)** - Core scenario management
1688
+ - **[@scenarist/core](../../internal/core)** - Core scenario management
1706
1689
  - **[@scenarist/express-adapter](../express-adapter)** - Express.js adapter
1707
- - **[@scenarist/msw-adapter](../msw-adapter)** - MSW integration (used internally)
1690
+ - **[@scenarist/msw-adapter](../../internal/msw-adapter)** - MSW integration (used internally)
1708
1691
 
1709
1692
  **Note:** The MSW adapter is used internally by this package. Users of `@scenarist/nextjs-adapter` don't need to interact with it directly.
@@ -97,5 +97,5 @@ export type AppScenarist = Omit<ScenaristAdapter<never>, "middleware"> & {
97
97
  * }
98
98
  * ```
99
99
  */
100
- export declare const createScenaristImpl: (options: AppAdapterOptions) => AppScenarist;
100
+ export declare const createScenaristImpl: (options: AppAdapterOptions) => AppScenarist | undefined;
101
101
  //# sourceMappingURL=impl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/app/impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACd,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE7E;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,oBAAoB,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAEvD,IAAI,iBAAiB,EAAE,aAAa,GAAG,SAAS,CAAC;IAEjD,IAAI,oBAAoB,EAAE,YAAY,GAAG,SAAS,CAAC;CACpD;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,GAAG;IACvE;;;;;;;;;;;;OAYG;IACH,sBAAsB,EAAE,MAAM,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;IAExE;;;;;;;;;;OAUG;IACH,mBAAmB,EAAE,MAAM,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,iBAAiB,KACzB,YA2CF,CAAC"}
1
+ {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/app/impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACd,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE7E;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,oBAAoB,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAEvD,IAAI,iBAAiB,EAAE,aAAa,GAAG,SAAS,CAAC;IAEjD,IAAI,oBAAoB,EAAE,YAAY,GAAG,SAAS,CAAC;CACpD;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,GAAG;IACvE;;;;;;;;;;;;OAYG;IACH,sBAAsB,EAAE,MAAM,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;IAExE;;;;;;;;;;OAUG;IACH,mBAAmB,EAAE,MAAM,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,iBAAiB,KACzB,YAAY,GAAG,SA+CjB,CAAC"}
package/dist/app/impl.js CHANGED
@@ -37,6 +37,9 @@ import { createScenarioEndpoint, createStateEndpoint } from "./endpoints.js";
37
37
  * ```
38
38
  */
39
39
  export const createScenaristImpl = (options) => {
40
+ if (!options.enabled) {
41
+ return undefined;
42
+ }
40
43
  // Singleton guard - return existing instance if already created
41
44
  // This prevents duplicate scenario registration errors when Next.js creates multiple module instances
42
45
  if (global.__scenarist_instance) {
@@ -279,4 +279,13 @@ describe("App Router production entry point", () => {
279
279
  expect(testId1).toBe(testId2);
280
280
  });
281
281
  });
282
+ describe("createConsoleLogger", () => {
283
+ it("should return undefined (logging disabled in production)", () => {
284
+ const logger = production.createConsoleLogger({
285
+ level: "debug",
286
+ format: "pretty",
287
+ });
288
+ expect(logger).toBeUndefined();
289
+ });
290
+ });
282
291
  });
@@ -1,4 +1,4 @@
1
- import { type BaseAdapterOptions, type ScenaristConfig, type ScenarioManager, type ResponseSelector } from "@scenarist/core";
1
+ import { type BaseAdapterOptions, type ScenaristConfig, type ScenarioManager, type ScenarioRegistry, type ScenarioStore, type ResponseSelector } from "@scenarist/core";
2
2
  import { type SharedMswServer } from "@scenarist/msw-adapter";
3
3
  /**
4
4
  * Shared setup logic for both Pages Router and App Router adapters.
@@ -21,12 +21,15 @@ export type ScenaristBaseSetup = {
21
21
  *
22
22
  * Follows hexagonal architecture:
23
23
  * - Accepts optional port implementations via dependency injection
24
- * - Uses in-memory defaults if not provided
24
+ * - Requires the injected registry and store; state manager and sequence tracker default to in-memory
25
25
  * - Sets up MSW dynamic handler with response selector
26
26
  * - Initializes MSW server
27
27
  *
28
28
  * @param options - Adapter configuration options
29
29
  * @returns Shared setup objects for both router implementations
30
30
  */
31
- export declare const createScenaristBase: (options: BaseAdapterOptions) => ScenaristBaseSetup;
31
+ export declare const createScenaristBase: (options: BaseAdapterOptions & {
32
+ readonly registry: ScenarioRegistry;
33
+ readonly store: ScenarioStore;
34
+ }) => ScenaristBaseSetup;
32
35
  //# sourceMappingURL=create-scenarist-base.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-scenarist-base.d.ts","sourceRoot":"","sources":["../../src/common/create-scenarist-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAUL,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,wBAAwB,CAAC;AAEhC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,QAAQ,CAAC,aAAa,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3C,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,kBAAkB,KAC1B,kBAyDF,CAAC"}
1
+ {"version":3,"file":"create-scenarist-base.d.ts","sourceRoot":"","sources":["../../src/common/create-scenarist-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,wBAAwB,CAAC;AAEhC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,QAAQ,CAAC,aAAa,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3C,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,kBAAkB,GAAG;IAC5B,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;CAC/B,KACA,kBAuDF,CAAC"}
@@ -1,11 +1,11 @@
1
- import { buildConfig, createScenarioManager, createResponseSelector, InMemoryScenarioRegistry, InMemoryScenarioStore, createInMemorySequenceTracker, createInMemoryStateManager, noOpLogger, SCENARIST_TEST_ID_HEADER, } from "@scenarist/core";
1
+ import { buildConfig, createScenarioManager, createResponseSelector, createInMemorySequenceTracker, createInMemoryStateManager, noOpLogger, SCENARIST_TEST_ID_HEADER, } from "@scenarist/core";
2
2
  import { createSharedMswServer, } from "@scenarist/msw-adapter";
3
3
  /**
4
4
  * Creates the base Scenarist setup shared by both Pages and App Router.
5
5
  *
6
6
  * Follows hexagonal architecture:
7
7
  * - Accepts optional port implementations via dependency injection
8
- * - Uses in-memory defaults if not provided
8
+ * - Requires the injected registry and store; state manager and sequence tracker default to in-memory
9
9
  * - Sets up MSW dynamic handler with response selector
10
10
  * - Initializes MSW server
11
11
  *
@@ -15,11 +15,7 @@ import { createSharedMswServer, } from "@scenarist/msw-adapter";
15
15
  export const createScenaristBase = (options) => {
16
16
  const config = buildConfig(options);
17
17
  const logger = options.logger ?? noOpLogger;
18
- // Use injected ports or in-memory defaults
19
- // Note: registry/store fallback branches are exercised via singleton pattern in impl.ts
20
- // (globals pass these through, but v8 coverage can't trace that execution path)
21
- const registry = options.registry ?? new InMemoryScenarioRegistry();
22
- const store = options.store ?? new InMemoryScenarioStore();
18
+ const { registry, store } = options;
23
19
  const stateManager = options.stateManager ?? createInMemoryStateManager();
24
20
  const sequenceTracker = options.sequenceTracker ?? createInMemorySequenceTracker();
25
21
  // Create scenario manager with all dependencies
@@ -53,6 +49,8 @@ export const createScenaristBase = (options) => {
53
49
  getScenarioDefinition: (scenarioId) => manager.getScenarioById(scenarioId),
54
50
  strictMode: config.strictMode,
55
51
  responseSelector,
52
+ errorBehaviors: config.errorBehaviors,
53
+ logger,
56
54
  });
57
55
  return {
58
56
  config,
@@ -93,5 +93,5 @@ export type PagesScenarist = Omit<ScenaristAdapter<never>, "middleware"> & {
93
93
  * }
94
94
  * ```
95
95
  */
96
- export declare const createScenaristImpl: (options: PagesAdapterOptions) => PagesScenarist;
96
+ export declare const createScenaristImpl: (options: PagesAdapterOptions) => PagesScenarist | undefined;
97
97
  //# sourceMappingURL=impl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/pages/impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACd,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE7E;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,0BAA0B,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAE7D,IAAI,uBAAuB,EAAE,aAAa,GAAG,SAAS,CAAC;IAEvD,IAAI,0BAA0B,EAAE,cAAc,GAAG,SAAS,CAAC;CAC5D;AAED;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG,kBAAkB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,GAAG;IACzE;;;;;;;;;;OAUG;IACH,sBAAsB,EAAE,MAAM,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;IAExE;;;;;;;;;;OAUG;IACH,mBAAmB,EAAE,MAAM,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,mBAAmB,KAC3B,cA2CF,CAAC"}
1
+ {"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/pages/impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACd,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE7E;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,0BAA0B,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAE7D,IAAI,uBAAuB,EAAE,aAAa,GAAG,SAAS,CAAC;IAEvD,IAAI,0BAA0B,EAAE,cAAc,GAAG,SAAS,CAAC;CAC5D;AAED;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG,kBAAkB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,GAAG;IACzE;;;;;;;;;;OAUG;IACH,sBAAsB,EAAE,MAAM,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;IAExE;;;;;;;;;;OAUG;IACH,mBAAmB,EAAE,MAAM,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,mBAAmB,KAC3B,cAAc,GAAG,SA+CnB,CAAC"}
@@ -35,6 +35,9 @@ import { createScenarioEndpoint, createStateEndpoint } from "./endpoints.js";
35
35
  * ```
36
36
  */
37
37
  export const createScenaristImpl = (options) => {
38
+ if (!options.enabled) {
39
+ return undefined;
40
+ }
38
41
  // Singleton guard - return existing instance if already created
39
42
  // This prevents duplicate scenario registration errors when Next.js creates multiple module instances
40
43
  if (global.__scenarist_instance_pages) {
@@ -331,4 +331,13 @@ describe("Pages Router production entry point", () => {
331
331
  });
332
332
  });
333
333
  });
334
+ describe("createConsoleLogger", () => {
335
+ it("should return undefined (logging disabled in production)", () => {
336
+ const logger = production.createConsoleLogger({
337
+ level: "debug",
338
+ format: "pretty",
339
+ });
340
+ expect(logger).toBeUndefined();
341
+ });
342
+ });
334
343
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenarist/nextjs-adapter",
3
- "version": "0.4.14",
3
+ "version": "0.5.0",
4
4
  "description": "Next.js adapter for Scenarist (Pages Router and App Router)",
5
5
  "author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
6
6
  "license": "MIT",
@@ -58,24 +58,24 @@
58
58
  "LICENSE"
59
59
  ],
60
60
  "dependencies": {
61
- "zod": "^4.3.6",
62
- "@scenarist/core": "0.4.14",
63
- "@scenarist/msw-adapter": "0.4.14"
61
+ "@scenarist/core": "0.5.0",
62
+ "@scenarist/msw-adapter": "0.5.0",
63
+ "zod": "^4.6.5"
64
64
  },
65
65
  "peerDependencies": {
66
66
  "msw": "^2.0.0",
67
67
  "next": "^14.0.0 || ^15.0.0 || ^16.0.0"
68
68
  },
69
69
  "devDependencies": {
70
- "@types/node": "^25.3.0",
71
- "@vitest/coverage-v8": "^4.1.5",
72
- "eslint": "^9.39.4",
73
- "msw": "^2.12.10",
74
- "next": "^16.2.6",
75
- "typescript": "^5.9.3",
76
- "vitest": "^4.1.5",
77
70
  "@scenarist/eslint-config": "^0.0.0",
78
- "@scenarist/typescript-config": "0.0.0"
71
+ "@scenarist/typescript-config": "0.0.0",
72
+ "@types/node": "^25.9.8",
73
+ "@vitest/coverage-v8": "^5.0.1",
74
+ "eslint": "^9.39.5",
75
+ "msw": "^2.15.0",
76
+ "next": "^16.3.5",
77
+ "typescript": "^6.0.3",
78
+ "vitest": "^5.0.1"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc",