{"name":"node-request-interceptor","description":"Low-level HTTP/HTTPS/XHR request interception library for NodeJS","version":"0.6.1","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.3.0","headers-utils":"^1.2.0","strict-event-emitter":"^0.1.0"},"keywords":["request","intercept","http","https","xmlhttprequest","xhr","fetch","low-level","mock"],"_id":"node-request-interceptor@0.6.1","dist":{"shasum":"7536e5b002fedadb01d5c7c32851c5f875b66ce5","integrity":"sha512-Bj/5rImX8rECeKUrv7CEESay/tjqfdGZwpkd0qO9Km9ZeOBxKac45bCzeZDk9KOWbOp/Lxke+MiY0jTCHpSPTQ==","tarball":"http://registry-npm.ywwl.com/node-request-interceptor/download/node-request-interceptor-0.6.1.tgz","fileCount":82,"unpackedSize":135035,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJf3M3OCRA9TVsSAnZWagAAORkQAI11NIdfDMpFoNSTGKkH\njpYEqPKWmc+fyA1A0ZfrrLh/uAo4G7NZ04wIJYI7mVaxz+K7OXZdrDmyAGVA\nlDCIKrng44QEG/DtfVmw1d0la6Qt/0TE7F8LtdApnXlv90vHVaF2aedMFxV9\nNfSeOXptZbA06I/BflEVSpKHshQv7og8AjTWK4c3KHkxt+ygRdf+XYuoknNK\n6nvzYqvIqsSLteO9ugmY5e2aXf2S593YgVN6eHn/rnFZ5WeunjULERUKD1IA\ndK6GhRhRSKTcOg8yJfEMDfsXnWV7H7eA2lqdpm3fuXyUaAv9zbk5LC6L+R3K\nRL52gB3/24llcVqARvpQ74dAj4K11V4P0NCNblo4rtAY+ij0Nc45G1GtOI0+\nuJiK+DQeIPxb2lTZ+Yo42wGa992nPy1LU1zzVGTuwHajm+j9UErv5GxkTfZv\nX9NTD2ZxY53ZYyTwbYU6IsXEDPWfxq8qDcIqkREmEDnrAkWkMP/qfQS0qTsJ\nV8Lgw/emN2OafJku56Ll07vaIBy6AgR5mlGhS745ClR0n9+4aOiaSojzbG9t\nvvneDWqqq5JB58MFaKLlHMEpM+PQWFiFSKW6Lq7IFg/Z7A8UFo0i4pYflzAR\nSlk0h0FbFMMm2skJ9pYDJIFP4VbyHaT4wyFN+cLV/TIg0VamyvRNe+1huLOs\nCUwN\r\n=Js4a\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICYHq32AfvLCNYJXcTrbq1T0VSlqVzjkLZMSHT2vX9mtAiEApdnU/pSoptku5vAhOXgbqfBgacOPs93DKHGH7ekPYJY="}],"size":35729,"noattachment":false,"key":"/node-request-interceptor/-/node-request-interceptor-0.6.1.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.6.1_1608306126327_0.7928816253882742"},"_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":1608306126486,"_cnpm_publish_time":1608306126486,"dist-tags":{"latest":"0.6.3"}}