msw 0.20.1 → 0.20.5

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.
@@ -1,4 +1,4 @@
1
- var statuses = {
1
+ var codes = {
2
2
  "100": "Continue",
3
3
  "101": "Switching Protocols",
4
4
  "102": "Processing",
@@ -64,6 +64,11 @@ var statuses = {
64
64
  "511": "Network Authentication Required"
65
65
  };
66
66
 
67
+ var statuses = /*#__PURE__*/Object.freeze({
68
+ __proto__: null,
69
+ 'default': codes
70
+ });
71
+
67
72
  const status = (statusCode, statusText) => {
68
73
  return (res) => {
69
74
  res.status = statusCode;
@@ -1,6 +1,6 @@
1
1
  import { a as set, s as status, d as delay, f as fetch } from './fetch-deps.js';
2
2
  import { d as data, e as errors } from './errors-deps.js';
3
- import { j as jsonParse, p as prepareRequest, a as prepareResponse, b as getTimestamp, c as getStatusCodeColor } from './getStatusCodeColor-deps.js';
3
+ import { j as jsonParse, m as matchRequestUrl, p as prepareRequest, a as prepareResponse, b as getTimestamp, c as getStatusCodeColor } from './matchRequest-deps.js';
4
4
 
5
5
  // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
6
6
  var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
@@ -3015,11 +3015,12 @@ function parseQuery(query, definitionOperation = 'query') {
3015
3015
  operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
3016
3016
  };
3017
3017
  }
3018
- const createGraphQLHandler = (operationType) => {
3018
+ const createGraphQLHandler = (operationType, mask) => {
3019
3019
  return (expectedOperation, resolver) => {
3020
3020
  return {
3021
3021
  resolver,
3022
3022
  parse(req) {
3023
+ var _a;
3023
3024
  // According to the GraphQL specification, a GraphQL request can be issued
3024
3025
  // using both "GET" and "POST" methods.
3025
3026
  switch (req.method) {
@@ -3040,7 +3041,7 @@ const createGraphQLHandler = (operationType) => {
3040
3041
  };
3041
3042
  }
3042
3043
  case 'POST': {
3043
- if (!req.body) {
3044
+ if (!((_a = req.body) === null || _a === void 0 ? void 0 : _a.query)) {
3044
3045
  return null;
3045
3046
  }
3046
3047
  const { query, variables } = req.body;
@@ -3062,10 +3063,13 @@ const createGraphQLHandler = (operationType) => {
3062
3063
  if (!parsed || !parsed.operationName) {
3063
3064
  return false;
3064
3065
  }
3066
+ // Match the request URL against a given mask,
3067
+ // in case of an endpoint-specific request handler.
3068
+ const hasMatchingMask = matchRequestUrl(req.url, mask);
3065
3069
  const isMatchingOperation = expectedOperation instanceof RegExp
3066
3070
  ? expectedOperation.test(parsed.operationName)
3067
3071
  : expectedOperation === parsed.operationName;
3068
- return isMatchingOperation;
3072
+ return isMatchingOperation && hasMatchingMask.matches;
3069
3073
  },
3070
3074
  defineContext() {
3071
3075
  return graphqlContext;
@@ -3087,9 +3091,16 @@ const createGraphQLHandler = (operationType) => {
3087
3091
  };
3088
3092
  };
3089
3093
  };
3090
- const graphql = {
3091
- query: createGraphQLHandler('query'),
3092
- mutation: createGraphQLHandler('mutation'),
3093
- };
3094
+ const graphqlStandardHandlers = {
3095
+ query: createGraphQLHandler('query', '*'),
3096
+ mutation: createGraphQLHandler('mutation', '*'),
3097
+ };
3098
+ function createGraphQLLink(uri) {
3099
+ return {
3100
+ query: createGraphQLHandler('query', uri),
3101
+ mutation: createGraphQLHandler('mutation', uri),
3102
+ };
3103
+ }
3104
+ const graphql = Object.assign(Object.assign({}, graphqlStandardHandlers), { link: createGraphQLLink });
3094
3105
 
3095
3106
  export { graphql, graphqlContext, parseQuery };
@@ -1,5 +1,5 @@
1
1
  import { s as status, a as set, d as delay, f as fetch, j as json } from './fetch-deps.js';
2
- import { a as cookie, b as body, t as text, x as xml } from './xml-deps.js';
2
+ import { c as cookie, b as body, t as text, x as xml } from './xml-deps.js';
3
3
  import { d as data, e as errors } from './errors-deps.js';
4
4
 
5
5
  var index = /*#__PURE__*/Object.freeze({
package/lib/esm/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { c as createCommonjsModule, s as status, a as set, d as delay, f as fetch, l as lib$1, i as isNodeProcess } from './fetch-deps.js';
2
- import { c as cookie } from './xml-deps.js';
2
+ import { p as parse_1 } from './xml-deps.js';
3
3
  import './errors-deps.js';
4
4
  export { i as context } from './index-deps.js';
5
- import { g as getJsonBody } from './getStatusCodeColor-deps.js';
5
+ import { g as getJsonBody } from './matchRequest-deps.js';
6
+ export { m as matchRequestUrl } from './matchRequest-deps.js';
6
7
  import { i as isStringEqual } from './rest-deps.js';
7
8
  export { R as RESTMethods, r as rest, a as restContext } from './rest-deps.js';
8
9
  export { graphql, graphqlContext } from './graphql.js';
@@ -59,11 +60,20 @@ exports.until = until.until;
59
60
  });
60
61
 
61
62
  /**
62
- * Attempts to resolve a Service Worker instance from any of its states:
63
- * active, installing, or waiting.
63
+ * Attempts to resolve a Service Worker instance from a given registration,
64
+ * regardless of its state (active, installing, waiting).
64
65
  */
65
- const getWorkerByRegistration = (registration) => {
66
- return registration.active || registration.installing || registration.waiting;
66
+ const getWorkerByRegistration = (registration, absoluteWorkerUrl) => {
67
+ const allStates = [
68
+ registration.active,
69
+ registration.installing,
70
+ registration.waiting,
71
+ ];
72
+ const existingStates = allStates.filter(Boolean);
73
+ const mockWorker = existingStates.find((worker) => {
74
+ return worker.scriptURL === absoluteWorkerUrl;
75
+ });
76
+ return mockWorker || null;
67
77
  };
68
78
 
69
79
  /**
@@ -84,9 +94,7 @@ const getWorkerInstance = (url, options) => __awaiter(void 0, void 0, void 0, fu
84
94
  const [, mockRegistrations] = yield lib.until(() => __awaiter(void 0, void 0, void 0, function* () {
85
95
  const registrations = yield navigator.serviceWorker.getRegistrations();
86
96
  return registrations.filter((registration) => {
87
- const worker = getWorkerByRegistration(registration);
88
- // Filter out other workers that can be associated with this page
89
- return (worker === null || worker === void 0 ? void 0 : worker.scriptURL) === absoluteWorkerUrl;
97
+ return getWorkerByRegistration(registration, absoluteWorkerUrl);
90
98
  });
91
99
  }));
92
100
  if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
@@ -98,21 +106,24 @@ const getWorkerInstance = (url, options) => __awaiter(void 0, void 0, void 0, fu
98
106
  // at this point we are sure it's hard reload that falls into this clause.
99
107
  location.reload();
100
108
  }
101
- const [, existingRegistration] = yield lib.until(() => {
102
- return navigator.serviceWorker.getRegistration(url);
103
- });
109
+ const [existingRegistration] = mockRegistrations;
104
110
  if (existingRegistration) {
105
111
  // Update existing service worker to ensure it's up-to-date
106
112
  return existingRegistration.update().then(() => {
107
113
  return [
108
- getWorkerByRegistration(existingRegistration),
114
+ getWorkerByRegistration(existingRegistration, absoluteWorkerUrl),
109
115
  existingRegistration,
110
116
  ];
111
117
  });
112
118
  }
113
119
  const [error, instance] = yield lib.until(() => __awaiter(void 0, void 0, void 0, function* () {
114
120
  const registration = yield navigator.serviceWorker.register(url, options);
115
- return [getWorkerByRegistration(registration), registration];
121
+ return [
122
+ // Compare existing worker registration by its worker URL,
123
+ // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
124
+ getWorkerByRegistration(registration, absoluteWorkerUrl),
125
+ registration,
126
+ ];
116
127
  }));
117
128
  if (error) {
118
129
  const isWorkerMissing = error.message.includes('(404)');
@@ -219,49 +230,72 @@ const response = Object.assign(createResponseComposition(), {
219
230
  * Returns a mocked response for a given request using following request handlers.
220
231
  */
221
232
  const getResponse = (req, handlers) => __awaiter(void 0, void 0, void 0, function* () {
222
- const [relevantHandler, parsedRequest] = handlers.reduce((found, requestHandler) => {
223
- // Skip any request handlers lookup if a handler is already found,
224
- // or the current handler is a one-time handler that's been already used.
225
- if ((found && found[0]) || requestHandler.shouldSkip) {
226
- return found;
227
- }
233
+ const relevantHandlers = handlers
234
+ .filter((requestHandler) => {
235
+ // Skip a handler if it has been already used for a one-time response.
236
+ return !requestHandler.shouldSkip;
237
+ })
238
+ .map((requestHandler) => {
228
239
  // Parse the captured request to get additional information.
229
240
  // Make the predicate function accept all the necessary information
230
241
  // to decide on the interception.
231
242
  const parsedRequest = requestHandler.parse
232
243
  ? requestHandler.parse(req)
233
244
  : null;
234
- if (requestHandler.predicate(req, parsedRequest)) {
235
- return [requestHandler, parsedRequest];
236
- }
237
- }, []) || [null, null];
238
- if (relevantHandler == null) {
245
+ return [requestHandler, parsedRequest];
246
+ })
247
+ .filter(([requestHandler, parsedRequest]) => {
248
+ return requestHandler.predicate(req, parsedRequest);
249
+ });
250
+ if (relevantHandlers.length == 0) {
251
+ // Handle a scenario when a request has no relevant request handlers.
252
+ // In that case it would be bypassed (performed as-is).
239
253
  return {
240
254
  handler: null,
241
255
  response: null,
242
256
  };
243
257
  }
244
- const { getPublicRequest, defineContext, resolver } = relevantHandler;
245
- const publicRequest = getPublicRequest
246
- ? getPublicRequest(req, parsedRequest)
247
- : req;
248
- const context = defineContext ? defineContext(publicRequest) : defaultContext;
249
- const mockedResponse = yield resolver(publicRequest, response, context);
250
- // Handle a scenario when a request handler is present,
251
- // but returns no mocked response (i.e. misses a `return res()` statement).
252
- if (!mockedResponse) {
258
+ const { requestHandler, parsedRequest, mockedResponse, publicRequest, } = yield relevantHandlers.reduce((asyncAcc, [requestHandler, parsedRequest]) => __awaiter(void 0, void 0, void 0, function* () {
259
+ // Now the reduce function is async so we need to await if response was found
260
+ const acc = yield asyncAcc;
261
+ // If a first not empty response was found we'll stop evaluating other requests
262
+ if (acc.requestHandler) {
263
+ return acc;
264
+ }
265
+ const { getPublicRequest, defineContext, resolver } = requestHandler;
266
+ const publicRequest = getPublicRequest
267
+ ? getPublicRequest(req, parsedRequest)
268
+ : req;
269
+ const context = defineContext
270
+ ? defineContext(publicRequest)
271
+ : defaultContext;
272
+ const mockedResponse = yield resolver(publicRequest, response, context);
273
+ if (!mockedResponse) {
274
+ return acc;
275
+ }
276
+ if (mockedResponse && mockedResponse.once) {
277
+ // When responded with a one-time response, match the relevant request handler
278
+ // as skipped, so it cannot affect the captured requests anymore.
279
+ requestHandler.shouldSkip = true;
280
+ }
281
+ return {
282
+ requestHandler,
283
+ parsedRequest,
284
+ mockedResponse,
285
+ publicRequest,
286
+ };
287
+ }), Promise.resolve({ mockedResponse: null }));
288
+ // Although reducing a list of relevant request handlers, it's possible
289
+ // that in the end there will be no handler associted with the request
290
+ // (i.e. if relevant handlers are fall-through).
291
+ if (!requestHandler) {
253
292
  return {
254
- handler: relevantHandler,
293
+ handler: null,
255
294
  response: null,
256
295
  };
257
296
  }
258
- if (mockedResponse.once) {
259
- // When responded with a one-time response, match the relevant request handler
260
- // as skipped, so it cannot affect the captured requests anymore.
261
- relevantHandler.shouldSkip = true;
262
- }
263
297
  return {
264
- handler: relevantHandler,
298
+ handler: requestHandler,
265
299
  response: mockedResponse,
266
300
  publicRequest,
267
301
  parsedRequest,
@@ -302,7 +336,7 @@ function parseRequestBody(body, headers) {
302
336
  }
303
337
 
304
338
  function getAllCookies() {
305
- return cookie.parse(document.cookie);
339
+ return parse_1(document.cookie);
306
340
  }
307
341
  /**
308
342
  * Returns relevant document cookies based on the request `credentials` option.
package/lib/esm/index2.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { d as delay, f as fetch, j as json, a as set, s as status } from './fetch-deps.js';
2
- export { b as body, a as cookie, t as text, x as xml } from './xml-deps.js';
2
+ export { b as body, c as cookie, t as text, x as xml } from './xml-deps.js';
3
3
  export { d as data, e as errors } from './errors-deps.js';
@@ -0,0 +1,168 @@
1
+ import { l as lib, c as createCommonjsModule } from './fetch-deps.js';
2
+
3
+ /**
4
+ * Parses a given string into a JSON.
5
+ * Does not throw an exception on an invalid JSON string.
6
+ */
7
+ function jsonParse(str) {
8
+ try {
9
+ return JSON.parse(str);
10
+ }
11
+ catch (error) {
12
+ return undefined;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Returns a parsed JSON from a given valid body string,
18
+ * otherwise returns a given body string as-is.
19
+ */
20
+ function getJsonBody(body) {
21
+ return jsonParse(body) || body;
22
+ }
23
+
24
+ /**
25
+ * Formats a mocked request for introspection in browser's console.
26
+ */
27
+ function prepareRequest(req) {
28
+ return Object.assign(Object.assign({}, req), { headers: req.headers.getAllHeaders() });
29
+ }
30
+
31
+ /**
32
+ * Formats a mocked response for introspection in browser's console.
33
+ */
34
+ function prepareResponse(res) {
35
+ var _a;
36
+ const resHeaders = lib.listToHeaders(res.headers);
37
+ return Object.assign(Object.assign({}, res), {
38
+ // Parse a response JSON body for preview in the logs
39
+ body: ((_a = resHeaders.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json')) ? getJsonBody(res.body)
40
+ : res.body });
41
+ }
42
+
43
+ function getTimestamp() {
44
+ const now = new Date();
45
+ return [now.getHours(), now.getMinutes(), now.getSeconds()]
46
+ .map(String)
47
+ .map((chunk) => chunk.slice(0, 2))
48
+ .map((chunk) => chunk.padStart(2, '0'))
49
+ .join(':');
50
+ }
51
+
52
+ /**
53
+ * Returns a HEX color for a given response status code number.
54
+ */
55
+ function getStatusCodeColor(status) {
56
+ if (status < 300) {
57
+ return '#69AB32';
58
+ }
59
+ if (status < 400) {
60
+ return '#F0BB4B';
61
+ }
62
+ return '#E95F5D';
63
+ }
64
+
65
+ /**
66
+ * Converts a string path to a Regular Expression.
67
+ * Transforms path parameters into named RegExp groups.
68
+ */
69
+ const pathToRegExp = (path) => {
70
+ const pattern = path
71
+ // Escape literal dots
72
+ .replace(/\./g, '\\.')
73
+ // Escape literal slashes
74
+ .replace(/\//g, '/')
75
+ // Escape literal question marks
76
+ .replace(/\?/g, '\\?')
77
+ // Ignore trailing slashes
78
+ .replace(/\/+$/, '')
79
+ // Replace wildcard with any single character sequence
80
+ .replace(/\*+/g, '.+')
81
+ // Replace parameters with named capturing groups
82
+ .replace(/:([^\d|^\/][a-zA-Z0-9]*(?=(?:\/|\\.)|$))/g, (_, match) => `(?<${match}>.+?)`)
83
+ // Allow optional trailing slash
84
+ .concat('(\\/|$)');
85
+ return new RegExp(pattern, 'g');
86
+ };
87
+
88
+ /**
89
+ * Matches a given url against a path.
90
+ */
91
+ const match = (path, url) => {
92
+ const expression = path instanceof RegExp ? path : pathToRegExp(path);
93
+ const match = expression.exec(url) || false;
94
+ // Matches in strict mode: match string should equal to input (url)
95
+ // Otherwise loose matches will be considered truthy:
96
+ // match('/messages/:id', '/messages/123/users') // true
97
+ const matches = path instanceof RegExp ? !!match : !!match && match[0] === match.input;
98
+ return {
99
+ matches,
100
+ params: match && matches ? match.groups || null : null,
101
+ };
102
+ };
103
+
104
+ var getCleanUrl_1 = createCommonjsModule(function (module, exports) {
105
+ Object.defineProperty(exports, "__esModule", { value: true });
106
+ /**
107
+ * Removes query parameters and hashes from a given URL.
108
+ */
109
+ function getCleanUrl(url, isAbsolute) {
110
+ if (isAbsolute === void 0) { isAbsolute = true; }
111
+ return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('');
112
+ }
113
+ exports.getCleanUrl = getCleanUrl;
114
+ });
115
+
116
+ /**
117
+ * Resolves a relative URL to the absolute URL with the same hostname.
118
+ * Ignores regular expressions.
119
+ */
120
+ const resolveRelativeUrl = (mask) => {
121
+ // Global `location` object doesn't exist in Node.
122
+ // Relative request predicate URL cannot become absolute.
123
+ const hasLocation = typeof location !== 'undefined';
124
+ return typeof mask === 'string' && mask.startsWith('/')
125
+ ? `${hasLocation ? location.origin : ''}${mask}`
126
+ : mask;
127
+ };
128
+
129
+ /**
130
+ * Converts a given request handler mask into a URL, if given a valid URL string.
131
+ * Otherwise, returns the mask as-is.
132
+ */
133
+ function resolveMask(mask) {
134
+ if (mask instanceof RegExp) {
135
+ return mask;
136
+ }
137
+ try {
138
+ // Attempt to create a URL instance out of the mask string.
139
+ // Resolve mask to an absolute URL, because even a valid relative URL
140
+ // cannot be converted into the URL instance (required absolute URL only).
141
+ return new URL(resolveRelativeUrl(mask));
142
+ }
143
+ catch (error) {
144
+ // Otherwise, the mask is a path string.
145
+ return mask;
146
+ }
147
+ }
148
+
149
+ function getCleanMask(resolvedMask) {
150
+ return resolvedMask instanceof URL
151
+ ? getCleanUrl_1.getCleanUrl(resolvedMask)
152
+ : resolvedMask instanceof RegExp
153
+ ? resolvedMask
154
+ : resolveRelativeUrl(resolvedMask);
155
+ }
156
+
157
+ /**
158
+ * Returns the result of matching given request URL
159
+ * against a mask.
160
+ */
161
+ function matchRequestUrl(url, mask) {
162
+ const resolvedMask = resolveMask(mask);
163
+ const cleanMask = getCleanMask(resolvedMask);
164
+ const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
165
+ return match(cleanMask, cleanRequestUrl);
166
+ }
167
+
168
+ export { prepareResponse as a, getTimestamp as b, getStatusCodeColor as c, getJsonBody as g, jsonParse as j, matchRequestUrl as m, prepareRequest as p, resolveMask as r };
@@ -1,6 +1,6 @@
1
1
  import { c as createCommonjsModule, b as commonjsGlobal, a as set, s as status, j as json, d as delay, f as fetch } from './fetch-deps.js';
2
- import { a as cookie, b as body, t as text, x as xml } from './xml-deps.js';
3
- import { p as prepareRequest, a as prepareResponse, b as getTimestamp, c as getStatusCodeColor } from './getStatusCodeColor-deps.js';
2
+ import { c as cookie, b as body, t as text, x as xml } from './xml-deps.js';
3
+ import { r as resolveMask, m as matchRequestUrl, p as prepareRequest, a as prepareResponse, b as getTimestamp, c as getStatusCodeColor } from './matchRequest-deps.js';
4
4
 
5
5
  /**
6
6
  * Performs a case-insensitive comparison of two given strings.
@@ -1350,90 +1350,6 @@ Url.prototype.parseHost = function() {
1350
1350
  if (host) this.hostname = host;
1351
1351
  };
1352
1352
 
1353
- /**
1354
- * Converts a string path to a Regular Expression.
1355
- * Transforms path parameters into named RegExp groups.
1356
- */
1357
- const pathToRegExp = (path) => {
1358
- const pattern = path
1359
- // Escape literal dots
1360
- .replace(/\./g, '\\.')
1361
- // Escape literal slashes
1362
- .replace(/\//g, '/')
1363
- // Escape literal question marks
1364
- .replace(/\?/g, '\\?')
1365
- // Ignore trailing slashes
1366
- .replace(/\/+$/, '')
1367
- // Replace wildcard with any single character sequence
1368
- .replace(/\*+/g, '.+')
1369
- // Replace parameters with named capturing groups
1370
- .replace(/:([^\d|^\/][a-zA-Z0-9]*(?=(?:\/|\\.)|$))/g, (_, match) => `(?<${match}>.+?)`)
1371
- // Allow optional trailing slash
1372
- .concat('(\\/|$)');
1373
- return new RegExp(pattern, 'g');
1374
- };
1375
-
1376
- /**
1377
- * Matches a given url against a path.
1378
- */
1379
- const match = (path, url) => {
1380
- const expression = path instanceof RegExp ? path : pathToRegExp(path);
1381
- const match = expression.exec(url) || false;
1382
- // Matches in strict mode: match string should equal to input (url)
1383
- // Otherwise loose matches will be considered truthy:
1384
- // match('/messages/:id', '/messages/123/users') // true
1385
- const matches = path instanceof RegExp ? !!match : !!match && match[0] === match.input;
1386
- return {
1387
- matches,
1388
- params: match && matches ? match.groups || null : null,
1389
- };
1390
- };
1391
-
1392
- var getCleanUrl_1 = createCommonjsModule(function (module, exports) {
1393
- Object.defineProperty(exports, "__esModule", { value: true });
1394
- /**
1395
- * Removes query parameters and hashes from a given URL.
1396
- */
1397
- function getCleanUrl(url, isAbsolute) {
1398
- if (isAbsolute === void 0) { isAbsolute = true; }
1399
- return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('');
1400
- }
1401
- exports.getCleanUrl = getCleanUrl;
1402
- });
1403
-
1404
- /**
1405
- * Resolves a relative URL to the absolute URL with the same hostname.
1406
- * Ignores regular expressions.
1407
- */
1408
- const resolveRelativeUrl = (mask) => {
1409
- // Global `location` object doesn't exist in Node.
1410
- // Relative request predicate URL cannot become absolute.
1411
- const hasLocation = typeof location !== 'undefined';
1412
- return typeof mask === 'string' && mask.startsWith('/')
1413
- ? `${hasLocation ? location.origin : ''}${mask}`
1414
- : mask;
1415
- };
1416
-
1417
- /**
1418
- * Converts a given request handler mask into a URL, if given a valid URL string.
1419
- * Otherwise, returns the mask as-is.
1420
- */
1421
- function resolveMask(mask) {
1422
- if (mask instanceof RegExp) {
1423
- return mask;
1424
- }
1425
- try {
1426
- // Attempt to create a URL instance out of the mask string.
1427
- // Resolve mask to an absolute URL, because even a valid relative URL
1428
- // cannot be converted into the URL instance (required absolute URL only).
1429
- return new URL(resolveRelativeUrl(mask));
1430
- }
1431
- catch (error) {
1432
- // Otherwise, the mask is a path string.
1433
- return mask;
1434
- }
1435
- }
1436
-
1437
1353
  var RESTMethods;
1438
1354
  (function (RESTMethods) {
1439
1355
  RESTMethods["GET"] = "GET";
@@ -1457,24 +1373,21 @@ const restContext = {
1457
1373
  const createRestHandler = (method) => {
1458
1374
  return (mask, resolver) => {
1459
1375
  const resolvedMask = resolveMask(mask);
1460
- const cleanMask = resolvedMask instanceof URL
1461
- ? getCleanUrl_1.getCleanUrl(resolvedMask)
1462
- : resolvedMask instanceof RegExp
1463
- ? resolvedMask
1464
- : resolveRelativeUrl(resolvedMask);
1465
1376
  return {
1466
- predicate(req) {
1467
- // Ignore query parameters and hash when matching requests URI
1468
- const cleanUrl = getCleanUrl_1.getCleanUrl(req.url);
1469
- const hasSameMethod = isStringEqual(method, req.method);
1470
- const urlMatch = match(cleanMask, cleanUrl);
1471
- return hasSameMethod && urlMatch.matches;
1377
+ parse(req) {
1378
+ // Match the request during parsing to prevent matching it twice
1379
+ // in order to get the request URL parameters.
1380
+ const match = matchRequestUrl(req.url, mask);
1381
+ return {
1382
+ match,
1383
+ };
1384
+ },
1385
+ predicate(req, parsedRequest) {
1386
+ return isStringEqual(method, req.method) && parsedRequest.match.matches;
1472
1387
  },
1473
- getPublicRequest(req) {
1388
+ getPublicRequest(req, parsedRequest) {
1474
1389
  // Get request path parameters based on the given mask
1475
- const params = (mask &&
1476
- match(resolveRelativeUrl(mask), getCleanUrl_1.getCleanUrl(req.url)).params) ||
1477
- {};
1390
+ const params = (mask && parsedRequest.match.params) || {};
1478
1391
  return Object.assign(Object.assign({}, req), { params });
1479
1392
  },
1480
1393
  resolver,
package/lib/esm/rest.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import './fetch-deps.js';
2
2
  import './xml-deps.js';
3
- import './getStatusCodeColor-deps.js';
3
+ import './matchRequest-deps.js';
4
4
  export { R as RESTMethods, r as rest, a as restContext } from './rest-deps.js';
@@ -199,21 +199,18 @@ function tryDecode(str, decode) {
199
199
  }
200
200
  }
201
201
 
202
- var cookie = {
203
- parse: parse_1,
204
- serialize: serialize_1
205
- };
206
-
207
202
  /**
208
203
  * Sets a given cookie on the response.
209
204
  * @example
210
205
  * res(cookie('name', 'value'))
211
206
  */
212
- const cookie$1 = (name, value, options) => {
207
+ const cookie = (name, value, options) => {
213
208
  return (res) => {
214
- const serializedCookie = cookie.serialize(name, value, options);
209
+ const serializedCookie = serialize_1(name, value, options);
215
210
  res.headers.set('Set-Cookie', serializedCookie);
216
- document.cookie = serializedCookie;
211
+ if (typeof document !== 'undefined') {
212
+ document.cookie = serializedCookie;
213
+ }
217
214
  return res;
218
215
  };
219
216
  };
@@ -256,4 +253,4 @@ const xml = (body) => {
256
253
  };
257
254
  };
258
255
 
259
- export { cookie$1 as a, body as b, cookie as c, text as t, xml as x };
256
+ export { body as b, cookie as c, parse_1 as p, text as t, xml as x };
@@ -1,4 +1,4 @@
1
- import cookieUtils from 'cookie';
1
+ import * as cookieUtils from 'cookie';
2
2
  import { ResponseTransformer } from '../response';
3
3
  /**
4
4
  * Sets a given cookie on the response.