@uiwwsw/next-test-mode 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -0
  4. package/bin/test-mode.mjs +164 -0
  5. package/dist/browser.d.ts +7 -0
  6. package/dist/browser.d.ts.map +1 -0
  7. package/dist/browser.js +455 -0
  8. package/dist/browser.js.map +1 -0
  9. package/dist/client.d.ts +14 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +92 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/core.d.ts +160 -0
  14. package/dist/core.d.ts.map +1 -0
  15. package/dist/core.js +741 -0
  16. package/dist/core.js.map +1 -0
  17. package/dist/fetch.d.ts +16 -0
  18. package/dist/fetch.d.ts.map +1 -0
  19. package/dist/fetch.js +212 -0
  20. package/dist/fetch.js.map +1 -0
  21. package/dist/index.d.ts +6 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +6 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/internal/draft-handler.d.ts +30 -0
  26. package/dist/internal/draft-handler.d.ts.map +1 -0
  27. package/dist/internal/draft-handler.js +80 -0
  28. package/dist/internal/draft-handler.js.map +1 -0
  29. package/dist/internal/lifecycle.d.ts +7 -0
  30. package/dist/internal/lifecycle.d.ts.map +1 -0
  31. package/dist/internal/lifecycle.js +65 -0
  32. package/dist/internal/lifecycle.js.map +1 -0
  33. package/dist/internal/next-request.d.ts +11 -0
  34. package/dist/internal/next-request.d.ts.map +1 -0
  35. package/dist/internal/next-request.js +22 -0
  36. package/dist/internal/next-request.js.map +1 -0
  37. package/dist/internal/overrides.d.ts +25 -0
  38. package/dist/internal/overrides.d.ts.map +1 -0
  39. package/dist/internal/overrides.js +111 -0
  40. package/dist/internal/overrides.js.map +1 -0
  41. package/dist/internal/paths.d.ts +3 -0
  42. package/dist/internal/paths.d.ts.map +1 -0
  43. package/dist/internal/paths.js +22 -0
  44. package/dist/internal/paths.js.map +1 -0
  45. package/dist/internal/server-context.d.ts +4 -0
  46. package/dist/internal/server-context.d.ts.map +1 -0
  47. package/dist/internal/server-context.js +6 -0
  48. package/dist/internal/server-context.js.map +1 -0
  49. package/dist/internal/ssr-state.d.ts +8 -0
  50. package/dist/internal/ssr-state.d.ts.map +1 -0
  51. package/dist/internal/ssr-state.js +48 -0
  52. package/dist/internal/ssr-state.js.map +1 -0
  53. package/dist/internal/storage.d.ts +6 -0
  54. package/dist/internal/storage.d.ts.map +1 -0
  55. package/dist/internal/storage.js +70 -0
  56. package/dist/internal/storage.js.map +1 -0
  57. package/dist/internal/symbols.d.ts +3 -0
  58. package/dist/internal/symbols.d.ts.map +1 -0
  59. package/dist/internal/symbols.js +3 -0
  60. package/dist/internal/symbols.js.map +1 -0
  61. package/dist/next.d.ts +9 -0
  62. package/dist/next.d.ts.map +1 -0
  63. package/dist/next.js +32 -0
  64. package/dist/next.js.map +1 -0
  65. package/dist/node.d.ts +27 -0
  66. package/dist/node.d.ts.map +1 -0
  67. package/dist/node.js +144 -0
  68. package/dist/node.js.map +1 -0
  69. package/dist/server.d.ts +20 -0
  70. package/dist/server.d.ts.map +1 -0
  71. package/dist/server.js +36 -0
  72. package/dist/server.js.map +1 -0
  73. package/dist/setup.d.ts +14 -0
  74. package/dist/setup.d.ts.map +1 -0
  75. package/dist/setup.js +66 -0
  76. package/dist/setup.js.map +1 -0
  77. package/dist/types.d.ts +179 -0
  78. package/dist/types.d.ts.map +1 -0
  79. package/dist/types.js +2 -0
  80. package/dist/types.js.map +1 -0
  81. package/docs/architecture.md +116 -0
  82. package/docs/guide.md +171 -0
  83. package/docs/migration.md +26 -0
  84. package/docs/releasing.md +41 -0
  85. package/docs/server-rendering.md +136 -0
  86. package/docs/story-test-design.md +252 -0
  87. package/package.json +136 -0
  88. package/src/browser.ts +593 -0
  89. package/src/client.ts +114 -0
  90. package/src/core.ts +1161 -0
  91. package/src/fetch.ts +271 -0
  92. package/src/index.ts +5 -0
  93. package/src/internal/draft-handler.ts +113 -0
  94. package/src/internal/lifecycle.ts +81 -0
  95. package/src/internal/next-request.ts +31 -0
  96. package/src/internal/overrides.ts +141 -0
  97. package/src/internal/paths.ts +27 -0
  98. package/src/internal/server-context.ts +6 -0
  99. package/src/internal/ssr-state.ts +48 -0
  100. package/src/internal/storage.ts +75 -0
  101. package/src/internal/symbols.ts +2 -0
  102. package/src/next.ts +49 -0
  103. package/src/node.ts +213 -0
  104. package/src/server.ts +52 -0
  105. package/src/setup.ts +69 -0
  106. package/src/types.ts +240 -0
  107. package/templates/test-mode/README.md +30 -0
  108. package/templates/test-mode/config.ts +25 -0
  109. package/templates/test-mode/features/auth.ts +23 -0
  110. package/templates/test-mode/index.ts +11 -0
  111. package/templates/test-mode/install.ts +13 -0
  112. package/templates/test-mode/stories/auth.stories.ts +10 -0
package/src/core.ts ADDED
@@ -0,0 +1,1161 @@
1
+ import type {
2
+ TestModeLogger,
3
+ MockResult,
4
+ MockHttpResult,
5
+ MockPassThrough,
6
+ MockContext,
7
+ MockHandler,
8
+ PatchHandler,
9
+ RouteMatcher,
10
+ MockDefinition,
11
+ PatchDefinition,
12
+ RegisteredMockDefinition,
13
+ RegisteredPatchDefinition,
14
+ TestModeRequest,
15
+ TestModePatchRequest,
16
+ FeatureCatalogItem,
17
+ StoryDefinition,
18
+ StoryListOptions,
19
+ StoryListInput,
20
+ StoryCatalogItem,
21
+ TestModeSearchOptions,
22
+ TestModeSearchInput,
23
+ TestModeSearchResult,
24
+ TestModeOptions,
25
+ ResponseOverrideOptions,
26
+ } from "./types.js";
27
+ import { MOCK_RESULT, MOCK_PASS_THROUGH } from "./internal/symbols.js";
28
+ import { normalizePath, parseInputList } from "./internal/paths.js";
29
+ import {
30
+ parseStoredPaths,
31
+ readCookieValue,
32
+ writeCookie,
33
+ readBrowserStorage,
34
+ writeBrowserStorage,
35
+ } from "./internal/storage.js";
36
+
37
+ import { ResponseOverrides } from "./internal/overrides.js";
38
+
39
+ export { normalizePath } from "./internal/paths.js";
40
+ export type * from "./types.js";
41
+
42
+ const DEFAULT_STORAGE_KEY = "test-mode.entries";
43
+ const DEFAULT_CHANGE_EVENT = "test-mode:change";
44
+ const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
45
+
46
+ type RuntimeDefinition = Readonly<{
47
+ caseKey?: string;
48
+ description?: string;
49
+ handler: MockHandler | PatchHandler;
50
+ key: string;
51
+ match?: RouteMatcher;
52
+ method?: readonly string[];
53
+ mode: "mock" | "patch";
54
+ pages: readonly string[];
55
+ path: string;
56
+ }>;
57
+
58
+ type ActiveEntry = Readonly<{
59
+ caseKey?: string;
60
+ path: string;
61
+ serialized: string;
62
+ }>;
63
+
64
+ const readNodeEnv = () =>
65
+ (globalThis as { process?: { env?: Record<string, string | undefined> } })
66
+ .process?.env?.NODE_ENV;
67
+
68
+ const defaultEnabled = () =>
69
+ ["development", "test"].includes(readNodeEnv() ?? "");
70
+
71
+ const createPathCandidates = (path: string) => {
72
+ const normalizedPath = normalizePath(path);
73
+
74
+ if (!normalizedPath) {
75
+ return [];
76
+ }
77
+
78
+ const withoutApiPrefix = normalizedPath.replace(/^\/api(?=\/)/, "");
79
+
80
+ return Array.from(
81
+ new Set([normalizedPath, withoutApiPrefix, `/api${withoutApiPrefix}`]),
82
+ );
83
+ };
84
+
85
+ const serializeEntry = (path: string, caseKey?: string) => {
86
+ const normalizedPath = normalizePath(path);
87
+
88
+ return caseKey
89
+ ? `${normalizedPath}:${encodeURIComponent(caseKey)}`
90
+ : normalizedPath;
91
+ };
92
+
93
+ export const entry = serializeEntry;
94
+
95
+ const parseEntry = (value: string): ActiveEntry | null => {
96
+ const normalizedValue = normalizePath(value);
97
+
98
+ if (!normalizedValue) {
99
+ return null;
100
+ }
101
+
102
+ const separatorIndex = normalizedValue.lastIndexOf(":");
103
+
104
+ if (separatorIndex <= 0) {
105
+ return {
106
+ path: normalizedValue,
107
+ serialized: normalizedValue,
108
+ };
109
+ }
110
+
111
+ const path = normalizedValue.slice(0, separatorIndex);
112
+ let caseKey: string;
113
+ try {
114
+ caseKey = decodeURIComponent(
115
+ normalizedValue.slice(separatorIndex + 1).trim(),
116
+ );
117
+ } catch {
118
+ return null;
119
+ }
120
+
121
+ if (!path || !caseKey) {
122
+ return {
123
+ path: normalizedValue,
124
+ serialized: normalizedValue,
125
+ };
126
+ }
127
+
128
+ return {
129
+ caseKey,
130
+ path,
131
+ serialized: serializeEntry(path, caseKey),
132
+ };
133
+ };
134
+
135
+ const isSamePath = (left: string, right: string) => {
136
+ const leftCandidates = createPathCandidates(left);
137
+ const rightCandidates = createPathCandidates(right);
138
+
139
+ return leftCandidates.some((candidate) =>
140
+ rightCandidates.includes(candidate),
141
+ );
142
+ };
143
+
144
+ const escapeRegExp = (value: string) =>
145
+ value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
146
+
147
+ const routePatternToRegExp = (pattern: string) =>
148
+ new RegExp(
149
+ `^${normalizePath(pattern)
150
+ .split("/")
151
+ .map((segment) => {
152
+ if (segment === "*") {
153
+ return ".*";
154
+ }
155
+
156
+ if (segment.startsWith(":")) {
157
+ return "[^/]+";
158
+ }
159
+
160
+ return escapeRegExp(segment).replace(/\\\*/g, ".*");
161
+ })
162
+ .join("/")}$`,
163
+ );
164
+
165
+ const doesPathMatch = (pattern: string, path: string) => {
166
+ if (!pattern.includes(":") && !pattern.includes("*")) {
167
+ return isSamePath(pattern, path);
168
+ }
169
+
170
+ const matcher = routePatternToRegExp(pattern);
171
+
172
+ return createPathCandidates(path).some((candidate) =>
173
+ matcher.test(candidate),
174
+ );
175
+ };
176
+
177
+ const normalizeMethods = (method: readonly string[] | string | undefined) => {
178
+ if (!method) {
179
+ return undefined;
180
+ }
181
+
182
+ const methods = (Array.isArray(method) ? method : [method])
183
+ .map((item) => item.trim().toUpperCase())
184
+ .filter(Boolean);
185
+
186
+ return methods.length > 0 ? methods : undefined;
187
+ };
188
+
189
+ const methodsOverlap = (
190
+ left: readonly string[] | undefined,
191
+ right: readonly string[] | undefined,
192
+ ) => {
193
+ if (!left || !right) {
194
+ return true;
195
+ }
196
+
197
+ return left.some((method) => right.includes(method));
198
+ };
199
+
200
+ const isMockHttpResult = (value: unknown): value is MockHttpResult =>
201
+ typeof value === "object" &&
202
+ value !== null &&
203
+ (value as Partial<MockHttpResult>)[MOCK_RESULT] === true;
204
+
205
+ const isMockPassThrough = (value: unknown): value is MockPassThrough =>
206
+ typeof value === "object" &&
207
+ value !== null &&
208
+ (value as Partial<MockPassThrough>)[MOCK_PASS_THROUGH] === true;
209
+
210
+ export const httpResult = (result: MockResult): MockHttpResult => ({
211
+ ...result,
212
+ [MOCK_RESULT]: true,
213
+ });
214
+
215
+ export const passThrough = (): MockPassThrough => ({
216
+ [MOCK_PASS_THROUGH]: true,
217
+ });
218
+
219
+ export const defineMock = <TRequest = unknown, TResponse = unknown>(
220
+ path: string,
221
+ handler: MockHandler<TRequest, TResponse>,
222
+ options: Omit<MockDefinition<TRequest, TResponse>, "handler" | "path"> = {},
223
+ ): MockDefinition<TRequest, TResponse> => ({
224
+ ...options,
225
+ handler,
226
+ path: normalizePath(path),
227
+ });
228
+
229
+ export const definePatch = <TRequest = unknown, TResponse = unknown>(
230
+ path: string,
231
+ handler: PatchHandler<TRequest, TResponse>,
232
+ options: Omit<PatchDefinition<TRequest, TResponse>, "handler" | "path"> = {},
233
+ ): PatchDefinition<TRequest, TResponse> => ({
234
+ ...options,
235
+ handler,
236
+ path: normalizePath(path),
237
+ });
238
+
239
+ export const defineStory = (
240
+ story: Readonly<{
241
+ description: string;
242
+ entries: readonly string[];
243
+ key: string;
244
+ pages?: readonly string[];
245
+ title: string;
246
+ }>,
247
+ ): StoryDefinition => ({
248
+ description: story.description,
249
+ entries: story.entries
250
+ .map((item) => parseEntry(item)?.serialized ?? "")
251
+ .filter(Boolean),
252
+ key: story.key,
253
+ pages: story.pages?.map(normalizePath).filter(Boolean) ?? [],
254
+ title: story.title,
255
+ });
256
+
257
+ const normalizeDefinition = (
258
+ definition: RegisteredMockDefinition | RegisteredPatchDefinition,
259
+ mode: "mock" | "patch",
260
+ ): RuntimeDefinition => {
261
+ const method = normalizeMethods(definition.method);
262
+ const normalized: {
263
+ caseKey?: string;
264
+ description?: string;
265
+ handler: MockHandler | PatchHandler;
266
+ key: string;
267
+ match?: RouteMatcher;
268
+ method?: readonly string[];
269
+ mode: "mock" | "patch";
270
+ pages: readonly string[];
271
+ path: string;
272
+ } = {
273
+ handler: definition.handler,
274
+ key: serializeEntry(definition.path, definition.caseKey),
275
+ mode,
276
+ pages: definition.pages?.map(normalizePath).filter(Boolean) ?? [],
277
+ path: normalizePath(definition.path),
278
+ };
279
+
280
+ if (definition.caseKey) {
281
+ normalized.caseKey = definition.caseKey;
282
+ }
283
+
284
+ if (definition.description) {
285
+ normalized.description = definition.description;
286
+ }
287
+
288
+ if (definition.match) {
289
+ normalized.match = definition.match;
290
+ }
291
+
292
+ if (method) {
293
+ normalized.method = method;
294
+ }
295
+
296
+ return normalized;
297
+ };
298
+
299
+ const normalizeStoryQuery = (query: string | undefined) =>
300
+ query?.trim().toLocaleLowerCase() ?? "";
301
+
302
+ const normalizeStoryListOptions = (input: StoryListInput): StoryListOptions =>
303
+ typeof input === "string" ? { page: input } : input;
304
+
305
+ const doesPageMatch = (page: string | undefined, pages: readonly string[]) => {
306
+ const normalizedPage = normalizePath(page ?? "");
307
+
308
+ if (!normalizedPage) {
309
+ return true;
310
+ }
311
+
312
+ return pages.some((candidate) => {
313
+ const normalizedCandidate = normalizePath(candidate);
314
+
315
+ return (
316
+ normalizedCandidate === normalizedPage ||
317
+ (normalizedCandidate !== "/" &&
318
+ normalizedPage.startsWith(`${normalizedCandidate}/`))
319
+ );
320
+ });
321
+ };
322
+
323
+ const doesStoryQueryMatch = (query: string, story: StoryCatalogItem) => {
324
+ if (!query) {
325
+ return true;
326
+ }
327
+
328
+ return [
329
+ story.description,
330
+ story.key,
331
+ story.title,
332
+ ...story.entries,
333
+ ...story.pages,
334
+ ].some((value) => value.toLocaleLowerCase().includes(query));
335
+ };
336
+
337
+ const normalizeSearchOptions = (
338
+ input: TestModeSearchInput,
339
+ ): TestModeSearchOptions =>
340
+ typeof input === "string" ? { query: input } : input;
341
+
342
+ const doesFeatureQueryMatch = (query: string, feature: FeatureCatalogItem) => {
343
+ if (!query) {
344
+ return true;
345
+ }
346
+
347
+ return [
348
+ feature.caseKey,
349
+ feature.description,
350
+ feature.key,
351
+ feature.mode,
352
+ feature.path,
353
+ ...feature.pages,
354
+ ]
355
+ .filter((value): value is string => typeof value === "string")
356
+ .some((value) => value.toLocaleLowerCase().includes(query));
357
+ };
358
+
359
+ export class TestMode {
360
+ readonly cookieKey: string;
361
+ readonly eventName: string;
362
+ readonly storageKey: string;
363
+
364
+ private readonly enabled: boolean | (() => boolean);
365
+ private readonly beforeChange: TestModeOptions["beforeChange"];
366
+ private readonly logger: false | TestModeLogger | undefined;
367
+ private definitions: RuntimeDefinition[];
368
+ private storiesCatalog: StoryDefinition[];
369
+ private memoryPaths: string[] = [];
370
+ private responseOverrides = new ResponseOverrides();
371
+ private listeners = new Set<(paths: string[]) => void>();
372
+ private readonly requestCounts = new Map<string, number>();
373
+ private dispatchingChange = false;
374
+ private memoryOnly = false;
375
+
376
+ constructor({
377
+ beforeChange,
378
+ cookieKey,
379
+ definitions = [],
380
+ enabled = defaultEnabled,
381
+ eventName = DEFAULT_CHANGE_EVENT,
382
+ logger,
383
+ patchDefinitions = [],
384
+ stories = [],
385
+ storageKey = DEFAULT_STORAGE_KEY,
386
+ }: TestModeOptions = {}) {
387
+ this.cookieKey = cookieKey ?? storageKey;
388
+ this.beforeChange = beforeChange;
389
+ this.enabled = enabled;
390
+ this.eventName = eventName;
391
+ this.logger = logger;
392
+ this.storageKey = storageKey;
393
+ this.definitions = [
394
+ ...definitions.map((definition) =>
395
+ normalizeDefinition(definition, "mock"),
396
+ ),
397
+ ...patchDefinitions.map((definition) =>
398
+ normalizeDefinition(definition, "patch"),
399
+ ),
400
+ ];
401
+ this.storiesCatalog = stories.map(defineStory);
402
+ this.assertStoriesAreValid();
403
+ this.canonicalizeStories();
404
+ }
405
+
406
+ isAvailable = () =>
407
+ typeof this.enabled === "function" ? this.enabled() : this.enabled;
408
+
409
+ register = (
410
+ definitions: readonly RegisteredMockDefinition[] = [],
411
+ patchDefinitions: readonly RegisteredPatchDefinition[] = [],
412
+ stories: readonly StoryDefinition[] = [],
413
+ ) => {
414
+ const previousDefinitions = this.definitions;
415
+ const previousStories = this.storiesCatalog;
416
+ this.definitions = [
417
+ ...this.definitions,
418
+ ...definitions.map((definition) =>
419
+ normalizeDefinition(definition, "mock"),
420
+ ),
421
+ ...patchDefinitions.map((definition) =>
422
+ normalizeDefinition(definition, "patch"),
423
+ ),
424
+ ];
425
+ this.storiesCatalog = [...this.storiesCatalog, ...stories.map(defineStory)];
426
+ try {
427
+ this.assertStoriesAreValid();
428
+ this.canonicalizeStories();
429
+ } catch (error) {
430
+ this.definitions = previousDefinitions;
431
+ this.storiesCatalog = previousStories;
432
+ throw error;
433
+ }
434
+ this.notify();
435
+ };
436
+
437
+ /** Replace one response immediately, without registering a feature or story. */
438
+ setMock = (
439
+ path: string,
440
+ data: unknown,
441
+ options: ResponseOverrideOptions = {},
442
+ ) => {
443
+ if (!this.isAvailable()) return [];
444
+ const next = this.responseOverrides.clone();
445
+ const result = next.set(path, data, "mock", options);
446
+ this.validateChange(this.read(), next);
447
+ this.responseOverrides = next;
448
+ this.notify();
449
+ return result;
450
+ };
451
+
452
+ /** Shallow-merge JSON fields into the real response. Nested values are replaced. */
453
+ setPatch = (
454
+ path: string,
455
+ fields: Readonly<Record<string, unknown>>,
456
+ options: Pick<ResponseOverrideOptions, "method"> = {},
457
+ ) => {
458
+ if (!this.isAvailable()) return [];
459
+ const next = this.responseOverrides.clone();
460
+ const result = next.set(path, fields, "patch", options);
461
+ this.validateChange(this.read(), next);
462
+ this.responseOverrides = next;
463
+ this.notify();
464
+ return result;
465
+ };
466
+
467
+ overrides = () => (this.isAvailable() ? this.responseOverrides.list() : []);
468
+
469
+ resetOverrides = (
470
+ path?: string,
471
+ options: Pick<ResponseOverrideOptions, "method"> = {},
472
+ ) => {
473
+ const next = this.responseOverrides.clone();
474
+ const result = next.clear(path, options.method);
475
+ this.validateChange(this.read(), next);
476
+ this.responseOverrides = next;
477
+ this.notify();
478
+ return result;
479
+ };
480
+
481
+ active = (cookieHeader?: string | null) => this.read(cookieHeader);
482
+
483
+ isActiveForPage = (page: string, cookieHeader?: string | null) => {
484
+ if (typeof cookieHeader !== "string" && this.overrides().length > 0)
485
+ return true;
486
+ const activeKeys = new Set(this.read(cookieHeader));
487
+ const activeDefinitions = this.definitions.filter((definition) =>
488
+ activeKeys.has(definition.key),
489
+ );
490
+
491
+ return (
492
+ activeDefinitions.some((definition) =>
493
+ this.definitionMatchesPage(definition, page),
494
+ ) ||
495
+ this.storiesCatalog.some((story) => {
496
+ const entries = story.entries.filter((item) =>
497
+ Boolean(this.findDefinitionByInput(item)),
498
+ );
499
+
500
+ return (
501
+ entries.length > 0 &&
502
+ entries.every((item) => activeKeys.has(item)) &&
503
+ doesPageMatch(page, this.getStoryPages(story))
504
+ );
505
+ })
506
+ );
507
+ };
508
+
509
+ list = () => {
510
+ const active = this.read();
511
+ const items = this.definitions
512
+ .map((definition) => ({
513
+ active: active.includes(definition.key),
514
+ description: definition.description ?? "No description",
515
+ key: definition.key,
516
+ mode: definition.mode,
517
+ pages: definition.pages,
518
+ path: definition.path,
519
+ ...(definition.caseKey ? { caseKey: definition.caseKey } : {}),
520
+ }))
521
+ .sort((left, right) => left.key.localeCompare(right.key));
522
+
523
+ return {
524
+ active: items.filter((item) => item.active),
525
+ inactive: items.filter((item) => !item.active),
526
+ };
527
+ };
528
+
529
+ features = this.list;
530
+
531
+ stories = (input: StoryListInput = {}) => {
532
+ if (!this.isAvailable()) {
533
+ return [];
534
+ }
535
+
536
+ const options = normalizeStoryListOptions(input);
537
+ const active = this.read();
538
+ const query = normalizeStoryQuery(options.query);
539
+
540
+ return this.storiesCatalog
541
+ .map((story) => {
542
+ const entries = story.entries.filter((item) =>
543
+ Boolean(this.findDefinitionByInput(item)),
544
+ );
545
+ const pages = this.getStoryPages(story);
546
+
547
+ return {
548
+ active:
549
+ entries.length > 0 &&
550
+ entries.every((item) => active.includes(item)),
551
+ activeEntries: entries.filter((item) => active.includes(item)),
552
+ description: story.description,
553
+ entries,
554
+ key: story.key,
555
+ pages,
556
+ title: story.title,
557
+ unavailableEntries: story.entries.filter(
558
+ (item) => !this.findDefinitionByInput(item),
559
+ ),
560
+ };
561
+ })
562
+ .filter((story) => !options.storyKey || story.key === options.storyKey)
563
+ .filter((story) => doesPageMatch(options.page, story.pages))
564
+ .filter((story) => doesStoryQueryMatch(query, story))
565
+ .filter(
566
+ (story) =>
567
+ typeof options.active !== "boolean" ||
568
+ story.active === options.active,
569
+ )
570
+ .sort((left, right) => left.title.localeCompare(right.title));
571
+ };
572
+
573
+ search = (input: TestModeSearchInput = {}): TestModeSearchResult => {
574
+ const options = normalizeSearchOptions(input);
575
+ const query = normalizeStoryQuery(options.query);
576
+ const featureItems = [...this.list().active, ...this.list().inactive]
577
+ .filter((feature) => doesPageMatch(options.page, feature.pages))
578
+ .filter((feature) => doesFeatureQueryMatch(query, feature))
579
+ .filter(
580
+ (feature) =>
581
+ typeof options.active !== "boolean" ||
582
+ feature.active === options.active,
583
+ );
584
+
585
+ return {
586
+ features: featureItems,
587
+ stories: this.stories(options),
588
+ };
589
+ };
590
+
591
+ hasStory = (storyKey: string) =>
592
+ this.storiesCatalog.some((story) => story.key === storyKey);
593
+
594
+ story = (storyKey: string) => {
595
+ const story = this.findStory(storyKey);
596
+
597
+ return story ? this.set(story.entries) : this.read();
598
+ };
599
+
600
+ addStory = (storyKey: string) => {
601
+ const story = this.findStory(storyKey);
602
+
603
+ return story ? this.set([...this.read(), ...story.entries]) : this.read();
604
+ };
605
+
606
+ set = (paths: readonly string[] | string) => {
607
+ const nextPaths: string[] = [];
608
+
609
+ for (const input of parseInputList(paths)) {
610
+ const key = this.normalizeActiveInput(input);
611
+
612
+ if (!key) {
613
+ continue;
614
+ }
615
+
616
+ const compatible = nextPaths.filter((path) => !this.conflicts(path, key));
617
+ nextPaths.splice(0, nextPaths.length, ...compatible, key);
618
+ }
619
+
620
+ return this.write(nextPaths.sort());
621
+ };
622
+
623
+ add = (path: string) => {
624
+ const key = this.normalizeActiveInput(path);
625
+
626
+ if (!key) {
627
+ return this.read();
628
+ }
629
+
630
+ return this.set([
631
+ ...this.read().filter((item) => !this.conflicts(item, key)),
632
+ key,
633
+ ]);
634
+ };
635
+
636
+ remove = (path: string) => {
637
+ const key = this.normalizeActiveInput(path);
638
+
639
+ if (!key) {
640
+ return this.read();
641
+ }
642
+
643
+ return this.set(this.read().filter((item) => item !== key));
644
+ };
645
+
646
+ toggle = (path: string) => {
647
+ const key = this.normalizeActiveInput(path);
648
+
649
+ if (!key) {
650
+ return this.read();
651
+ }
652
+
653
+ return this.read().includes(key) ? this.remove(key) : this.add(key);
654
+ };
655
+
656
+ clear = () => this.write([], new ResponseOverrides());
657
+
658
+ subscribe = (listener: (paths: string[]) => void) => {
659
+ this.listeners.add(listener);
660
+
661
+ if (typeof window !== "undefined") {
662
+ const handleStorage = (event: StorageEvent) => {
663
+ if (event.key === this.storageKey || event.key === null) {
664
+ try {
665
+ if (event.storageArea && event.storageArea !== window.localStorage)
666
+ return;
667
+ } catch {
668
+ return;
669
+ }
670
+ this.memoryPaths = this.normalizeActivePaths(
671
+ parseStoredPaths(event.newValue),
672
+ );
673
+ this.memoryOnly = false;
674
+ writeCookie(this.cookieKey, this.memoryPaths);
675
+ listener(this.read());
676
+ }
677
+ };
678
+ const handleCustomEvent = () => {
679
+ if (!this.dispatchingChange) listener(this.read());
680
+ };
681
+
682
+ window.addEventListener("storage", handleStorage);
683
+ window.addEventListener(this.eventName, handleCustomEvent);
684
+
685
+ return () => {
686
+ this.listeners.delete(listener);
687
+ window.removeEventListener("storage", handleStorage);
688
+ window.removeEventListener(this.eventName, handleCustomEvent);
689
+ };
690
+ }
691
+
692
+ return () => {
693
+ this.listeners.delete(listener);
694
+ };
695
+ };
696
+
697
+ resolve = async ({
698
+ body,
699
+ cookieHeader,
700
+ headers = {},
701
+ method,
702
+ params,
703
+ path,
704
+ url,
705
+ }: TestModeRequest): Promise<MockResult | null> => {
706
+ const definition = this.findActiveDefinition("mock", {
707
+ cookieHeader,
708
+ headers,
709
+ method,
710
+ params,
711
+ path,
712
+ url,
713
+ });
714
+
715
+ if (!definition) {
716
+ return null;
717
+ }
718
+
719
+ const normalizedMethod = method.toUpperCase();
720
+ const normalizedPath = normalizePath(path);
721
+ const request = BODYLESS_METHODS.has(normalizedMethod) ? params : body;
722
+ const result = await (definition.handler as MockHandler)({
723
+ activeKey: definition.key,
724
+ body: request,
725
+ headers,
726
+ method: normalizedMethod,
727
+ params,
728
+ path: normalizedPath,
729
+ request,
730
+ requestCount: this.nextRequestCount(definition.key),
731
+ url: url ?? normalizedPath,
732
+ });
733
+
734
+ if (isMockPassThrough(result)) {
735
+ this.log("info", "Mock pass-through", { method: normalizedMethod, path });
736
+ return null;
737
+ }
738
+
739
+ if (isMockHttpResult(result)) {
740
+ return result;
741
+ }
742
+
743
+ return {
744
+ data: result,
745
+ status: 200,
746
+ statusText: "OK",
747
+ };
748
+ };
749
+
750
+ hasMock = (request: TestModeRequest) =>
751
+ this.findActiveDefinition("mock", request) !== null;
752
+
753
+ hasPatch = (request: TestModeRequest) =>
754
+ this.findActiveDefinition("patch", request) !== null;
755
+
756
+ /** Unlike patch(), this distinguishes a JSON null payload from no match. */
757
+ applyPatch = async ({
758
+ body,
759
+ cookieHeader,
760
+ data,
761
+ headers = {},
762
+ method,
763
+ params,
764
+ path,
765
+ url,
766
+ }: TestModePatchRequest): Promise<Readonly<{ data: unknown }> | null> => {
767
+ const definition = this.findActiveDefinition("patch", {
768
+ cookieHeader,
769
+ headers,
770
+ method,
771
+ params,
772
+ path,
773
+ url,
774
+ });
775
+
776
+ if (!definition) {
777
+ return null;
778
+ }
779
+
780
+ const normalizedMethod = method.toUpperCase();
781
+ const normalizedPath = normalizePath(path);
782
+ const request = BODYLESS_METHODS.has(normalizedMethod) ? params : body;
783
+
784
+ const patched = await (definition.handler as PatchHandler)(data, {
785
+ activeKey: definition.key,
786
+ body: request,
787
+ headers,
788
+ method: normalizedMethod,
789
+ params,
790
+ path: normalizedPath,
791
+ request,
792
+ requestCount: this.nextRequestCount(definition.key),
793
+ url: url ?? normalizedPath,
794
+ });
795
+ return { data: patched };
796
+ };
797
+
798
+ /** Compatibility helper. Use applyPatch() when a handler can return null. */
799
+ patch = async (request: TestModePatchRequest): Promise<unknown | null> => {
800
+ const result = await this.applyPatch(request);
801
+ return result === null ? null : result.data;
802
+ };
803
+
804
+ private read = (cookieHeader?: string | null) => {
805
+ if (!this.isAvailable()) {
806
+ return [];
807
+ }
808
+
809
+ if (typeof cookieHeader === "string") {
810
+ return this.normalizeActivePaths(
811
+ parseStoredPaths(readCookieValue(cookieHeader, this.cookieKey)),
812
+ );
813
+ }
814
+
815
+ if (typeof window === "undefined" || this.memoryOnly) {
816
+ return [...this.memoryPaths];
817
+ }
818
+
819
+ const stored = readBrowserStorage(this.storageKey);
820
+ if (typeof stored === "string") {
821
+ return this.normalizeActivePaths(parseStoredPaths(stored));
822
+ }
823
+ try {
824
+ const cookie =
825
+ typeof document === "undefined"
826
+ ? ""
827
+ : readCookieValue(document.cookie, this.cookieKey);
828
+ if (cookie) return this.normalizeActivePaths(parseStoredPaths(cookie));
829
+ } catch {
830
+ // Fall back to the instance state when browser persistence is unavailable.
831
+ }
832
+ return [...this.memoryPaths];
833
+ };
834
+
835
+ private validateChange = (paths: readonly string[], overrides: ResponseOverrides) =>
836
+ this.beforeChange?.({ entries: [...paths], overrides: overrides.list() });
837
+
838
+ private write = (paths: readonly string[], overrides = this.responseOverrides) => {
839
+ if (!this.isAvailable()) {
840
+ this.responseOverrides = overrides;
841
+ return [];
842
+ }
843
+ const normalizedPaths = this.normalizeActivePaths(paths);
844
+ this.validateChange(normalizedPaths, overrides);
845
+ this.responseOverrides = overrides;
846
+ this.memoryPaths = normalizedPaths;
847
+
848
+ if (typeof window !== "undefined") {
849
+ this.memoryOnly = !writeBrowserStorage(
850
+ this.storageKey,
851
+ JSON.stringify(normalizedPaths),
852
+ );
853
+ writeCookie(this.cookieKey, normalizedPaths);
854
+ }
855
+ this.notify(normalizedPaths);
856
+ return [...normalizedPaths];
857
+ };
858
+
859
+ private notify = (paths = this.read()) => {
860
+ if (typeof window !== "undefined") {
861
+ this.dispatchingChange = true;
862
+ try {
863
+ window.dispatchEvent(
864
+ new CustomEvent<string[]>(this.eventName, { detail: [...paths] }),
865
+ );
866
+ } finally {
867
+ this.dispatchingChange = false;
868
+ }
869
+ }
870
+ for (const listener of this.listeners) listener([...paths]);
871
+ };
872
+
873
+ private normalizeActivePaths = (paths: readonly string[]) =>
874
+ Array.from(
875
+ new Set(
876
+ paths
877
+ .map((path) => this.normalizeActiveInput(path))
878
+ .filter((path) => path.length > 0),
879
+ ),
880
+ ).sort();
881
+
882
+ private normalizeActiveInput = (input: string) => {
883
+ const trimmed = input.trim();
884
+
885
+ if (!trimmed) {
886
+ return "";
887
+ }
888
+
889
+ const exact = this.definitions.find(
890
+ (definition) => definition.key === trimmed,
891
+ );
892
+
893
+ if (exact) {
894
+ return exact.key;
895
+ }
896
+
897
+ const entry = parseEntry(trimmed);
898
+
899
+ if (!entry) {
900
+ return "";
901
+ }
902
+
903
+ const definition = this.findDefinitionByEntry(entry);
904
+
905
+ return definition?.key ?? "";
906
+ };
907
+
908
+ private findDefinitionByInput = (input: string) => {
909
+ const exact = this.definitions.find(
910
+ (definition) => definition.key === input,
911
+ );
912
+
913
+ if (exact) {
914
+ return exact;
915
+ }
916
+
917
+ const entry = parseEntry(input);
918
+
919
+ return entry ? this.findDefinitionByEntry(entry) : null;
920
+ };
921
+
922
+ private findDefinitionByEntry = (entry: ActiveEntry) =>
923
+ this.definitions.find(
924
+ (item) =>
925
+ item.caseKey === entry.caseKey && isSamePath(item.path, entry.path),
926
+ );
927
+
928
+ private conflicts = (leftKey: string, rightKey: string) => {
929
+ const left = this.definitions.filter(
930
+ (definition) => definition.key === leftKey,
931
+ );
932
+ const right = this.definitions.filter(
933
+ (definition) => definition.key === rightKey,
934
+ );
935
+
936
+ if (left.length === 0 || right.length === 0) {
937
+ return leftKey === rightKey;
938
+ }
939
+
940
+ return left.some((a) =>
941
+ right.some(
942
+ (b) => isSamePath(a.path, b.path) && methodsOverlap(a.method, b.method),
943
+ ),
944
+ );
945
+ };
946
+
947
+ private findActiveDefinition = (
948
+ mode: "mock" | "patch",
949
+ request: Omit<TestModeRequest, "body">,
950
+ ) => {
951
+ if (!this.isAvailable()) {
952
+ return null;
953
+ }
954
+
955
+ const normalizedMethod = request.method.toUpperCase();
956
+ const normalizedPath = normalizePath(request.path);
957
+ // Explicit cookie input is server/request-scoped; never apply a local experiment to it.
958
+ const override =
959
+ typeof request.cookieHeader === "string"
960
+ ? undefined
961
+ : this.responseOverrides.find(normalizedPath, normalizedMethod);
962
+ if (override) {
963
+ if (override.mode !== mode) return null;
964
+ const handler: MockHandler | PatchHandler =
965
+ mode === "mock"
966
+ ? () =>
967
+ httpResult({
968
+ data: override.data,
969
+ bodyFormat: "json",
970
+ status: override.status!,
971
+ statusText: override.statusText!,
972
+ })
973
+ : (data: unknown) => {
974
+ if (
975
+ data === null ||
976
+ typeof data !== "object" ||
977
+ Array.isArray(data)
978
+ )
979
+ throw new TypeError(
980
+ "Cannot apply an object patch to a non-object response. Use a mock to replace it.",
981
+ );
982
+ return { ...data, ...(override.data as Record<string, unknown>) };
983
+ };
984
+ return {
985
+ key: `override:${normalizedMethod}:${normalizedPath}`,
986
+ path: normalizedPath,
987
+ mode,
988
+ pages: [],
989
+ handler,
990
+ } satisfies RuntimeDefinition;
991
+ }
992
+
993
+ for (const key of this.read(request.cookieHeader)) {
994
+ const definition = this.definitions.find(
995
+ (item) =>
996
+ item.mode === mode &&
997
+ item.key === key &&
998
+ this.methodMatches(item, normalizedMethod) &&
999
+ this.routeMatches(item, {
1000
+ headers: request.headers ?? {},
1001
+ method: normalizedMethod,
1002
+ params: request.params,
1003
+ path: normalizedPath,
1004
+ url: request.url ?? normalizedPath,
1005
+ }),
1006
+ );
1007
+
1008
+ if (definition) {
1009
+ return definition;
1010
+ }
1011
+ }
1012
+
1013
+ return null;
1014
+ };
1015
+
1016
+ private methodMatches = (definition: RuntimeDefinition, method: string) =>
1017
+ !definition.method || definition.method.includes(method);
1018
+
1019
+ private routeMatches = (
1020
+ definition: RuntimeDefinition,
1021
+ context: Pick<
1022
+ MockContext,
1023
+ "headers" | "method" | "params" | "path" | "url"
1024
+ >,
1025
+ ) => {
1026
+ const matcher = definition.match ?? definition.path;
1027
+
1028
+ if (typeof matcher === "function") {
1029
+ return matcher(context);
1030
+ }
1031
+
1032
+ if (matcher instanceof RegExp) {
1033
+ matcher.lastIndex = 0;
1034
+ return matcher.test(context.path);
1035
+ }
1036
+
1037
+ return doesPathMatch(matcher, context.path);
1038
+ };
1039
+
1040
+ private nextRequestCount = (key: string) => {
1041
+ const nextCount = (this.requestCounts.get(key) ?? 0) + 1;
1042
+
1043
+ this.requestCounts.set(key, nextCount);
1044
+
1045
+ return nextCount;
1046
+ };
1047
+
1048
+ private log = (
1049
+ level: "debug" | "error" | "info" | "warning",
1050
+ message: string,
1051
+ data?: unknown,
1052
+ ) => {
1053
+ if (this.logger === false) {
1054
+ return;
1055
+ }
1056
+
1057
+ this.logger?.[level]?.(message, data);
1058
+ };
1059
+
1060
+ private findStory = (storyKey: string) =>
1061
+ this.storiesCatalog.find((story) => story.key === storyKey) ?? null;
1062
+
1063
+ private definitionMatchesPage = (
1064
+ definition: RuntimeDefinition,
1065
+ page: string,
1066
+ ) => definition.pages.length === 0 || doesPageMatch(page, definition.pages);
1067
+
1068
+ private getStoryPages = (story: StoryDefinition) =>
1069
+ Array.from(
1070
+ new Set([
1071
+ ...story.pages,
1072
+ ...story.entries.flatMap(
1073
+ (item) => this.findDefinitionByInput(item)?.pages ?? [],
1074
+ ),
1075
+ ]),
1076
+ ).sort();
1077
+
1078
+ private assertStoriesAreValid = () => {
1079
+ const seenStoryKeys = new Set<string>();
1080
+ const errors: string[] = [];
1081
+
1082
+ for (const [index, definition] of this.definitions.entries()) {
1083
+ if (!definition.path) errors.push("Feature path is required.");
1084
+ if (
1085
+ this.definitions
1086
+ .slice(0, index)
1087
+ .some(
1088
+ (other) =>
1089
+ isSamePath(other.path, definition.path) &&
1090
+ other.caseKey === definition.caseKey &&
1091
+ methodsOverlap(other.method, definition.method),
1092
+ )
1093
+ )
1094
+ errors.push(`Ambiguous feature entry: ${definition.key}`);
1095
+ }
1096
+
1097
+ for (const story of this.storiesCatalog) {
1098
+ if (!story.key.trim()) {
1099
+ errors.push("Story key is required.");
1100
+ } else if (seenStoryKeys.has(story.key)) {
1101
+ errors.push(`Duplicate story key: ${story.key}`);
1102
+ }
1103
+
1104
+ seenStoryKeys.add(story.key);
1105
+
1106
+ if (!story.title.trim()) {
1107
+ errors.push(`Story title is required: ${story.key || "(missing key)"}`);
1108
+ }
1109
+
1110
+ if (!story.description.trim()) {
1111
+ errors.push(
1112
+ `Story description is required: ${story.key || "(missing key)"}`,
1113
+ );
1114
+ }
1115
+
1116
+ if (this.getStoryPages(story).length === 0) {
1117
+ errors.push(
1118
+ `Story pages are required: ${story.key || "(missing key)"}`,
1119
+ );
1120
+ }
1121
+
1122
+ if (story.entries.length === 0) {
1123
+ errors.push(
1124
+ `Story entries are required: ${story.key || "(missing key)"}`,
1125
+ );
1126
+ }
1127
+
1128
+ for (const item of story.entries) {
1129
+ if (!this.findDefinitionByInput(item)) {
1130
+ errors.push(`Story references unknown entry: ${story.key}: ${item}`);
1131
+ }
1132
+ }
1133
+ const canonicalEntries = story.entries
1134
+ .map(this.normalizeActiveInput)
1135
+ .filter(Boolean);
1136
+ if (
1137
+ canonicalEntries.some((item, index) =>
1138
+ canonicalEntries
1139
+ .slice(0, index)
1140
+ .some((other) => other !== item && this.conflicts(item, other)),
1141
+ )
1142
+ ) {
1143
+ errors.push(`Story contains conflicting entries: ${story.key}`);
1144
+ }
1145
+ }
1146
+
1147
+ if (errors.length > 0) {
1148
+ throw new Error(`Invalid test-mode stories:\n${errors.join("\n")}`);
1149
+ }
1150
+ };
1151
+
1152
+ private canonicalizeStories = () => {
1153
+ this.storiesCatalog = this.storiesCatalog.map((story) => ({
1154
+ ...story,
1155
+ entries: [...new Set(story.entries.map(this.normalizeActiveInput))],
1156
+ }));
1157
+ };
1158
+ }
1159
+
1160
+ export const createTestMode = (options?: TestModeOptions) =>
1161
+ new TestMode(options);