{"name":"node-request-interceptor","description":"Low-level HTTP/HTTPS/XHR request interception library for NodeJS","version":"0.5.8","main":"lib/index.js","typings":"lib/index.d.ts","author":{"name":"Artem Zakharchenko"},"license":"MIT","scripts":{"start":"tsc --build -w","test":"jest --no-cache --runInBand","clean":"rimraf lib","build":"yarn clean && tsc --build","prepublishOnly":"yarn test && yarn build"},"repository":{"type":"git","url":"https://github.com/mswjs/node-request-interceptor"},"devDependencies":{"@types/cors":"^2.8.7","@types/express":"^4.17.8","@types/jest":"^25.2.1","@types/node":"^13.13.2","@types/node-fetch":"^2.5.7","@types/supertest":"^2.0.10","axios":"^0.19.2","body-parser":"^1.19.0","cors":"^2.8.5","express":"^4.17.1","jest":"^25.4.0","node-fetch":"^2.6.0","rimraf":"^3.0.2","supertest":"^4.0.2","ts-jest":"^25.4.0","typescript":"^3.8.3"},"dependencies":{"@open-draft/until":"^1.0.3","debug":"^4.1.1","headers-utils":"^1.2.0"},"keywords":["request","intercept","http","https","xmlhttprequest","xhr","fetch","low-level","mock"],"_id":"node-request-interceptor@0.5.8","dist":{"shasum":"1777c05eae25f468c891f24075f4087ac2ea3f3b","integrity":"sha512-fO+3XGPboRX8760kOpg/6zGIWtbJoTTSIr359ig1ubzunQppAOCYva3SOIXKX+BHiGNgJsefbAjIEQKvV9S8Kg==","tarball":"http://registry-npm.ywwl.com/node-request-interceptor/download/node-request-interceptor-0.5.8.tgz","fileCount":79,"unpackedSize":127503,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfyMoCCRA9TVsSAnZWagAAMY0P/jrDu/+MsDzt1k9f3lCH\n8p5do/KD/zB8NPbdbdrJCTcWM67e2tHOGtKV+D95dTBa9qqXbpt5Zr3T/zkS\nIbBb9yK1ut8cxY2U3KdFYTgmToPKyNnsc5UkdcEirpjNvmHnH6rZJwV1FuQe\nJfZWqQ2+AAfONylUtokCOPTQmdwxNnPrdh8kOxUBSVqMXDiZrcw/4SY/ucDB\nOgswbL9Uq2X/qGiKLLLRpajERD9/r/rKHZf0pmaDwo8Nk26AnIch710wtqrp\niKEQvKwwCBP9wtbYBmQyHC9DITSjLxhVR/2qhDVWJ083iuEGLt0JnDeoun+H\nETdz5g1EAR2/Yej4CyCFEm7qEBFf118Jf4p0UZu9GaZFv0UiQ9rYwUB2ZCSw\n3Kj7lmcx0qBLx2iV1LY1pholBEIWUgWDcY/Ne1HgO0K+8d4HaJkeNcBbQFA4\nb2GxmlVwdR5wDD8q9xLJljVjhn1O9V2nQHgohvVINrDy/y4U5Mxpfq9q0Ft0\nrCn86J8dg9i3ar506FyT4uQyKWH3FNu7jnalwEBx0hErb3aXkmO5zkpmwimi\nwvu9RDIx0jU9Ho/p4u4zzlSZsv79lATPdxOM+Ib5z1mg9n2JUvhgm4mmIfVO\npY3klwh55TTR2L/RsP2+70Ij2DqY4uwHLBgnW2tL3jRnxZIwkwSNmyANUJci\nCBo/\r\n=88CD\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHzCgl2RW0UALRD2/x/5MKv/E9Y+d6yyV7mJt00W15lOAiEAiZVh8u4MKEeX1sJfOx6D34iAHFW4byBHDiT14UT+XZU="}],"size":34102,"noattachment":false,"key":"/node-request-interceptor/-/node-request-interceptor-0.5.8.tgz"},"_npmUser":{"name":"kettanaito","email":"kettanaito@gmail.com"},"directories":{},"maintainers":[{"name":"kettanaito","email":"kettanaito@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/node-request-interceptor_0.5.8_1606994434221_0.9373223529419188"},"_hasShrinkwrap":false,"readme":"[![Latest version](https://img.shields.io/npm/v/node-request-interceptor.svg)](https://www.npmjs.com/package/node-request-interceptor)\n[![Build status](https://img.shields.io/circleci/project/github/mswjs/node-request-interceptor/master.svg)](https://app.circleci.com/pipelines/github/mswjs/node-request-interceptor)\n\n# `node-request-interceptor`\n\nLow-level HTTP/HTTPS/XHR request interception library for NodeJS.\n\n**Intercepts any requests issued by:**\n\n- `http.get`/`http.request`\n- `https.get`/`https.request`\n- `fetch`\n- `XMLHttpRequest`\n- Any third-party libraries that utilize the modules above (i.e. `request`, `node-fetch`, etc.)\n\n## Motivation\n\nWhile there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, exposing you a high-level API that includes request matching, timeouts, retries, and so forth.\n\nThis library is a strip-to-bone implementation that provides as little abstraction as possible to execute arbitrary logic upon any request in NodeJS. It's primarily designed as an underlying component for a high-level API mocking solutions.\n\n### How is this library different?\n\nAs interception is often combined with request route matching, some libraries can determine whether a request should be mocked _before_ it actually happens. This approach is not suitable for this library, as it rather _intercepts all requests_ and then let's you decide which ones should be mocked. This affects the level at which interception happens, and also the way mocked/original response is constructed, in comparison to other solutions.\n\n### Why XMLHttpRequest?\n\nAlthough NodeJS has no `XMLHttpRequest` implementation, this library covers it for the sake of processes that still run in NodeJS, but emulate a browser-like environment (i.e. `jsdom` when running tests in Jest).\n\n## What this library does\n\nThis library monkey-patches the following native modules:\n\n- `http.get`/`http.request`\n- `https.get`/`https.request`\n- `XMLHttpRequest`\n\nOnce patched, it provides an interface to execute an arbitrary logic upon any outgoing request using a request middleware function.\n\n- Bypasses all requests by default, so your network channel is not affected.\n- Handles an abstract response object returned from the request middleware as an actual response for the occurred request (taking into account the difference in constructing a response for different clients).\n\n## What this library doesn't do\n\n- Does **not** provide any request matching logic.\n- Does **not** decide how to handle requests.\n- Does **not** run in a browser (although supports `jsdom`).\n\n## Getting started\n\n```bash\nnpm install node-request-interceptor\n```\n\n## API\n\n### `RequestInterceptor(interceptors: Interceptor[])`\n\n```js\nimport { RequestInterceptor } from 'node-request-interceptor'\nimport withDefaultInterceptors from 'node-request-interceptor/presets/default'\n\nconst interceptor = new RequestInterceptor(withDefaultInterceptors)\n```\n\n> Using the `/presets/default` interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin.\n\n### Interceptors\n\nThis library utilizes a concept of an _interceptor_–a module that performs necessary patching, handles a mocked response, and restores patched instances.\n\n**The list of interceptors:**\n\n- `/interceptors/ClientRequest`\n- `/interceptors/XMLHttpRequest`\n\nTo use one, or multiple interceptors, import and provide them to the `RequestInterceptor` constructor.\n\n```js\nimport { RequestInterceptors } from 'node-request-interceptor'\nimport { interceptXMLHttpRequest } from 'node-request-interceptor/interceptors/XMLHttpRequest'\n\n// This `interceptor` instance would handle only XMLHttpRequest,\n// ignoring requests issued via `http`/`https` modules.\nconst interceptor = new RequestInterceptors([interceptXMLHttpRequest])\n```\n\n> Interceptors are crucial in leveraging environment-specific module overrides. Certain environments (i.e. React Native) do not have access to native NodeJS modules (like `http`). Importing such modules raises an exception, and must be avoided.\n\n### Methods\n\n#### `.use(middleware: (req: InterceptedRequest, ref: IncomingMessage | XMLHttpRequest) => MockedResponse): void`\n\nApplies a given middleware function to an intercepted request. May return a [`MockedResponse`](#MockedResponse) object that is going to be used to respond to an intercepted request.\n\n##### Requests monitoring\n\n```js\ninterceptor.use((req) => {\n  // Will print to stdout any outgoing requests\n  // without affecting their responses\n  console.log('%s %s', req.method, req.url.href)\n})\n```\n\n##### Response mocking\n\nWhen a request middleware returns a [`MockedResponse`](#MockedResponse) object, it will be returned as the response to the intercepted request. This library automatically creates a proper response instance according to the request issuing module (`http`/`XMLHttpRequest`).\n\n```js\ninterceptor.use((req) => {\n  if (['https://google.com'].includes(req.url.origin)) {\n    // Will return a mocked response for any request\n    // that is issued from the \"https://google.com\" origin.\n    return {\n      status: 301,\n      headers: {\n        'x-powered-by': 'node-request-interceptor',\n      },\n      body: JSON.stringify({\n        message: 'Hey, I am a mocked response',\n      }),\n    }\n  }\n})\n```\n\n#### `.restore(): void`\n\nRestores all patched modules and stops the interception of any future requests.\n\n```js\ninterceptor.restore()\n```\n\n---\n\n### `InterceptedRequest`\n\n```ts\ninterface InterceptedRequest {\n  url: URL\n  method: string\n  headers?: http.OutgoingHttpHeaders\n  body?: string\n}\n```\n\n---\n\n### `MockedResponse`\n\nWhenever a `MockedResponse` object is returned from the request middleware function, it's being used to constructs a relevant response for the intercepted request.\n\n```ts\ninterface MockedResponse {\n  status?: number\n  statusText?: string\n  headers?: Record<string, string | string[]>\n  body?: string\n}\n```\n\n## Special mention\n\nThe following libraries were used as an inspiration to write this low-level API:\n\n- [`node`](https://github.com/nodejs/node)\n- [`nock`](https://github.com/nock/nock)\n- [`mock-xmlhttprequest`](https://github.com/berniegp/mock-xmlhttprequest)\n","publish_time":1606994434408,"_cnpm_publish_time":1606994434408,"dist-tags":{"latest":"0.6.3"}}