{"name":"node-request-interceptor","description":"Low-level HTTP/HTTPS/XHR request interception library for NodeJS","version":"0.3.0","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/jest":"^25.2.1","@types/node":"^13.13.2","@types/node-fetch":"^2.5.7","axios":"^0.19.2","jest":"^25.4.0","node-fetch":"^2.6.0","rimraf":"^3.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.3.0","dist":{"shasum":"9a0b717c5f5f4b09a4423db17d5b0bea5f7260c1","integrity":"sha512-yrEFqAIrdDYTB+5+m6Mk/hyHLy95bhMKfhH+VWvQ90kr+ILykRcE1wDt0OhsQr2sEkfYJYE1eTSt/rpd/lN4ig==","tarball":"http://registry-npm.ywwl.com/node-request-interceptor/download/node-request-interceptor-0.3.0.tgz","fileCount":37,"unpackedSize":66146,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfBXfDCRA9TVsSAnZWagAA4CwP/R9qIVVMYK4ZQvxw6ogP\nwt+q0EP885LY8QUZOiEglYyoYxhNYvIWNWuvu2sUyomqq/ofZV8w/mgajW5O\nj4xI9F3/ZnMwOK7lU39DzjGb268UOviPGIuMULWNGILnOwwfQ55Im6nUwxOH\nwXGWjNPXdRqenrerE9vonLiAQbhMMEVgEO6SW/rBZluPrGJu4fCoAMQcEm4v\nQRcrJAGr4gfZwnP7uxBwZIJylXjMZbZQ0qpDjs+najj1xzHYkQqYw4IGb1iZ\nAbMvbU7QokreqQdAIWSiX3tpD+4tyhFPv1SC+pCErEexLNu5AV+TO4kvPhhR\nWQiVrxD3qdvuH3/Ks1/vFFcvTaMQph5NPOB3bqPwK54DIcP6EsEGzh2UOzBb\nfG1QOsgdzWLDgYrjUmtzoNUK1wJqac0f2bUNHYq4zSNys1QZWLBdqgAbNWak\nc4AwVbCz/D40i4mvf0lII3O4J3kLyY8otEvKGjOq5IKcp1tDDLu2xRz1Q9b4\nP/vv36dUcy7WE1AiBqnRduVgv7xQFjEegMZEDDSEr1EMLVZoi+U7t8C0AXlv\nh7bQfPf5aVFq7XDnY9UeVwkVmIbEe8Fh1KntyG54WAH4jEMwmf+wkDAVc8YV\ndsKqlUqgZLpj9dvaeJZN7eJNi0UCX+AZh2J8mQw4tkVLi/cteHU1Drnn5gJE\nuAJX\r\n=/n3F\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICk+yB/lOXcr9ssG06ckBaNLOkVxCFPRNPyerhS2187JAiAMNlPciKRFsqE6h5nhkc0fYs6G5TDL0t9Y1kpZhShReQ=="}],"size":16436,"noattachment":false,"key":"/node-request-interceptor/-/node-request-interceptor-0.3.0.tgz"},"maintainers":[{"name":"kettanaito","email":"kettanaito@gmail.com"}],"_npmUser":{"name":"kettanaito","email":"kettanaito@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/node-request-interceptor_0.3.0_1594193859174_0.636704811411821"},"_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":1594193859373,"_cnpm_publish_time":1594193859373,"dist-tags":{"latest":"0.6.3"}}