@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.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +170 -0
- package/bin/test-mode.mjs +164 -0
- package/dist/browser.d.ts +7 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +455 -0
- package/dist/browser.js.map +1 -0
- package/dist/client.d.ts +14 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +92 -0
- package/dist/client.js.map +1 -0
- package/dist/core.d.ts +160 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +741 -0
- package/dist/core.js.map +1 -0
- package/dist/fetch.d.ts +16 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +212 -0
- package/dist/fetch.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/draft-handler.d.ts +30 -0
- package/dist/internal/draft-handler.d.ts.map +1 -0
- package/dist/internal/draft-handler.js +80 -0
- package/dist/internal/draft-handler.js.map +1 -0
- package/dist/internal/lifecycle.d.ts +7 -0
- package/dist/internal/lifecycle.d.ts.map +1 -0
- package/dist/internal/lifecycle.js +65 -0
- package/dist/internal/lifecycle.js.map +1 -0
- package/dist/internal/next-request.d.ts +11 -0
- package/dist/internal/next-request.d.ts.map +1 -0
- package/dist/internal/next-request.js +22 -0
- package/dist/internal/next-request.js.map +1 -0
- package/dist/internal/overrides.d.ts +25 -0
- package/dist/internal/overrides.d.ts.map +1 -0
- package/dist/internal/overrides.js +111 -0
- package/dist/internal/overrides.js.map +1 -0
- package/dist/internal/paths.d.ts +3 -0
- package/dist/internal/paths.d.ts.map +1 -0
- package/dist/internal/paths.js +22 -0
- package/dist/internal/paths.js.map +1 -0
- package/dist/internal/server-context.d.ts +4 -0
- package/dist/internal/server-context.d.ts.map +1 -0
- package/dist/internal/server-context.js +6 -0
- package/dist/internal/server-context.js.map +1 -0
- package/dist/internal/ssr-state.d.ts +8 -0
- package/dist/internal/ssr-state.d.ts.map +1 -0
- package/dist/internal/ssr-state.js +48 -0
- package/dist/internal/ssr-state.js.map +1 -0
- package/dist/internal/storage.d.ts +6 -0
- package/dist/internal/storage.d.ts.map +1 -0
- package/dist/internal/storage.js +70 -0
- package/dist/internal/storage.js.map +1 -0
- package/dist/internal/symbols.d.ts +3 -0
- package/dist/internal/symbols.d.ts.map +1 -0
- package/dist/internal/symbols.js +3 -0
- package/dist/internal/symbols.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +32 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +27 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +144 -0
- package/dist/node.js.map +1 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +36 -0
- package/dist/server.js.map +1 -0
- package/dist/setup.d.ts +14 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +66 -0
- package/dist/setup.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/architecture.md +116 -0
- package/docs/guide.md +171 -0
- package/docs/migration.md +26 -0
- package/docs/releasing.md +41 -0
- package/docs/server-rendering.md +136 -0
- package/docs/story-test-design.md +252 -0
- package/package.json +136 -0
- package/src/browser.ts +593 -0
- package/src/client.ts +114 -0
- package/src/core.ts +1161 -0
- package/src/fetch.ts +271 -0
- package/src/index.ts +5 -0
- package/src/internal/draft-handler.ts +113 -0
- package/src/internal/lifecycle.ts +81 -0
- package/src/internal/next-request.ts +31 -0
- package/src/internal/overrides.ts +141 -0
- package/src/internal/paths.ts +27 -0
- package/src/internal/server-context.ts +6 -0
- package/src/internal/ssr-state.ts +48 -0
- package/src/internal/storage.ts +75 -0
- package/src/internal/symbols.ts +2 -0
- package/src/next.ts +49 -0
- package/src/node.ts +213 -0
- package/src/server.ts +52 -0
- package/src/setup.ts +69 -0
- package/src/types.ts +240 -0
- package/templates/test-mode/README.md +30 -0
- package/templates/test-mode/config.ts +25 -0
- package/templates/test-mode/features/auth.ts +23 -0
- package/templates/test-mode/index.ts +11 -0
- package/templates/test-mode/install.ts +13 -0
- package/templates/test-mode/stories/auth.stories.ts +10 -0
package/src/fetch.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import type { TestMode } from "./core.js";
|
|
2
|
+
import type { MockResult, TestModeRequest } from "./types.js";
|
|
3
|
+
|
|
4
|
+
export type MockFetchOptions = Readonly<{
|
|
5
|
+
/** A string fixes selection to that cookie. false uses runtime state, ignoring outgoing cookies. */
|
|
6
|
+
cookieHeader?: string | null | false;
|
|
7
|
+
mapRequest?: (
|
|
8
|
+
request: TestModeRequest,
|
|
9
|
+
) => Promise<TestModeRequest> | TestModeRequest;
|
|
10
|
+
originalFetch?: typeof fetch;
|
|
11
|
+
target?: { fetch: typeof fetch };
|
|
12
|
+
}>;
|
|
13
|
+
|
|
14
|
+
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
15
|
+
const BODYLESS_STATUSES = new Set([204, 205, 304]);
|
|
16
|
+
const installations = new WeakMap<
|
|
17
|
+
typeof fetch,
|
|
18
|
+
{ previous: typeof fetch; active: boolean }
|
|
19
|
+
>();
|
|
20
|
+
|
|
21
|
+
const parseText = (text: string): unknown => {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(text) as unknown;
|
|
24
|
+
} catch {
|
|
25
|
+
return text;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const parseBody = async (body: BodyInit | null | undefined) => {
|
|
30
|
+
if (body == null) return undefined;
|
|
31
|
+
if (typeof body === "string") return parseText(body);
|
|
32
|
+
if (body instanceof URLSearchParams)
|
|
33
|
+
return Object.fromEntries(body.entries());
|
|
34
|
+
return body;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const requestMetadata = (
|
|
38
|
+
input: RequestInfo | URL,
|
|
39
|
+
init: RequestInit | undefined,
|
|
40
|
+
cookieHeader?: string | null | false,
|
|
41
|
+
): TestModeRequest => {
|
|
42
|
+
const request = input instanceof Request ? input : undefined;
|
|
43
|
+
const base =
|
|
44
|
+
typeof document !== "undefined"
|
|
45
|
+
? document.baseURI
|
|
46
|
+
: typeof window !== "undefined"
|
|
47
|
+
? window.location.href
|
|
48
|
+
: "https://test-mode.invalid";
|
|
49
|
+
const url = new URL(request?.url ?? String(input), base);
|
|
50
|
+
// RequestInit.headers replaces the Request headers, as native fetch does.
|
|
51
|
+
const headers = new Headers(init?.headers ?? request?.headers);
|
|
52
|
+
return {
|
|
53
|
+
cookieHeader:
|
|
54
|
+
cookieHeader === false
|
|
55
|
+
? undefined
|
|
56
|
+
: (cookieHeader ?? headers.get("cookie")),
|
|
57
|
+
headers,
|
|
58
|
+
method: (init?.method ?? request?.method ?? "GET").toUpperCase(),
|
|
59
|
+
params: Object.fromEntries(url.searchParams.entries()),
|
|
60
|
+
path: url.pathname,
|
|
61
|
+
url: url.toString(),
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const readRequestBody = async (
|
|
66
|
+
input: RequestInfo | URL,
|
|
67
|
+
init: RequestInit | undefined,
|
|
68
|
+
method: string,
|
|
69
|
+
): Promise<unknown> => {
|
|
70
|
+
if (BODYLESS_METHODS.has(method)) return undefined;
|
|
71
|
+
if (init?.body != null) return parseBody(init.body);
|
|
72
|
+
if (!(input instanceof Request) || input.body === null) return undefined;
|
|
73
|
+
|
|
74
|
+
const copy = input.clone();
|
|
75
|
+
const contentType = copy.headers.get("content-type") ?? "";
|
|
76
|
+
if (contentType.includes("multipart/form-data")) return copy.formData();
|
|
77
|
+
if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
78
|
+
return Object.fromEntries(new URLSearchParams(await copy.text()));
|
|
79
|
+
}
|
|
80
|
+
return parseText(await copy.text());
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const isBodyInit = (data: unknown): data is BodyInit =>
|
|
84
|
+
typeof data === "string" ||
|
|
85
|
+
data instanceof Blob ||
|
|
86
|
+
data instanceof FormData ||
|
|
87
|
+
data instanceof URLSearchParams ||
|
|
88
|
+
data instanceof ArrayBuffer ||
|
|
89
|
+
ArrayBuffer.isView(data) ||
|
|
90
|
+
data instanceof ReadableStream;
|
|
91
|
+
|
|
92
|
+
const responseFromMock = (result: MockResult, method: string) => {
|
|
93
|
+
const headers = new Headers(result.headers);
|
|
94
|
+
let body: BodyInit | null = null;
|
|
95
|
+
if (method !== "HEAD" && !BODYLESS_STATUSES.has(result.status)) {
|
|
96
|
+
if (result.bodyFormat === "json") {
|
|
97
|
+
body = JSON.stringify(result.data);
|
|
98
|
+
if (!headers.has("content-type"))
|
|
99
|
+
headers.set("content-type", "application/json");
|
|
100
|
+
} else if (isBodyInit(result.data)) {
|
|
101
|
+
body = result.data;
|
|
102
|
+
} else if (result.data !== undefined) {
|
|
103
|
+
body = JSON.stringify(result.data);
|
|
104
|
+
if (!headers.has("content-type"))
|
|
105
|
+
headers.set("content-type", "application/json");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return new Response(body, {
|
|
109
|
+
headers,
|
|
110
|
+
status: result.status,
|
|
111
|
+
statusText: result.statusText,
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const readResponsePayload = async (response: Response): Promise<unknown> => {
|
|
116
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
117
|
+
if (
|
|
118
|
+
contentType &&
|
|
119
|
+
!contentType.includes("json") &&
|
|
120
|
+
!contentType.startsWith("text/") &&
|
|
121
|
+
!contentType.includes("xml") &&
|
|
122
|
+
!contentType.includes("x-www-form-urlencoded")
|
|
123
|
+
) {
|
|
124
|
+
return response.clone().arrayBuffer();
|
|
125
|
+
}
|
|
126
|
+
const text = await response.clone().text();
|
|
127
|
+
return text.trim() ? parseText(text) : null;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const withAbort = <T>(
|
|
131
|
+
signal: AbortSignal | null | undefined,
|
|
132
|
+
run: () => Promise<T>,
|
|
133
|
+
): Promise<T> => {
|
|
134
|
+
if (!signal) return run();
|
|
135
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
136
|
+
return new Promise<T>((resolve, reject) => {
|
|
137
|
+
const abort = () => reject(signal.reason);
|
|
138
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
139
|
+
run().then(
|
|
140
|
+
(value) => {
|
|
141
|
+
signal.removeEventListener("abort", abort);
|
|
142
|
+
resolve(value);
|
|
143
|
+
},
|
|
144
|
+
(error: unknown) => {
|
|
145
|
+
signal.removeEventListener("abort", abort);
|
|
146
|
+
reject(error);
|
|
147
|
+
},
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const preserveMetadata = (result: Response, source: Response): Response => {
|
|
153
|
+
const clone = result.clone.bind(result);
|
|
154
|
+
Object.defineProperties(result, {
|
|
155
|
+
url: { value: source.url },
|
|
156
|
+
redirected: { value: source.redirected },
|
|
157
|
+
type: { value: source.type },
|
|
158
|
+
clone: { value: () => preserveMetadata(clone(), source) },
|
|
159
|
+
});
|
|
160
|
+
return result;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/** Wrap fetch without touching unmatched response bodies (including SSE streams). */
|
|
164
|
+
export const createMockFetch =
|
|
165
|
+
(
|
|
166
|
+
testMode: TestMode,
|
|
167
|
+
{
|
|
168
|
+
cookieHeader,
|
|
169
|
+
mapRequest,
|
|
170
|
+
originalFetch = globalThis.fetch.bind(globalThis),
|
|
171
|
+
}: MockFetchOptions = {},
|
|
172
|
+
): typeof fetch =>
|
|
173
|
+
async (input, init) => {
|
|
174
|
+
if (!testMode.isAvailable()) return originalFetch(input, init);
|
|
175
|
+
const signal =
|
|
176
|
+
init?.signal === undefined && input instanceof Request
|
|
177
|
+
? input.signal
|
|
178
|
+
: init?.signal;
|
|
179
|
+
return withAbort(signal, async () => {
|
|
180
|
+
let request = requestMetadata(input, init, cookieHeader);
|
|
181
|
+
if (
|
|
182
|
+
!mapRequest &&
|
|
183
|
+
!testMode.hasMock(request) &&
|
|
184
|
+
!testMode.hasPatch(request)
|
|
185
|
+
) {
|
|
186
|
+
return originalFetch(input, init);
|
|
187
|
+
}
|
|
188
|
+
request = {
|
|
189
|
+
...request,
|
|
190
|
+
body: await readRequestBody(input, init, request.method),
|
|
191
|
+
};
|
|
192
|
+
if (mapRequest) request = await mapRequest(request);
|
|
193
|
+
signal?.throwIfAborted();
|
|
194
|
+
const mock = await testMode.resolve(request);
|
|
195
|
+
signal?.throwIfAborted();
|
|
196
|
+
if (mock) return responseFromMock(mock, request.method.toUpperCase());
|
|
197
|
+
|
|
198
|
+
const response = await originalFetch(input, init);
|
|
199
|
+
// Opaque and bodyless responses cannot be reconstructed with a payload.
|
|
200
|
+
if (
|
|
201
|
+
response.status === 0 ||
|
|
202
|
+
request.method.toUpperCase() === "HEAD" ||
|
|
203
|
+
BODYLESS_STATUSES.has(response.status) ||
|
|
204
|
+
!testMode.hasPatch(request)
|
|
205
|
+
)
|
|
206
|
+
return response;
|
|
207
|
+
|
|
208
|
+
const patched = await testMode.applyPatch({
|
|
209
|
+
...request,
|
|
210
|
+
data: await readResponsePayload(response),
|
|
211
|
+
});
|
|
212
|
+
signal?.throwIfAborted();
|
|
213
|
+
if (patched === null) return response;
|
|
214
|
+
|
|
215
|
+
const headers = new Headers(response.headers);
|
|
216
|
+
// These describe the upstream bytes, which no longer match the patched body.
|
|
217
|
+
for (const name of [
|
|
218
|
+
"content-length",
|
|
219
|
+
"content-encoding",
|
|
220
|
+
"etag",
|
|
221
|
+
"content-md5",
|
|
222
|
+
"digest",
|
|
223
|
+
]) {
|
|
224
|
+
headers.delete(name);
|
|
225
|
+
}
|
|
226
|
+
const result = responseFromMock(
|
|
227
|
+
{
|
|
228
|
+
data: patched.data,
|
|
229
|
+
headers,
|
|
230
|
+
status: response.status,
|
|
231
|
+
statusText: response.statusText,
|
|
232
|
+
},
|
|
233
|
+
request.method.toUpperCase(),
|
|
234
|
+
);
|
|
235
|
+
// The Response constructor does not accept transport metadata.
|
|
236
|
+
return preserveMetadata(result, response);
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/** Cleanup is idempotent and supports nested installations in any teardown order. */
|
|
241
|
+
export const installMockFetch = (
|
|
242
|
+
testMode: TestMode,
|
|
243
|
+
{
|
|
244
|
+
target = globalThis,
|
|
245
|
+
originalFetch: transport,
|
|
246
|
+
...options
|
|
247
|
+
}: MockFetchOptions = {},
|
|
248
|
+
) => {
|
|
249
|
+
const previous = target.fetch;
|
|
250
|
+
const originalFetch = transport ?? previous.bind(target);
|
|
251
|
+
const wrapped = createMockFetch(testMode, { ...options, originalFetch });
|
|
252
|
+
const installation = { previous, active: true };
|
|
253
|
+
const replacement: typeof fetch = (input, init) =>
|
|
254
|
+
installation.active
|
|
255
|
+
? wrapped(input, init)
|
|
256
|
+
: previous.call(target, input, init);
|
|
257
|
+
installations.set(replacement, installation);
|
|
258
|
+
target.fetch = replacement;
|
|
259
|
+
return () => {
|
|
260
|
+
installation.active = false;
|
|
261
|
+
if (target.fetch === replacement) {
|
|
262
|
+
let restore = previous;
|
|
263
|
+
let state = installations.get(restore);
|
|
264
|
+
while (state && !state.active) {
|
|
265
|
+
restore = state.previous;
|
|
266
|
+
state = installations.get(restore);
|
|
267
|
+
}
|
|
268
|
+
target.fetch = restore;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
type CookieOptions = {
|
|
2
|
+
path: string;
|
|
3
|
+
httpOnly: boolean;
|
|
4
|
+
sameSite: "lax";
|
|
5
|
+
secure: boolean;
|
|
6
|
+
maxAge?: number;
|
|
7
|
+
};
|
|
8
|
+
export type DraftContext = {
|
|
9
|
+
draft: { isEnabled: boolean; enable: () => void; disable: () => void };
|
|
10
|
+
cookies: {
|
|
11
|
+
get: (name: string) => { value: string } | undefined;
|
|
12
|
+
set: (name: string, value: string, options: CookieOptions) => unknown;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
export type DraftHandlerOptions = Readonly<{
|
|
16
|
+
enabled?: boolean | (() => boolean);
|
|
17
|
+
/** Optional app authorization, in addition to the same-origin POST checks. */
|
|
18
|
+
authorize?: (request: Request) => boolean | Promise<boolean>;
|
|
19
|
+
/** Match the cookieKey used by the browser/server runtime. */
|
|
20
|
+
cookieKey?: string;
|
|
21
|
+
}>;
|
|
22
|
+
|
|
23
|
+
const result = (data: unknown, status = 200) =>
|
|
24
|
+
Response.json(data, {
|
|
25
|
+
status,
|
|
26
|
+
headers: { "Cache-Control": "private, no-store", Vary: "Cookie" },
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
export const createDraftControl =
|
|
30
|
+
(
|
|
31
|
+
getContext: () => Promise<DraftContext>,
|
|
32
|
+
{
|
|
33
|
+
enabled = () => process.env.NODE_ENV === "development",
|
|
34
|
+
authorize,
|
|
35
|
+
cookieKey = "test-mode.entries",
|
|
36
|
+
}: DraftHandlerOptions = {},
|
|
37
|
+
) =>
|
|
38
|
+
async (request: Request): Promise<Response> => {
|
|
39
|
+
if (!(typeof enabled === "function" ? enabled() : enabled))
|
|
40
|
+
return result({ error: "Not found" }, 404);
|
|
41
|
+
if (request.method !== "POST") return result({ error: "Use POST" }, 405);
|
|
42
|
+
const url = new URL(request.url);
|
|
43
|
+
if (
|
|
44
|
+
request.headers.get("origin") !==
|
|
45
|
+
`${url.protocol}//${request.headers.get("host") ?? url.host}` ||
|
|
46
|
+
request.headers.get("x-next-test-mode") !== "1" ||
|
|
47
|
+
(request.headers.has("sec-fetch-site") &&
|
|
48
|
+
request.headers.get("sec-fetch-site") !== "same-origin")
|
|
49
|
+
)
|
|
50
|
+
return result({ error: "A same-origin request is required" }, 403);
|
|
51
|
+
if (authorize && !(await authorize(request)))
|
|
52
|
+
return result({ error: "Not authorized" }, 403);
|
|
53
|
+
if (
|
|
54
|
+
request.headers.get("content-type")?.split(";")[0]?.trim() !==
|
|
55
|
+
"application/json"
|
|
56
|
+
)
|
|
57
|
+
return result({ error: "Use application/json" }, 415);
|
|
58
|
+
let input: unknown;
|
|
59
|
+
try {
|
|
60
|
+
const reader = request.body?.getReader();
|
|
61
|
+
if (!reader) return result({ error: "Missing body" }, 400);
|
|
62
|
+
const chunks: Uint8Array[] = [];
|
|
63
|
+
let length = 0;
|
|
64
|
+
while (true) {
|
|
65
|
+
const { value, done } = await reader.read();
|
|
66
|
+
if (done) break;
|
|
67
|
+
length += value.byteLength;
|
|
68
|
+
if (length > 1024) {
|
|
69
|
+
await reader.cancel();
|
|
70
|
+
return result({ error: "Request too large" }, 413);
|
|
71
|
+
}
|
|
72
|
+
chunks.push(value);
|
|
73
|
+
}
|
|
74
|
+
const bytes = new Uint8Array(length);
|
|
75
|
+
let offset = 0;
|
|
76
|
+
for (const chunk of chunks) {
|
|
77
|
+
bytes.set(chunk, offset);
|
|
78
|
+
offset += chunk.byteLength;
|
|
79
|
+
}
|
|
80
|
+
input = JSON.parse(new TextDecoder().decode(bytes));
|
|
81
|
+
} catch {
|
|
82
|
+
return result({ error: "Invalid JSON" }, 400);
|
|
83
|
+
}
|
|
84
|
+
if (
|
|
85
|
+
!input ||
|
|
86
|
+
typeof input !== "object" ||
|
|
87
|
+
typeof (input as { enabled?: unknown }).enabled !== "boolean"
|
|
88
|
+
)
|
|
89
|
+
return result({ error: "enabled must be a boolean" }, 400);
|
|
90
|
+
const desired = (input as { enabled: boolean }).enabled;
|
|
91
|
+
const { draft, cookies } = await getContext();
|
|
92
|
+
const marker = `${cookieKey}.draft-owner`;
|
|
93
|
+
const owned = cookies.get(marker)?.value === "1";
|
|
94
|
+
const before = draft.isEnabled;
|
|
95
|
+
const attributes: CookieOptions = {
|
|
96
|
+
path: "/",
|
|
97
|
+
httpOnly: true,
|
|
98
|
+
sameSite: "lax",
|
|
99
|
+
secure: url.protocol === "https:",
|
|
100
|
+
};
|
|
101
|
+
if (desired && !before) {
|
|
102
|
+
draft.enable();
|
|
103
|
+
cookies.set(marker, "1", attributes);
|
|
104
|
+
} else if (!desired && owned) {
|
|
105
|
+
draft.disable();
|
|
106
|
+
cookies.set(marker, "", { ...attributes, maxAge: 0 });
|
|
107
|
+
}
|
|
108
|
+
// Do not disable a CMS preview session that this package did not create.
|
|
109
|
+
return result({
|
|
110
|
+
enabled: draft.isEnabled,
|
|
111
|
+
changed: before !== draft.isEnabled,
|
|
112
|
+
});
|
|
113
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
type Cleanup = () => void;
|
|
2
|
+
|
|
3
|
+
/** Unwind every acquired resource, even when an individual teardown throws. */
|
|
4
|
+
export const createCleanup = (cleanups: readonly Cleanup[]): Cleanup => {
|
|
5
|
+
let cleaned = false;
|
|
6
|
+
return () => {
|
|
7
|
+
if (cleaned) return;
|
|
8
|
+
cleaned = true;
|
|
9
|
+
const errors: unknown[] = [];
|
|
10
|
+
for (const cleanup of [...cleanups].reverse()) {
|
|
11
|
+
try {
|
|
12
|
+
cleanup();
|
|
13
|
+
} catch (error) {
|
|
14
|
+
errors.push(error);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (errors.length)
|
|
18
|
+
throw new AggregateError(errors, "Test mode cleanup failed");
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type Layer = {
|
|
23
|
+
active: boolean;
|
|
24
|
+
descriptor: PropertyDescriptor;
|
|
25
|
+
previous: PropertyDescriptor | undefined;
|
|
26
|
+
parent: Layer | undefined;
|
|
27
|
+
};
|
|
28
|
+
const layers = new WeakMap<object, Map<string, Layer>>();
|
|
29
|
+
const matches = (
|
|
30
|
+
left: PropertyDescriptor | undefined,
|
|
31
|
+
right: PropertyDescriptor,
|
|
32
|
+
) =>
|
|
33
|
+
left !== undefined &&
|
|
34
|
+
["value", "get", "set", "writable", "enumerable", "configurable"].every(
|
|
35
|
+
(key) =>
|
|
36
|
+
left[key as keyof PropertyDescriptor] ===
|
|
37
|
+
right[key as keyof PropertyDescriptor],
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
/** Restore only owned globals, skipping disposed layers after out-of-order cleanup. */
|
|
41
|
+
export const installProperty = (
|
|
42
|
+
target: object,
|
|
43
|
+
key: string,
|
|
44
|
+
descriptor: PropertyDescriptor,
|
|
45
|
+
): Cleanup => {
|
|
46
|
+
let properties = layers.get(target);
|
|
47
|
+
if (!properties) {
|
|
48
|
+
properties = new Map();
|
|
49
|
+
layers.set(target, properties);
|
|
50
|
+
}
|
|
51
|
+
const previous = Object.getOwnPropertyDescriptor(target, key);
|
|
52
|
+
const current = properties.get(key);
|
|
53
|
+
Object.defineProperty(target, key, descriptor);
|
|
54
|
+
const layer: Layer = {
|
|
55
|
+
active: true,
|
|
56
|
+
descriptor: Object.getOwnPropertyDescriptor(target, key)!,
|
|
57
|
+
previous,
|
|
58
|
+
parent:
|
|
59
|
+
current && matches(previous, current.descriptor) ? current : undefined,
|
|
60
|
+
};
|
|
61
|
+
properties.set(key, layer);
|
|
62
|
+
return () => {
|
|
63
|
+
if (!layer.active) return;
|
|
64
|
+
layer.active = false;
|
|
65
|
+
if (
|
|
66
|
+
properties.get(key) !== layer ||
|
|
67
|
+
!matches(Object.getOwnPropertyDescriptor(target, key), layer.descriptor)
|
|
68
|
+
)
|
|
69
|
+
return;
|
|
70
|
+
let restore = layer.previous;
|
|
71
|
+
let parent = layer.parent;
|
|
72
|
+
while (parent && !parent.active) {
|
|
73
|
+
restore = parent.previous;
|
|
74
|
+
parent = parent.parent;
|
|
75
|
+
}
|
|
76
|
+
if (restore) Object.defineProperty(target, key, restore);
|
|
77
|
+
else Reflect.deleteProperty(target, key);
|
|
78
|
+
if (parent) properties.set(key, parent);
|
|
79
|
+
else properties.delete(key);
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Next 16 keeps the request's Draft Mode provider across `use cache` boundaries.
|
|
3
|
+
* Reading public headers() inside those boundaries throws, and reading it during
|
|
4
|
+
* prerender would change a static route into a dynamic one. Keep this version-
|
|
5
|
+
* sensitive bridge small, read-only, guarded, and covered by production fixtures.
|
|
6
|
+
*/
|
|
7
|
+
export const requestFromDraft = (draft: unknown, cookieKey: string) => {
|
|
8
|
+
const provider = (draft as { _provider?: object })._provider;
|
|
9
|
+
const jar = (
|
|
10
|
+
provider as
|
|
11
|
+
| {
|
|
12
|
+
_mutableCookies?: {
|
|
13
|
+
get: (key: string) => { value: string } | undefined;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
| undefined
|
|
17
|
+
)?._mutableCookies;
|
|
18
|
+
if (!provider || !jar || typeof jar.get !== "function")
|
|
19
|
+
throw new Error(
|
|
20
|
+
"Unsupported Next.js Draft Mode internals. Use a tested Next.js version with @uiwwsw/next-test-mode.",
|
|
21
|
+
);
|
|
22
|
+
const cookieHeader = [cookieKey, `${cookieKey}.ssr`]
|
|
23
|
+
.flatMap((name) => {
|
|
24
|
+
const value = jar.get(name)?.value;
|
|
25
|
+
return value === undefined
|
|
26
|
+
? []
|
|
27
|
+
: [`${name}=${encodeURIComponent(value)}`];
|
|
28
|
+
})
|
|
29
|
+
.join("; ");
|
|
30
|
+
return { key: provider, cookieHeader };
|
|
31
|
+
};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { ResponseOverride, ResponseOverrideOptions } from "../types.js";
|
|
2
|
+
import { normalizePath } from "./paths.js";
|
|
3
|
+
|
|
4
|
+
/** Keep console experiments as detached JSON values, never persisted code. */
|
|
5
|
+
const copyJSON = (value: unknown): unknown => {
|
|
6
|
+
const ancestors = new Set<object>();
|
|
7
|
+
const copy = (item: unknown): unknown => {
|
|
8
|
+
if (item === null || typeof item === "string" || typeof item === "boolean")
|
|
9
|
+
return item;
|
|
10
|
+
if (typeof item === "number" && Number.isFinite(item)) return item;
|
|
11
|
+
if (typeof item !== "object" || item === null)
|
|
12
|
+
throw new TypeError("Response overrides require JSON values.");
|
|
13
|
+
if (ancestors.has(item))
|
|
14
|
+
throw new TypeError("Response overrides cannot contain circular values.");
|
|
15
|
+
const array = Array.isArray(item);
|
|
16
|
+
if (
|
|
17
|
+
!array &&
|
|
18
|
+
Object.getPrototypeOf(item) !== Object.prototype &&
|
|
19
|
+
Object.getPrototypeOf(item) !== null
|
|
20
|
+
)
|
|
21
|
+
throw new TypeError("Response overrides require plain JSON objects.");
|
|
22
|
+
ancestors.add(item);
|
|
23
|
+
const output: Record<string, unknown> | unknown[] = array ? [] : {};
|
|
24
|
+
for (const key of Reflect.ownKeys(item)) {
|
|
25
|
+
if (array && key === "length") continue;
|
|
26
|
+
if (typeof key !== "string" || (array && !/^(0|[1-9]\d*)$/.test(key)))
|
|
27
|
+
throw new TypeError("Response overrides require JSON property keys.");
|
|
28
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, key)!;
|
|
29
|
+
if (!("value" in descriptor))
|
|
30
|
+
throw new TypeError(
|
|
31
|
+
"Response overrides cannot contain getters or setters.",
|
|
32
|
+
);
|
|
33
|
+
const cloned = copy(descriptor.value);
|
|
34
|
+
if (descriptor.enumerable)
|
|
35
|
+
Object.defineProperty(output, key, {
|
|
36
|
+
value: cloned,
|
|
37
|
+
writable: true,
|
|
38
|
+
enumerable: true,
|
|
39
|
+
configurable: true,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
if (array && Object.keys(item).length !== item.length)
|
|
43
|
+
throw new TypeError("Response overrides cannot contain sparse arrays.");
|
|
44
|
+
ancestors.delete(item);
|
|
45
|
+
return output;
|
|
46
|
+
};
|
|
47
|
+
return copy(value);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const overridePath = (path: string) => {
|
|
51
|
+
if (
|
|
52
|
+
typeof path !== "string" ||
|
|
53
|
+
!path.trim().startsWith("/") ||
|
|
54
|
+
path.trim().startsWith("//")
|
|
55
|
+
) {
|
|
56
|
+
throw new TypeError("Use an absolute pathname such as /api/cart.");
|
|
57
|
+
}
|
|
58
|
+
return normalizePath(path);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const normalizeMethod = (method = "GET") => {
|
|
62
|
+
if (typeof method !== "string" || !/^[a-z]+$/i.test(method.trim()))
|
|
63
|
+
throw new TypeError("Use an HTTP method such as GET or POST.");
|
|
64
|
+
return method.trim().toUpperCase();
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export class ResponseOverrides {
|
|
68
|
+
private entries = new Map<string, ResponseOverride>();
|
|
69
|
+
|
|
70
|
+
clone() {
|
|
71
|
+
const result = new ResponseOverrides();
|
|
72
|
+
result.entries = new Map(this.entries);
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
set(
|
|
77
|
+
path: string,
|
|
78
|
+
data: unknown,
|
|
79
|
+
mode: "mock" | "patch",
|
|
80
|
+
options: ResponseOverrideOptions = {},
|
|
81
|
+
) {
|
|
82
|
+
const normalizedPath = overridePath(path);
|
|
83
|
+
const method = normalizeMethod(options.method);
|
|
84
|
+
const value = copyJSON(data);
|
|
85
|
+
if (
|
|
86
|
+
mode === "patch" &&
|
|
87
|
+
(value === null || typeof value !== "object" || Array.isArray(value))
|
|
88
|
+
) {
|
|
89
|
+
throw new TypeError(
|
|
90
|
+
"A patch must be a JSON object containing the fields to replace.",
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
const status = options.status ?? 200;
|
|
94
|
+
if (!Number.isInteger(status) || status < 200 || status > 599)
|
|
95
|
+
throw new RangeError("Mock status must be an integer from 200 to 599.");
|
|
96
|
+
const statusText =
|
|
97
|
+
options.statusText ??
|
|
98
|
+
(status === 200 ? "OK" : status === 503 ? "Service Unavailable" : "");
|
|
99
|
+
if (
|
|
100
|
+
typeof statusText !== "string" ||
|
|
101
|
+
/[^\x20-\x7e\x80-\xff]/.test(statusText)
|
|
102
|
+
)
|
|
103
|
+
throw new TypeError("Invalid HTTP status text.");
|
|
104
|
+
this.entries.set(`${method} ${normalizedPath}`, {
|
|
105
|
+
path: normalizedPath,
|
|
106
|
+
method,
|
|
107
|
+
mode,
|
|
108
|
+
data: value,
|
|
109
|
+
...(mode === "mock" ? { status, statusText } : {}),
|
|
110
|
+
});
|
|
111
|
+
return this.list();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
list(): ResponseOverride[] {
|
|
115
|
+
return [...this.entries.values()].map((item) => ({
|
|
116
|
+
...item,
|
|
117
|
+
data: copyJSON(item.data),
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
find(path: string, method: string): ResponseOverride | undefined {
|
|
122
|
+
const item = this.entries.get(
|
|
123
|
+
`${method.toUpperCase()} ${normalizePath(path)}`,
|
|
124
|
+
);
|
|
125
|
+
return item ? { ...item, data: copyJSON(item.data) } : undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
clear(path?: string, method?: string) {
|
|
129
|
+
const normalizedPath = path === undefined ? undefined : overridePath(path);
|
|
130
|
+
const normalizedMethod =
|
|
131
|
+
method === undefined ? undefined : normalizeMethod(method);
|
|
132
|
+
for (const [key, item] of this.entries) {
|
|
133
|
+
if (
|
|
134
|
+
(normalizedPath === undefined || normalizedPath === item.path) &&
|
|
135
|
+
(normalizedMethod === undefined || normalizedMethod === item.method)
|
|
136
|
+
)
|
|
137
|
+
this.entries.delete(key);
|
|
138
|
+
}
|
|
139
|
+
return this.list();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const parseInputList = (value: readonly string[] | string) =>
|
|
2
|
+
(typeof value === "string" ? value.split(/[;,]/) : [...value])
|
|
3
|
+
.map((item) => item.trim())
|
|
4
|
+
.filter(Boolean);
|
|
5
|
+
|
|
6
|
+
export const normalizePath = (path: string) => {
|
|
7
|
+
const trimmed = path.trim();
|
|
8
|
+
|
|
9
|
+
if (!trimmed) {
|
|
10
|
+
return "";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
try {
|
|
14
|
+
const base =
|
|
15
|
+
typeof window === "undefined"
|
|
16
|
+
? "https://test-mode.invalid"
|
|
17
|
+
: window.location.origin;
|
|
18
|
+
const parsedUrl = new URL(trimmed, base);
|
|
19
|
+
|
|
20
|
+
return parsedUrl.pathname || "/";
|
|
21
|
+
} catch {
|
|
22
|
+
const withoutHash = trimmed.split("#")[0] ?? trimmed;
|
|
23
|
+
const withoutQuery = withoutHash.split("?")[0] ?? withoutHash;
|
|
24
|
+
|
|
25
|
+
return withoutQuery.startsWith("/") ? withoutQuery : `/${withoutQuery}`;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
const bypass = new AsyncLocalStorage<boolean>();
|
|
3
|
+
export const isTestModeBypassed = () => bypass.getStore() === true;
|
|
4
|
+
/** Control-route authentication and bookkeeping must use real server data. */
|
|
5
|
+
export const withoutTestMode = <T>(operation: () => T): T =>
|
|
6
|
+
bypass.run(true, operation);
|