New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

msw

Package Overview
Dependencies
Maintainers
1
Versions
279
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

msw - npm Package Compare versions

Comparing version 2.1.3 to 2.1.4

2

lib/core/sharedOptions.d.ts
import { Emitter } from 'strict-event-emitter';
import { UnhandledRequestStrategy } from './utils/request/onUnhandledRequest.js';
import './RequestHandler-CwjkprZE.js';
import './typeUtils.js';

@@ -6,0 +4,0 @@ interface SharedOptions {

2

lib/core/utils/handleRequest.js

@@ -52,3 +52,3 @@ "use strict";

if (!lookupResult.data) {
await (0, import_onUnhandledRequest.onUnhandledRequest)(request, handlers, options.onUnhandledRequest);
await (0, import_onUnhandledRequest.onUnhandledRequest)(request, options.onUnhandledRequest);
emitter.emit("request:unhandled", { request, requestId });

@@ -55,0 +55,0 @@ emitter.emit("request:end", { request, requestId });

@@ -1,4 +0,1 @@

import { R as RequestHandler } from '../../RequestHandler-CwjkprZE.js';
import '../../typeUtils.js';
interface UnhandledRequestPrint {

@@ -10,4 +7,4 @@ warning(): void;

type UnhandledRequestStrategy = 'bypass' | 'warn' | 'error' | UnhandledRequestCallback;
declare function onUnhandledRequest(request: Request, handlers: Array<RequestHandler>, strategy?: UnhandledRequestStrategy): Promise<void>;
declare function onUnhandledRequest(request: Request, strategy?: UnhandledRequestStrategy): Promise<void>;
export { type UnhandledRequestCallback, type UnhandledRequestPrint, type UnhandledRequestStrategy, onUnhandledRequest };
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;

@@ -20,10 +18,2 @@ var __export = (target, all) => {

};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -35,111 +25,16 @@ var onUnhandledRequest_exports = {};

module.exports = __toCommonJS(onUnhandledRequest_exports);
var import_js_levenshtein = __toESM(require("@bundled-es-modules/js-levenshtein"));
var import_HttpHandler = require("../../handlers/HttpHandler.js");
var import_GraphQLHandler = require("../../handlers/GraphQLHandler.js");
var import_parseGraphQLRequest = require("../internal/parseGraphQLRequest.js");
var import_getPublicUrlFromRequest = require("./getPublicUrlFromRequest.js");
var import_isStringEqual = require("../internal/isStringEqual.js");
var import_devUtils = require("../internal/devUtils.js");
const getStringMatchScore = import_js_levenshtein.default;
const MAX_MATCH_SCORE = 3;
const MAX_SUGGESTION_COUNT = 4;
const TYPE_MATCH_DELTA = 0.5;
function groupHandlersByType(handlers) {
return handlers.reduce(
(groups, handler) => {
if (handler instanceof import_HttpHandler.HttpHandler) {
groups.http.push(handler);
}
if (handler instanceof import_GraphQLHandler.GraphQLHandler) {
groups.graphql.push(handler);
}
return groups;
},
{
http: [],
graphql: []
}
);
}
function getHttpHandlerScore() {
return (request, handler) => {
const { path, method } = handler.info;
if (path instanceof RegExp || method instanceof RegExp) {
return Infinity;
}
const hasSameMethod = (0, import_isStringEqual.isStringEqual)(request.method, method);
const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
const requestPublicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(request);
const score = getStringMatchScore(requestPublicUrl, path);
return score - methodScoreDelta;
};
}
function getGraphQLHandlerScore(parsedQuery) {
return (_, handler) => {
if (typeof parsedQuery.operationName === "undefined") {
return Infinity;
}
const { operationType, operationName } = handler.info;
if (typeof operationName !== "string") {
return Infinity;
}
const hasSameOperationType = parsedQuery.operationType === operationType;
const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
const score = getStringMatchScore(parsedQuery.operationName, operationName);
return score - operationTypeScoreDelta;
};
}
function getSuggestedHandler(request, handlers, getScore) {
const suggestedHandlers = handlers.reduce((suggestions, handler) => {
const score = getScore(request, handler);
return suggestions.concat([[score, handler]]);
}, []).sort(([leftScore], [rightScore]) => leftScore - rightScore).filter(([score]) => score <= MAX_MATCH_SCORE).slice(0, MAX_SUGGESTION_COUNT).map(([, handler]) => handler);
return suggestedHandlers;
}
function getSuggestedHandlersMessage(handlers) {
if (handlers.length > 1) {
return `Did you mean to request one of the following resources instead?
async function onUnhandledRequest(request, strategy = "warn") {
const publicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(request);
const unhandledRequestMessage = `intercepted a request without a matching request handler:
${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
}
return `Did you mean to request "${handlers[0].info.header}" instead?`;
}
async function onUnhandledRequest(request, handlers, strategy = "warn") {
const parsedGraphQLQuery = await (0, import_parseGraphQLRequest.parseGraphQLRequest)(request).catch(
() => null
);
const publicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(request);
function generateHandlerSuggestion() {
const handlerGroups = groupHandlersByType(handlers);
const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.http;
const suggestedHandlers = getSuggestedHandler(
request,
relevantHandlers,
parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getHttpHandlerScore()
);
return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
}
function getGraphQLRequestHeader(parsedGraphQLRequest) {
if (!parsedGraphQLRequest?.operationName) {
return `anonymous ${parsedGraphQLRequest?.operationType} (${request.method} ${publicUrl})`;
}
return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`;
}
function generateUnhandledRequestMessage() {
const requestHeader = parsedGraphQLQuery ? getGraphQLRequestHeader(parsedGraphQLQuery) : `${request.method} ${publicUrl}`;
const handlerSuggestion = generateHandlerSuggestion();
const messageTemplate = [
`intercepted a request without a matching request handler:`,
` \u2022 ${requestHeader}`,
handlerSuggestion,
`If you still wish to intercept this unhandled request, please create a request handler for it.
Read more: https://mswjs.io/docs/getting-started/mocks`
].filter(Boolean);
return messageTemplate.join("\n\n");
}
\u2022 ${request.method} ${publicUrl}
If you still wish to intercept this unhandled request, please create a request handler for it.
Read more: https://mswjs.io/docs/getting-started/mocks`;
function applyStrategy(strategy2) {
const message = generateUnhandledRequestMessage();
switch (strategy2) {
case "error": {
import_devUtils.devUtils.error("Error: %s", message);
import_devUtils.devUtils.error("Error: %s", unhandledRequestMessage);
throw new Error(

@@ -152,3 +47,3 @@ import_devUtils.devUtils.formatMessage(

case "warn": {
import_devUtils.devUtils.warn("Warning: %s", message);
import_devUtils.devUtils.warn("Warning: %s", unhandledRequestMessage);
break;

@@ -155,0 +50,0 @@ }

@@ -5,3 +5,3 @@ /* eslint-disable */

/**
* Mock Service Worker (2.1.3).
* Mock Service Worker (2.1.4).
* @see https://github.com/mswjs/msw

@@ -8,0 +8,0 @@ * - Please do NOT modify this file.

{
"name": "msw",
"version": "2.1.3",
"version": "2.1.4",
"description": "Seamless REST/GraphQL API mocking library for browser and Node.js.",

@@ -96,3 +96,2 @@ "main": "./lib/core/index.js",

"@bundled-es-modules/cookie": "^2.0.0",
"@bundled-es-modules/js-levenshtein": "^2.0.1",
"@bundled-es-modules/statuses": "^1.0.1",

@@ -103,3 +102,2 @@ "@mswjs/cookies": "^1.1.0",

"@types/cookie": "^0.6.0",
"@types/js-levenshtein": "^1.1.3",
"@types/statuses": "^2.0.4",

@@ -112,3 +110,2 @@ "chalk": "^4.1.2",

"is-node-process": "^1.2.0",
"js-levenshtein": "^1.1.6",
"outvariant": "^1.4.2",

@@ -115,0 +112,0 @@ "path-to-regexp": "^6.2.0",

@@ -85,3 +85,3 @@ import { until } from '@open-draft/until'

if (!lookupResult.data) {
await onUnhandledRequest(request, handlers, options.onUnhandledRequest)
await onUnhandledRequest(request, options.onUnhandledRequest)
emitter.emit('request:unhandled', { request, requestId })

@@ -88,0 +88,0 @@ emitter.emit('request:end', { request, requestId })

@@ -8,7 +8,3 @@ /**

} from './onUnhandledRequest'
import { HttpHandler, HttpMethods } from '../../handlers/HttpHandler'
import { ResponseResolver } from '../../handlers/RequestHandler'
const resolver: ResponseResolver = () => void 0
const fixtures = {

@@ -30,14 +26,2 @@ warningWithoutSuggestions: `\

Read more: https://mswjs.io/docs/getting-started/mocks`,
warningWithSuggestions: (suggestions: string) => `\
[MSW] Warning: intercepted a request without a matching request handler:
• GET /api
Did you mean to request one of the following resources instead?
${suggestions}
If you still wish to intercept this unhandled request, please create a request handler for it.
Read more: https://mswjs.io/docs/getting-started/mocks`,
}

@@ -57,3 +41,2 @@

new Request(new URL('http://localhost/api')),
[],
'bypass',

@@ -67,7 +50,3 @@ )

test('supports the "warn" request strategy', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[],
'warn',
)
await onUnhandledRequest(new Request(new URL('http://localhost/api')), 'warn')

@@ -79,7 +58,3 @@ expect(console.warn).toHaveBeenCalledWith(fixtures.warningWithoutSuggestions)

await expect(
onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[],
'error',
),
onUnhandledRequest(new Request(new URL('http://localhost/api')), 'error'),
).rejects.toThrow(

@@ -97,3 +72,3 @@ '[MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.',

const request = new Request(new URL('/user', 'http://localhost:3000'))
await onUnhandledRequest(request, [], callback)
await onUnhandledRequest(request, callback)

@@ -120,3 +95,3 @@ expect(callback).toHaveBeenCalledTimes(1)

const request = new Request(new URL('http://localhost/api'))
await expect(onUnhandledRequest(request, [], callback)).rejects.toThrow(
await expect(onUnhandledRequest(request, callback)).rejects.toThrow(
`[MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.`,

@@ -136,7 +111,3 @@ )

test('does not print any suggestions given no handlers to suggest', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[],
'warn',
)
await onUnhandledRequest(new Request(new URL('http://localhost/api')), 'warn')

@@ -146,68 +117,2 @@ expect(console.warn).toHaveBeenCalledWith(fixtures.warningWithoutSuggestions)

test('does not print any suggestions given no handlers are similar', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[
// None of the defined request handlers match the actual request URL
// to be used as suggestions.
new HttpHandler(HttpMethods.GET, 'https://api.github.com', resolver),
new HttpHandler(HttpMethods.GET, 'https://api.stripe.com', resolver),
],
'warn',
)
expect(console.warn).toHaveBeenCalledWith(fixtures.warningWithoutSuggestions)
})
test('respects RegExp as a request handler method', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[new HttpHandler(/^GE/, 'http://localhost/api', resolver)],
'warn',
)
expect(console.warn).toHaveBeenCalledWith(fixtures.warningWithoutSuggestions)
})
test('sorts the suggestions by relevance', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[
new HttpHandler(HttpMethods.GET, '/', resolver),
new HttpHandler(HttpMethods.GET, 'https://api.example.com/api', resolver),
new HttpHandler(HttpMethods.POST, '/api', resolver),
],
'warn',
)
expect(console.warn).toHaveBeenCalledWith(
fixtures.warningWithSuggestions(`\
• POST /api
• GET /`),
)
})
test('does not print more than 4 suggestions', async () => {
await onUnhandledRequest(
new Request(new URL('http://localhost/api')),
[
new HttpHandler(HttpMethods.GET, '/ap', resolver),
new HttpHandler(HttpMethods.GET, '/api', resolver),
new HttpHandler(HttpMethods.GET, '/api-1', resolver),
new HttpHandler(HttpMethods.GET, '/api-2', resolver),
new HttpHandler(HttpMethods.GET, '/api-3', resolver),
new HttpHandler(HttpMethods.GET, '/api-4', resolver),
],
'warn',
)
expect(console.warn).toHaveBeenCalledWith(
fixtures.warningWithSuggestions(`\
• GET /api
• GET /ap
• GET /api-1
• GET /api-2`),
)
})
test('throws an exception given unknown request strategy', async () => {

@@ -217,3 +122,2 @@ await expect(

new Request(new URL('http://localhost/api')),
[],
// @ts-expect-error Intentional unknown strategy.

@@ -220,0 +124,0 @@ 'invalid-strategy',

@@ -1,20 +0,4 @@

import jsLevenshtein from '@bundled-es-modules/js-levenshtein'
import { RequestHandler } from '../../handlers/RequestHandler'
import { HttpHandler } from '../../handlers/HttpHandler'
import { GraphQLHandler } from '../../handlers/GraphQLHandler'
import {
ParsedGraphQLQuery,
ParsedGraphQLRequest,
parseGraphQLRequest,
} from '../internal/parseGraphQLRequest'
import { getPublicUrlFromRequest } from './getPublicUrlFromRequest'
import { isStringEqual } from '../internal/isStringEqual'
import { devUtils } from '../internal/devUtils'
const getStringMatchScore = jsLevenshtein
const MAX_MATCH_SCORE = 3
const MAX_SUGGESTION_COUNT = 4
const TYPE_MATCH_DELTA = 0.5
export interface UnhandledRequestPrint {

@@ -36,179 +20,14 @@ warning(): void

interface RequestHandlerGroups {
http: Array<HttpHandler>
graphql: Array<GraphQLHandler>
}
function groupHandlersByType(
handlers: Array<RequestHandler>,
): RequestHandlerGroups {
return handlers.reduce<RequestHandlerGroups>(
(groups, handler) => {
if (handler instanceof HttpHandler) {
groups.http.push(handler)
}
if (handler instanceof GraphQLHandler) {
groups.graphql.push(handler)
}
return groups
},
{
http: [],
graphql: [],
},
)
}
type RequestHandlerSuggestion = [number, RequestHandler]
type ScoreGetterFn<RequestHandlerType extends RequestHandler> = (
request: Request,
handler: RequestHandlerType,
) => number
function getHttpHandlerScore(): ScoreGetterFn<HttpHandler> {
return (request, handler) => {
const { path, method } = handler.info
if (path instanceof RegExp || method instanceof RegExp) {
return Infinity
}
const hasSameMethod = isStringEqual(request.method, method)
// Always treat a handler with the same method as a more similar one.
const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0
const requestPublicUrl = getPublicUrlFromRequest(request)
const score = getStringMatchScore(requestPublicUrl, path)
return score - methodScoreDelta
}
}
function getGraphQLHandlerScore(
parsedQuery: ParsedGraphQLQuery,
): ScoreGetterFn<GraphQLHandler> {
return (_, handler) => {
if (typeof parsedQuery.operationName === 'undefined') {
return Infinity
}
const { operationType, operationName } = handler.info
if (typeof operationName !== 'string') {
return Infinity
}
const hasSameOperationType = parsedQuery.operationType === operationType
// Always treat a handler with the same operation type as a more similar one.
const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0
const score = getStringMatchScore(parsedQuery.operationName, operationName)
return score - operationTypeScoreDelta
}
}
function getSuggestedHandler(
request: Request,
handlers: Array<HttpHandler> | Array<GraphQLHandler>,
getScore: ScoreGetterFn<HttpHandler> | ScoreGetterFn<GraphQLHandler>,
): Array<RequestHandler> {
const suggestedHandlers = (handlers as Array<RequestHandler>)
.reduce<Array<RequestHandlerSuggestion>>((suggestions, handler) => {
const score = getScore(request, handler as any)
return suggestions.concat([[score, handler]])
}, [])
.sort(([leftScore], [rightScore]) => leftScore - rightScore)
.filter(([score]) => score <= MAX_MATCH_SCORE)
.slice(0, MAX_SUGGESTION_COUNT)
.map(([, handler]) => handler)
return suggestedHandlers
}
function getSuggestedHandlersMessage(handlers: RequestHandler[]) {
if (handlers.length > 1) {
return `\
Did you mean to request one of the following resources instead?
${handlers.map((handler) => ` • ${handler.info.header}`).join('\n')}`
}
return `Did you mean to request "${handlers[0].info.header}" instead?`
}
export async function onUnhandledRequest(
request: Request,
handlers: Array<RequestHandler>,
strategy: UnhandledRequestStrategy = 'warn',
): Promise<void> {
const parsedGraphQLQuery = await parseGraphQLRequest(request).catch(
() => null,
)
const publicUrl = getPublicUrlFromRequest(request)
const unhandledRequestMessage = `intercepted a request without a matching request handler:\n\n \u2022 ${request.method} ${publicUrl}\n\nIf you still wish to intercept this unhandled request, please create a request handler for it.\nRead more: https://mswjs.io/docs/getting-started/mocks`
function generateHandlerSuggestion(): string {
/**
* @note Ignore exceptions during GraphQL request parsing because at this point
* we cannot assume the unhandled request is a valid GraphQL request.
* If the GraphQL parsing fails, just don't treat it as a GraphQL request.
*/
const handlerGroups = groupHandlersByType(handlers)
const relevantHandlers = parsedGraphQLQuery
? handlerGroups.graphql
: handlerGroups.http
const suggestedHandlers = getSuggestedHandler(
request,
relevantHandlers,
parsedGraphQLQuery
? getGraphQLHandlerScore(parsedGraphQLQuery)
: getHttpHandlerScore(),
)
return suggestedHandlers.length > 0
? getSuggestedHandlersMessage(suggestedHandlers)
: ''
}
function getGraphQLRequestHeader(
parsedGraphQLRequest: ParsedGraphQLRequest<any>,
): string {
if (!parsedGraphQLRequest?.operationName) {
return `anonymous ${parsedGraphQLRequest?.operationType} (${request.method} ${publicUrl})`
}
return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`
}
function generateUnhandledRequestMessage(): string {
const requestHeader = parsedGraphQLQuery
? getGraphQLRequestHeader(parsedGraphQLQuery)
: `${request.method} ${publicUrl}`
const handlerSuggestion = generateHandlerSuggestion()
const messageTemplate = [
`intercepted a request without a matching request handler:`,
` \u2022 ${requestHeader}`,
handlerSuggestion,
`\
If you still wish to intercept this unhandled request, please create a request handler for it.
Read more: https://mswjs.io/docs/getting-started/mocks\
`,
].filter(Boolean)
return messageTemplate.join('\n\n')
}
function applyStrategy(strategy: UnhandledRequestStrategy) {
// Generate handler suggestions only when applying the strategy.
// This saves bandwidth for scenarios when developers opt-out
// from the default unhandled request handling strategy.
const message = generateUnhandledRequestMessage()
switch (strategy) {
case 'error': {
// Print a developer-friendly error.
devUtils.error('Error: %s', message)
devUtils.error('Error: %s', unhandledRequestMessage)

@@ -224,3 +43,3 @@ // Throw an exception to halt request processing and not perform the original request.

case 'warn': {
devUtils.warn('Warning: %s', message)
devUtils.warn('Warning: %s', unhandledRequestMessage)
break

@@ -227,0 +46,0 @@ }

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc