@serenity-js/rest
Version:
Serenity/JS Screenplay Pattern library for interacting with REST and other HTTP-based services, supporting comprehensive API testing and blended testing scenarios
83 lines • 3.07 kB
JavaScript
import { ConfigurationError } from '@serenity-js/core';
import { Agent } from 'agent-base';
import * as http from 'http';
import { HttpProxyAgent } from 'http-proxy-agent';
import * as https from 'https';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { LRUCache } from 'lru-cache';
const protocols = [
...HttpProxyAgent.protocols,
];
/**
* A simplified version of the original
* [`ProxyAgent`](https://github.com/TooTallNate/proxy-agents/blob/5923589c2e5206504772c250ac4f20fc31122d3b/packages/proxy-agent/src/index.ts)
* with fewer dependencies.
*
* Delegates requests to the appropriate `Agent` subclass based on the "proxy"
* environment variables, or the provided `agentOptions.getProxyForUrl` callback.
*
* Uses an LRU cache to prevent unnecessary creation of proxy `http.Agent` instances.
*/
export class ProxyAgent extends Agent {
agentOptions;
static proxyAgents = {
http: [HttpProxyAgent, HttpsProxyAgent],
https: [HttpProxyAgent, HttpsProxyAgent],
};
/**
* Cache for `Agent` instances.
*/
cache = new LRUCache({
max: 20,
dispose: (value, key) => value.destroy(),
});
httpAgent;
httpsAgent;
getProxyForUrl;
constructor(agentOptions) {
super(agentOptions);
this.agentOptions = agentOptions;
this.httpAgent = agentOptions?.httpAgent || new http.Agent(agentOptions);
this.httpsAgent = agentOptions?.httpsAgent || new https.Agent(agentOptions);
this.getProxyForUrl = agentOptions?.getProxyForUrl;
}
async connect(request, options) {
const { secureEndpoint } = options;
const isWebSocket = request.getHeader('upgrade') === 'websocket';
const protocol = secureEndpoint
? (isWebSocket ? 'wss:' : 'https:')
: (isWebSocket ? 'ws:' : 'http:');
const host = request.getHeader('host');
const url = new URL(request.path, `${protocol}//${host}`).href;
const proxy = this.getProxyForUrl(url);
if (!proxy) {
return secureEndpoint
? this.httpsAgent
: this.httpAgent;
}
// attempt to get a cached `http.Agent` instance first
const cacheKey = `${protocol}+${proxy}`;
let agent = this.cache.get(cacheKey);
if (!agent) {
agent = this.createAgent(new URL(proxy), secureEndpoint || isWebSocket);
this.cache.set(cacheKey, agent);
}
return agent;
}
createAgent(proxyUrl, requiresTls) {
const protocol = proxyUrl.protocol.replace(':', '');
if (!this.isValidProtocol(protocol)) {
throw new ConfigurationError(`Unsupported protocol for proxy URL: ${proxyUrl}`);
}
const ctor = ProxyAgent.proxyAgents[protocol][requiresTls ? 1 : 0];
return new ctor(proxyUrl, this.agentOptions);
}
isValidProtocol(v) {
return protocols.includes(v);
}
destroy() {
this.cache.clear();
super.destroy();
}
}
//# sourceMappingURL=ProxyAgent.js.map