@schmock/core 2.2.3 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -0
  3. package/dist/abort.d.ts +3 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/abort.js +30 -0
  6. package/dist/binary.d.ts +8 -0
  7. package/dist/binary.d.ts.map +1 -0
  8. package/dist/binary.js +9 -0
  9. package/dist/builder.d.ts +31 -10
  10. package/dist/builder.d.ts.map +1 -1
  11. package/dist/builder.js +804 -203
  12. package/dist/constants.d.ts +38 -0
  13. package/dist/constants.d.ts.map +1 -1
  14. package/dist/constants.js +123 -2
  15. package/dist/errors.d.ts +14 -3
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/errors.js +41 -6
  18. package/dist/helpers.d.ts +9 -0
  19. package/dist/helpers.d.ts.map +1 -1
  20. package/dist/helpers.js +18 -2
  21. package/dist/http-helpers.d.ts +52 -5
  22. package/dist/http-helpers.d.ts.map +1 -1
  23. package/dist/http-helpers.js +153 -37
  24. package/dist/index.d.ts +381 -60
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +9 -3
  27. package/dist/interceptor.d.ts +11 -1
  28. package/dist/interceptor.d.ts.map +1 -1
  29. package/dist/interceptor.js +354 -156
  30. package/dist/parser.d.ts.map +1 -1
  31. package/dist/parser.js +12 -3
  32. package/dist/plugin-pipeline.d.ts +11 -4
  33. package/dist/plugin-pipeline.d.ts.map +1 -1
  34. package/dist/plugin-pipeline.js +117 -39
  35. package/dist/response-normalizer.d.ts +16 -0
  36. package/dist/response-normalizer.d.ts.map +1 -0
  37. package/dist/response-normalizer.js +316 -0
  38. package/dist/response-parser.d.ts.map +1 -1
  39. package/dist/response-parser.js +85 -18
  40. package/dist/route-matcher.d.ts +3 -0
  41. package/dist/route-matcher.d.ts.map +1 -1
  42. package/dist/route-matcher.js +12 -6
  43. package/dist/types.d.ts +7 -2
  44. package/dist/types.d.ts.map +1 -1
  45. package/package.json +18 -8
  46. package/src/audit-core-builder.test.ts +0 -218
  47. package/src/audit-response-guard.test.ts +0 -38
  48. package/src/builder.test.ts +0 -289
  49. package/src/builder.ts +0 -701
  50. package/src/constants.test.ts +0 -99
  51. package/src/constants.ts +0 -73
  52. package/src/debug.test.ts +0 -241
  53. package/src/delay.test.ts +0 -319
  54. package/src/dist-shape.test.ts +0 -35
  55. package/src/errors.test.ts +0 -223
  56. package/src/errors.ts +0 -130
  57. package/src/factory.test.ts +0 -133
  58. package/src/helpers.test.ts +0 -147
  59. package/src/helpers.ts +0 -58
  60. package/src/http-helpers.ts +0 -113
  61. package/src/index.ts +0 -151
  62. package/src/interceptor.test.ts +0 -291
  63. package/src/interceptor.ts +0 -320
  64. package/src/namespace.test.ts +0 -274
  65. package/src/parser.property.test.ts +0 -594
  66. package/src/parser.test.ts +0 -148
  67. package/src/parser.ts +0 -64
  68. package/src/plugin-pipeline.ts +0 -103
  69. package/src/plugin-system.test.ts +0 -602
  70. package/src/response-parser.ts +0 -75
  71. package/src/response-parsing.test.ts +0 -333
  72. package/src/route-matcher.ts +0 -69
  73. package/src/route-matching.test.ts +0 -394
  74. package/src/server.test.ts +0 -165
  75. package/src/smart-defaults.test.ts +0 -361
  76. package/src/steps/async-support.steps.ts +0 -400
  77. package/src/steps/audit-core-builder.steps.ts +0 -188
  78. package/src/steps/audit-onerror-tuple.steps.ts +0 -99
  79. package/src/steps/basic-usage.steps.ts +0 -245
  80. package/src/steps/developer-experience.steps.ts +0 -204
  81. package/src/steps/error-handling.steps.ts +0 -345
  82. package/src/steps/fluent-api.steps.ts +0 -255
  83. package/src/steps/http-methods.steps.ts +0 -331
  84. package/src/steps/interceptor.steps.ts +0 -260
  85. package/src/steps/lifecycle-events.steps.ts +0 -142
  86. package/src/steps/performance-reliability.steps.ts +0 -423
  87. package/src/steps/plugin-integration.steps.ts +0 -280
  88. package/src/steps/request-history.steps.ts +0 -276
  89. package/src/steps/response-delay.steps.ts +0 -88
  90. package/src/steps/route-key-format.steps.ts +0 -99
  91. package/src/steps/standalone-server.steps.ts +0 -233
  92. package/src/steps/state-concurrency.steps.ts +0 -739
  93. package/src/steps/stateful-workflows.steps.ts +0 -353
  94. package/src/types.ts +0 -36
@@ -1,37 +1,180 @@
1
1
  /// <reference path="../schmock.d.ts" />
2
- import { isRouteNotFound, toHttpMethod } from "./constants.js";
3
- /**
4
- * Extract pathname from a URL string, handling both absolute and relative URLs.
5
- */
6
- function extractPathname(url) {
7
- const queryStart = url.indexOf("?");
8
- const urlWithoutQuery = queryStart === -1 ? url : url.slice(0, queryStart);
9
- if (urlWithoutQuery.includes("://")) {
2
+ import { awaitWithAbort, throwIfAborted } from "./abort.js";
3
+ import { isBinaryBody } from "./binary.js";
4
+ import { canonicalizePath, getResponseException, isRouteNotFound, toHttpMethod, } from "./constants.js";
5
+ import { normalizeResponse, serializeResponseBody, } from "./response-normalizer.js";
6
+ const PASSTHROUGH = Symbol("schmock.fetch.passthrough");
7
+ // A lease whose baseUrl filter rejected the request never reached its handler.
8
+ // It is distinct from PASSTHROUGH so the dispatch loop can tell "this owner
9
+ // already ran" from "this lease was not interested in the request at all".
10
+ const FILTERED = Symbol("schmock.fetch.filtered");
11
+ const RELATIVE_REQUEST_BASE = "http://schmock.invalid/";
12
+ let activeSession;
13
+ function getRelativeRequestBase() {
14
+ const candidates = [
15
+ typeof document === "undefined" ? undefined : document.baseURI,
16
+ typeof location === "undefined" ? undefined : location.href,
17
+ ];
18
+ for (const candidate of candidates) {
19
+ if (!candidate)
20
+ continue;
10
21
  try {
11
- return new URL(urlWithoutQuery).pathname;
22
+ return new URL(candidate).href;
12
23
  }
13
24
  catch {
14
- // Fall through to simple extraction
25
+ // Ignore invalid environment globals and use the next fallback.
15
26
  }
16
27
  }
17
- if (!urlWithoutQuery.startsWith("/")) {
18
- return `/${urlWithoutQuery}`;
28
+ return RELATIVE_REQUEST_BASE;
29
+ }
30
+ // The Fetch standard stamps a content type when the body is extracted from a
31
+ // string or URLSearchParams. Node's Request constructor conforms; Bun's omits
32
+ // the header, so identical consumer code would otherwise deliver a string
33
+ // body on Node and an opaque ArrayBuffer on Bun.
34
+ function stampBodyContentType(request, body) {
35
+ if (body == null || request.headers.has("content-type"))
36
+ return;
37
+ if (typeof body === "string") {
38
+ request.headers.set("content-type", "text/plain;charset=UTF-8");
39
+ }
40
+ else if (body instanceof URLSearchParams) {
41
+ request.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
19
42
  }
20
- return urlWithoutQuery;
21
43
  }
22
- /**
23
- * Extract origin (scheme + host + port) from a URL string, or null for
24
- * relative URLs that don't carry one.
25
- */
26
- function extractOrigin(url) {
27
- if (!url.includes("://"))
28
- return null;
44
+ function normalizeFetchRequest(input, init) {
45
+ if (input instanceof Request) {
46
+ // Constructing a Request from another Request transfers its body. Use a
47
+ // clone when the body is inherited so the original remains passthrough-safe.
48
+ const source = init?.body == null ? input.clone() : input;
49
+ const request = new Request(source, init);
50
+ if (init?.body != null) {
51
+ stampBodyContentType(request, init.body);
52
+ }
53
+ else if (request.body != null && !request.headers.has("content-type")) {
54
+ // The body was inherited from the input Request, but init.headers
55
+ // replaces the whole header list, dropping the content type stamped
56
+ // when that body was extracted. Restore it so the handler still sees
57
+ // the body as its original kind. (Bun never stamps at construction,
58
+ // so a string body on a type-less input Request stays opaque there.)
59
+ const inheritedType = input.headers.get("content-type");
60
+ if (inheritedType !== null) {
61
+ request.headers.set("content-type", inheritedType);
62
+ }
63
+ }
64
+ const url = new URL(request.url);
65
+ return {
66
+ request,
67
+ url,
68
+ origin: url.origin,
69
+ };
70
+ }
71
+ if (input instanceof URL) {
72
+ const request = new Request(input, init);
73
+ stampBodyContentType(request, init?.body);
74
+ const url = new URL(request.url);
75
+ return {
76
+ request,
77
+ url,
78
+ origin: url.origin,
79
+ };
80
+ }
81
+ let inputUrl;
82
+ let origin;
29
83
  try {
30
- return new URL(url).origin;
84
+ inputUrl = new URL(input);
85
+ origin = inputUrl.origin;
31
86
  }
32
87
  catch {
33
- return null;
88
+ inputUrl = new URL(input, getRelativeRequestBase());
89
+ origin = null;
90
+ }
91
+ const request = new Request(inputUrl, init);
92
+ stampBodyContentType(request, init?.body);
93
+ return {
94
+ request,
95
+ url: new URL(request.url),
96
+ origin,
97
+ };
98
+ }
99
+ function createInterceptorSession() {
100
+ const baselineFetch = globalThis.fetch;
101
+ const interceptors = [];
102
+ const dispatchFetch = async (input, init) => {
103
+ const snapshot = interceptors.slice();
104
+ if (snapshot.length === 0) {
105
+ return baselineFetch(input, init);
106
+ }
107
+ const normalizedRequest = normalizeFetchRequest(input, init);
108
+ throwIfAborted(normalizedRequest.request.signal);
109
+ // A mock is consulted at most once per request, however many leases it
110
+ // holds: without this, nested providers on one mock would run handle()
111
+ // — and emit request:start/notfound/end — once per lease.
112
+ const consultedOwners = new Set();
113
+ for (let index = snapshot.length - 1; index >= 0; index -= 1) {
114
+ const registered = snapshot[index];
115
+ const { owner } = registered;
116
+ if (owner !== undefined && consultedOwners.has(owner)) {
117
+ continue;
118
+ }
119
+ const result = await awaitWithAbort(registered.intercept(normalizedRequest), normalizedRequest.request.signal);
120
+ throwIfAborted(normalizedRequest.request.signal);
121
+ // The lease filtered the request out before admission, so its owner
122
+ // keeps its turn — a sibling lease may carry a matching baseUrl.
123
+ if (result === FILTERED) {
124
+ continue;
125
+ }
126
+ if (result !== PASSTHROUGH) {
127
+ return result;
128
+ }
129
+ if (owner !== undefined) {
130
+ consultedOwners.add(owner);
131
+ }
132
+ }
133
+ return awaitWithAbort(baselineFetch(normalizedRequest.request), normalizedRequest.request.signal);
134
+ };
135
+ return { baselineFetch, dispatchFetch, interceptors };
136
+ }
137
+ function registerInterceptor(intercept, applyOptions, owner) {
138
+ let session = activeSession;
139
+ if (!session || globalThis.fetch !== session.dispatchFetch) {
140
+ session = createInterceptorSession();
141
+ activeSession = session;
142
+ globalThis.fetch = session.dispatchFetch;
34
143
  }
144
+ const token = Symbol("schmock.fetch.interceptor");
145
+ session.interceptors.push({ token, owner, intercept });
146
+ let active = true;
147
+ return {
148
+ restore() {
149
+ if (!active)
150
+ return;
151
+ active = false;
152
+ const index = session.interceptors.findIndex((entry) => entry.token === token);
153
+ if (index !== -1) {
154
+ session.interceptors.splice(index, 1);
155
+ }
156
+ if (session.interceptors.length !== 0)
157
+ return;
158
+ if (activeSession === session) {
159
+ activeSession = undefined;
160
+ }
161
+ // A library may have installed its own fetch wrapper after Schmock. Its
162
+ // replacement is now the current owner and must not be overwritten.
163
+ if (globalThis.fetch === session.dispatchFetch) {
164
+ globalThis.fetch = session.baselineFetch;
165
+ }
166
+ },
167
+ update(options) {
168
+ // Reconfiguring never touches session.interceptors, so the lease keeps
169
+ // the dispatch position it was registered with.
170
+ if (!active)
171
+ return;
172
+ applyOptions(options);
173
+ },
174
+ get active() {
175
+ return active;
176
+ },
177
+ };
35
178
  }
36
179
  /**
37
180
  * Parse the user-supplied baseUrl option into its origin and path parts.
@@ -46,111 +189,158 @@ function parseBaseUrl(baseUrl) {
46
189
  if (baseUrl.includes("://")) {
47
190
  try {
48
191
  const parsed = new URL(baseUrl);
49
- const rawPath = parsed.pathname;
50
- const path = rawPath === "/" ? "" : rawPath.replace(/\/$/, "");
192
+ const canonicalPath = canonicalizePath(parsed.pathname);
193
+ const path = canonicalPath === "/" ? "" : canonicalPath.replace(/\/$/, "");
51
194
  return { origin: parsed.origin, path };
52
195
  }
53
196
  catch {
54
197
  // Fall through to path-only handling
55
198
  }
56
199
  }
57
- return { origin: null, path: baseUrl.replace(/\/$/, "") };
200
+ const canonicalPath = canonicalizePath(baseUrl);
201
+ const path = canonicalPath === "/" ? "" : canonicalPath.replace(/\/$/, "");
202
+ return { origin: null, path };
58
203
  }
59
- /**
60
- * Extract query parameters from a URL string.
61
- */
62
204
  function extractQuery(url) {
63
- const queryStart = url.indexOf("?");
64
- if (queryStart === -1)
65
- return {};
66
- const params = new URLSearchParams(url.slice(queryStart + 1));
67
- const result = {};
68
- params.forEach((value, key) => {
69
- result[key] = value;
70
- });
71
- return result;
205
+ return Object.fromEntries(url.searchParams);
72
206
  }
73
- /**
74
- * Extract headers from fetch init or Request object.
75
- */
76
- function extractHeaders(input, init) {
207
+ function extractHeaders(request) {
77
208
  const headers = {};
78
- const raw = init?.headers ?? (input instanceof Request ? input.headers : undefined);
79
- if (!raw)
80
- return headers;
81
- if (raw instanceof Headers) {
82
- raw.forEach((value, key) => {
83
- headers[key.toLowerCase()] = value;
84
- });
85
- }
86
- else if (Array.isArray(raw)) {
87
- for (const [key, value] of raw) {
88
- headers[key.toLowerCase()] = value;
89
- }
90
- }
91
- else {
92
- for (const key of Object.keys(raw)) {
93
- headers[key.toLowerCase()] = raw[key];
94
- }
95
- }
209
+ request.headers.forEach((value, key) => {
210
+ headers[key.toLowerCase()] = value;
211
+ });
96
212
  return headers;
97
213
  }
98
- /**
99
- * Extract body from fetch init, parsing JSON when possible.
100
- */
101
- async function extractBody(input, init) {
102
- // Per Fetch spec, init.body overrides Request.body when both are present
103
- const bodyInit = init?.body ?? (input instanceof Request ? input.body : null);
104
- if (bodyInit === null || bodyInit === undefined)
214
+ function normalizeMediaType(contentType) {
215
+ return contentType?.split(";", 1)[0].trim().toLowerCase() ?? "";
216
+ }
217
+ async function extractBody(request) {
218
+ if (request.body === null)
105
219
  return undefined;
106
- // String body — try to parse as JSON
107
- if (typeof bodyInit === "string") {
220
+ const body = request.clone();
221
+ const mediaType = normalizeMediaType(request.headers.get("content-type"));
222
+ if (mediaType === "application/json" || mediaType.endsWith("+json")) {
223
+ const text = await body.text();
108
224
  try {
109
- return JSON.parse(bodyInit);
225
+ return JSON.parse(text);
110
226
  }
111
227
  catch {
112
- return bodyInit;
228
+ return text;
113
229
  }
114
230
  }
115
- // URLSearchParams — convert to key/value object
116
- if (bodyInit instanceof URLSearchParams) {
117
- const result = {};
118
- bodyInit.forEach((value, key) => {
119
- result[key] = value;
120
- });
121
- return result;
231
+ if (mediaType === "application/x-www-form-urlencoded") {
232
+ return Object.fromEntries(new URLSearchParams(await body.text()));
233
+ }
234
+ if (mediaType.startsWith("text/")) {
235
+ return body.text();
236
+ }
237
+ if (mediaType.startsWith("multipart/")) {
238
+ return body.formData();
122
239
  }
123
- // Request with body — clone and read
124
- if (input instanceof Request && !init?.body && input.body) {
240
+ return body.arrayBuffer();
241
+ }
242
+ function isAbortError(error) {
243
+ return (typeof error === "object" &&
244
+ error !== null &&
245
+ "name" in error &&
246
+ error.name === "AbortError");
247
+ }
248
+ function toFetchResponse(response, method) {
249
+ const headers = { ...response.headers };
250
+ const hasContentType = Object.keys(headers).some((name) => name.toLowerCase() === "content-type");
251
+ if (!hasContentType &&
252
+ response.body !== null &&
253
+ response.body !== undefined) {
254
+ if (isBinaryBody(response.body)) {
255
+ headers["content-type"] = "application/octet-stream";
256
+ }
257
+ else if (typeof response.body !== "string") {
258
+ headers["content-type"] = "application/json";
259
+ }
260
+ }
261
+ const normalized = normalizeResponse({ ...response, headers }, method);
262
+ return new Response(serializeResponseBody(normalized) ?? null, {
263
+ status: normalized.status,
264
+ headers: normalized.headers,
265
+ });
266
+ }
267
+ /**
268
+ * Formatted error bodies are always JSON, so the replaced response's own
269
+ * content type must be dropped rather than inherited. Every case variant goes
270
+ * first: leaving a `Content-Type` beside the forced lowercase key makes the
271
+ * pair transport-invalid and the normalizer rejects it.
272
+ */
273
+ function withJsonContentType(headers) {
274
+ const result = {};
275
+ for (const [name, value] of Object.entries(headers ?? {})) {
276
+ if (name.toLowerCase() === "content-type")
277
+ continue;
278
+ result[name] = value;
279
+ }
280
+ result["content-type"] = "application/json";
281
+ return result;
282
+ }
283
+ /**
284
+ * Invoke the errorFormatter for a core-marked exception and build its
285
+ * response, falling back to a minimal safe body when the formatter throws or
286
+ * its result is not serializable.
287
+ *
288
+ * This helper is TOTAL — it never throws. It runs inside the interceptor's
289
+ * `try`, so an escaping error would land in the catch below and invoke the
290
+ * formatter a second time; the re-entrancy is exactly the defect the Express
291
+ * adapter's `sendFormattedError` was shaped to avoid.
292
+ *
293
+ * `responseHeaders` carries the (post-hook) headers of the response being
294
+ * replaced so metadata such as `retry-after` survives. There are two distinct
295
+ * fallbacks. When the inherited headers are untransportable, the send is
296
+ * retried once with the fixed JSON header set and the SAME formatted body —
297
+ * nothing is on the wire yet, and losing the body would silently change the
298
+ * user's error contract. Only a failure of the formatter itself, or of its
299
+ * body, reaches the minimal fallback, which deliberately inherits nothing.
300
+ */
301
+ function formatInterceptedError(errorFormatter, error, responseHeaders, method) {
302
+ try {
303
+ const formatted = errorFormatter(error);
125
304
  try {
126
- return await input.clone().json();
305
+ return toFetchResponse({
306
+ status: 500,
307
+ body: formatted,
308
+ headers: withJsonContentType(responseHeaders),
309
+ }, method);
127
310
  }
128
311
  catch {
129
- try {
130
- return await input.clone().text();
131
- }
132
- catch {
133
- return undefined;
134
- }
312
+ // `formatted` is reused, so the formatter still fires exactly once.
313
+ return toFetchResponse({
314
+ status: 500,
315
+ body: formatted,
316
+ headers: { "content-type": "application/json" },
317
+ }, method);
135
318
  }
136
319
  }
137
- return undefined;
320
+ catch {
321
+ return toFetchResponse({
322
+ status: 500,
323
+ body: { error: "Internal Server Error", code: "INTERNAL_ERROR" },
324
+ headers: { "content-type": "application/json" },
325
+ }, method);
326
+ }
138
327
  }
139
328
  /**
140
329
  * Create a fetch interceptor that routes requests through mock.handle().
330
+ *
331
+ * `owner` identifies the mock behind the lease. Leases sharing an owner are
332
+ * consulted at most once per request, so a mock held by several leases runs
333
+ * its handler — and emits its lifecycle events — once per network request.
141
334
  */
142
- export function createFetchInterceptor(handle, options = {}) {
143
- const { baseUrl, passthrough = true, beforeRequest, beforeResponse, errorFormatter, } = options;
144
- const originalFetch = globalThis.fetch;
145
- let active = true;
146
- globalThis.fetch = async (input, init) => {
147
- // Resolve the URL string
148
- const urlString = input instanceof Request
149
- ? input.url
150
- : input instanceof URL
151
- ? input.href
152
- : input;
153
- const path = extractPathname(urlString);
335
+ export function createFetchInterceptor(handle, options = {}, admitRequest, owner) {
336
+ // The options live in a mutable cell that each request reads once at its
337
+ // start. Reconfiguring a lease in place is what lets an adapter apply new
338
+ // hooks without re-registering — re-registration would move the lease to the
339
+ // front of the dispatch order and steal precedence from other mocks.
340
+ let currentOptions = options;
341
+ return registerInterceptor(async ({ request, url, origin }) => {
342
+ const { baseUrl, passthrough = true, beforeRequest, beforeResponse, errorFormatter, } = currentOptions;
343
+ const path = canonicalizePath(url.pathname);
154
344
  // BaseUrl filter — non-matching requests go straight to real fetch.
155
345
  // Two modes:
156
346
  // - origin form ("https://api.example.com/v1"): require matching
@@ -159,102 +349,110 @@ export function createFetchInterceptor(handle, options = {}) {
159
349
  // Both enforce a segment boundary so "/api" doesn't match "/apiv2".
160
350
  if (baseUrl) {
161
351
  const { origin: baseOrigin, path: basePath } = parseBaseUrl(baseUrl);
162
- if (baseOrigin) {
163
- const reqOrigin = extractOrigin(urlString);
164
- if (reqOrigin !== baseOrigin) {
165
- return originalFetch(input, init);
166
- }
352
+ if (baseOrigin && origin !== baseOrigin) {
353
+ return FILTERED;
167
354
  }
168
355
  if (basePath) {
169
356
  const isMatch = path === basePath || path.startsWith(`${basePath}/`);
170
357
  if (!isMatch) {
171
- return originalFetch(input, init);
358
+ return FILTERED;
172
359
  }
173
360
  }
174
361
  }
175
- // Build adapter request
176
- const method = input instanceof Request ? input.method : (init?.method ?? "GET");
177
- const headers = extractHeaders(input, init);
178
- const query = extractQuery(urlString);
179
- const body = await extractBody(input, init);
180
- let adapterRequest = {
181
- method,
182
- path,
183
- headers,
184
- body,
185
- query,
186
- };
362
+ throwIfAborted(request.signal);
363
+ const initialMethod = toHttpMethod(request.method);
364
+ const admission = admitRequest?.();
365
+ const admittedHandle = admission?.handle ?? handle;
366
+ let effectiveMethod = initialMethod;
187
367
  try {
368
+ const body = await awaitWithAbort(extractBody(request), request.signal);
369
+ throwIfAborted(request.signal);
370
+ let adapterRequest = {
371
+ method: request.method,
372
+ path,
373
+ headers: extractHeaders(request),
374
+ body,
375
+ query: extractQuery(url),
376
+ };
188
377
  // Apply beforeRequest hook
189
378
  if (beforeRequest) {
190
- const modified = await beforeRequest(adapterRequest);
379
+ throwIfAborted(request.signal);
380
+ const modified = await awaitWithAbort(beforeRequest(adapterRequest), request.signal);
381
+ throwIfAborted(request.signal);
191
382
  if (modified) {
192
383
  adapterRequest = modified;
193
384
  }
194
385
  }
195
- const schmockResponse = await handle(toHttpMethod(adapterRequest.method), adapterRequest.path, {
386
+ throwIfAborted(request.signal);
387
+ const requestOptions = {
196
388
  headers: adapterRequest.headers,
197
389
  body: adapterRequest.body,
198
390
  query: adapterRequest.query,
199
- });
391
+ signal: request.signal,
392
+ };
393
+ effectiveMethod = toHttpMethod(adapterRequest.method);
394
+ const schmockResponse = await awaitWithAbort(admittedHandle(effectiveMethod, adapterRequest.path, requestOptions), request.signal);
395
+ throwIfAborted(request.signal);
396
+ // Exception provenance is carried on the response as a non-enumerable
397
+ // symbol, so it must be read BEFORE beforeResponse runs: the
398
+ // documented `{...response}` hook pattern copies only own enumerable
399
+ // properties and would otherwise strip the mark, silently bypassing
400
+ // errorFormatter.
401
+ const internalError = getResponseException(schmockResponse);
200
402
  // Route not found — passthrough or 404
201
403
  if (isRouteNotFound(schmockResponse)) {
202
404
  if (passthrough) {
203
- return originalFetch(input, init);
405
+ return PASSTHROUGH;
204
406
  }
205
- return new Response(JSON.stringify({
206
- error: "No matching mock route found",
207
- code: "ROUTE_NOT_FOUND",
208
- }), {
407
+ return toFetchResponse({
209
408
  status: 404,
409
+ body: {
410
+ error: "No matching mock route found",
411
+ code: "ROUTE_NOT_FOUND",
412
+ },
210
413
  headers: { "content-type": "application/json" },
211
- });
414
+ }, effectiveMethod);
212
415
  }
213
416
  // Apply beforeResponse hook
214
417
  let response = schmockResponse;
215
418
  if (beforeResponse) {
216
- const modified = await beforeResponse(response, adapterRequest);
419
+ throwIfAborted(request.signal);
420
+ const modified = await awaitWithAbort(beforeResponse(response, adapterRequest), request.signal);
421
+ throwIfAborted(request.signal);
217
422
  if (modified) {
218
423
  response = modified;
219
424
  }
220
425
  }
221
- // Build fetch Response
222
- const responseHeaders = new Headers(response.headers);
223
- if (!responseHeaders.has("content-type") &&
224
- response.body !== null &&
225
- response.body !== undefined) {
226
- responseHeaders.set("content-type", "application/json");
426
+ // Only core-marked exceptions reach errorFormatter; a user-defined 500
427
+ // with an error-shaped body stays an ordinary domain response. The
428
+ // POST-hook status gates the replacement (matching Express and
429
+ // Angular): a beforeResponse that rewrites an exception into a 503 or
430
+ // a 200 is honoured instead of being forced back to a formatted 500.
431
+ if (errorFormatter && internalError && response.status === 500) {
432
+ return formatInterceptedError(errorFormatter, internalError, response.headers, effectiveMethod);
227
433
  }
228
- const responseBody = response.body === null || response.body === undefined
229
- ? null
230
- : typeof response.body === "string"
231
- ? response.body
232
- : JSON.stringify(response.body);
233
- return new Response(responseBody, {
234
- status: response.status,
235
- headers: responseHeaders,
236
- });
434
+ return toFetchResponse(response, effectiveMethod);
237
435
  }
238
436
  catch (error) {
437
+ throwIfAborted(request.signal);
438
+ if (isAbortError(error)) {
439
+ throw error;
440
+ }
239
441
  if (errorFormatter) {
240
442
  const formatted = errorFormatter(error instanceof Error ? error : new Error(String(error)));
241
- return new Response(JSON.stringify(formatted), {
443
+ throwIfAborted(request.signal);
444
+ return toFetchResponse({
242
445
  status: 500,
446
+ body: formatted,
243
447
  headers: { "content-type": "application/json" },
244
- });
448
+ }, effectiveMethod);
245
449
  }
246
450
  throw error;
247
451
  }
248
- };
249
- return {
250
- restore() {
251
- if (active) {
252
- globalThis.fetch = originalFetch;
253
- active = false;
254
- }
255
- },
256
- get active() {
257
- return active;
258
- },
259
- };
452
+ finally {
453
+ admission?.release();
454
+ }
455
+ }, (nextOptions) => {
456
+ currentOptions = nextOptions ?? {};
457
+ }, owner);
260
458
  }
@@ -1 +1 @@
1
- {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,UAAU,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAyC3D"}
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,UAAU,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAmD3D"}
package/dist/parser.js CHANGED
@@ -1,4 +1,4 @@
1
- import { toHttpMethod } from "./constants.js";
1
+ import { canonicalizePath, normalizePath, toHttpMethod } from "./constants.js";
2
2
  import { RouteParseError } from "./errors.js";
3
3
  /**
4
4
  * Parse 'METHOD /path' route key format
@@ -12,11 +12,20 @@ import { RouteParseError } from "./errors.js";
12
12
  * // => { method: 'GET', path: '/users/:id', pattern: /^\/users\/([^/]+)$/, params: ['id'] }
13
13
  */
14
14
  export function parseRouteKey(routeKey) {
15
- const match = routeKey.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (.+)$/);
15
+ // The path group must start with "/": every transport (server, interceptor,
16
+ // adapters) delivers a leading-slash pathname, so a slash-less key such as
17
+ // "GET users" compiles a route no request can ever reach. `.*` is kept
18
+ // deliberately — hostile-but-reachable segments (spaces, tabs, unicode) must
19
+ // still parse.
20
+ const match = routeKey.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (\/.*)$/);
16
21
  if (!match) {
17
22
  throw new RouteParseError(routeKey, 'Expected format: "METHOD /path" (e.g., "GET /users")');
18
23
  }
19
- const [, method, path] = match;
24
+ const [, method, rawPath] = match;
25
+ // Canonicalize once, here, so `path`, `pattern`, the duplicate check, the
26
+ // static-route Map key and getRoutes() all agree on one spelling: the
27
+ // percent-encoded transport form with a single trailing slash stripped.
28
+ const path = normalizePath(canonicalizePath(rawPath));
20
29
  // Parameter names are restricted to [A-Za-z0-9_-] so that surrounding
21
30
  // literals (".json", brackets, parens, etc.) terminate the name and can
22
31
  // be escaped without bleeding into the parameter regex. Build the