UNPKG

nyro

Version:

A simple and effective promise-based HTTP & HTTP/2 request library that supports all HTTP methods.

971 lines (970 loc) 64.8 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var http = __importStar(require("http")); var https = __importStar(require("https")); var http2 = __importStar(require("http2")); var zlib = __importStar(require("zlib")); var url_1 = require("url"); var utils_1 = require("./utils"); var combineUrl_1 = __importDefault(require("../helpers/combineUrl")); var errorHandler_1 = __importDefault(require("../helpers/errorHandler")); var http_proxy_agent_1 = require("http-proxy-agent"); var https_proxy_agent_1 = require("https-proxy-agent"); var socks_proxy_agent_1 = require("socks-proxy-agent"); var stream_1 = require("stream"); var packageJson = require('../../package.json'); var Core = /** @class */ (function () { function Core(baseRequestOptions) { this.baseRequestOptions = baseRequestOptions || {}; } ; /** * @param url * @returns this * @example Nyro.setURL('https://jsonplaceholder.typicode.com/posts'); * @description This function sets the URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setURL = function (url) { this.baseRequestOptions.url = url; return this; }; ; /** * @param baseURL * @returns this * @example Nyro.setBaseURL('https://jsonplaceholder.typicode.com'); * @description This function sets the base URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBaseURL = function (baseURL) { this.baseRequestOptions.baseURL = baseURL; return this; }; ; /** * @param path * @returns this * @example Nyro.setPath('/posts'); * @description This function sets the path for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setPath = function (path) { this.baseRequestOptions.path = path; return this; }; ; /** * @param bodySchema * @returns this * @example Nyro.setBodySchema({ title: String, body: String }); * @description This function sets the body schema for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBodySchema = function (bodySchema) { this.baseRequestOptions.bodySchema = bodySchema; return this; }; ; /** * @param auth * @returns this * @example Nyro.setAuth({ username: 'user', password: 'pass' }); * @description This function sets the authentication credentials for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setAuth = function (auth) { this.baseRequestOptions.auth = auth; return this; }; ; /** * @param port * @returns this * @example Nyro.setPort(443); * @description This function sets the port for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setProxy = function (proxy) { this.baseRequestOptions.proxy = proxy; return this; }; ; /** * @param port * @returns this * @example Nyro.setPort(443); * @description This function sets the port for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMethod = function (method) { this.baseRequestOptions.method = method; return this; }; ; /** * @param headers * @returns this * @example Nyro.setHeaders({ 'Content-Type': 'application/json' }); * @description This function sets the headers for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setHeaders = function (headers) { this.baseRequestOptions.headers = headers; return this; }; ; /** * @param params * @returns this * @example Nyro.setParams({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setParams = function (params) { this.baseRequestOptions.params = params; return this; }; ; /** * @param query * @returns this * @example Nyro.setQuery({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setQuery = function (query) { this.baseRequestOptions.query = query; return this; }; ; /** * @param body * @returns this * @example Nyro.setBody({ title: 'foo', body: 'bar', userId: 1 }); * @description This function sets the body for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBody = function (body) { this.baseRequestOptions.body = body; return this; }; ; /** * @param timeout * @returns this * @example Nyro.setTimeout(5000); * @description This function sets the timeout for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setTimeout = function (timeout) { this.baseRequestOptions.timeout = timeout; return this; }; ; /** * @param responseType * @returns this * @example Nyro.setResponseType('json'); * @description This function sets the response type for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetryOn = function (retryOn) { this.baseRequestOptions.retryOn = retryOn; return this; }; ; /** * @param retries * @returns this * @example Nyro.setRetries(3); * @description This function sets the number of retries for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetries = function (retries) { this.baseRequestOptions.retries = retries; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setValidateStatus = function (validateStatus) { this.baseRequestOptions.validateStatus = validateStatus; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxBodyLength = function (maxBodyLength) { this.baseRequestOptions.maxBodyLength = maxBodyLength; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxContentLength = function (maxContentLength) { this.baseRequestOptions.maxContentLength = maxContentLength; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxRate = function (maxRate) { this.baseRequestOptions.maxRate = maxRate; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setSignal = function (signal) { this.baseRequestOptions.signal = signal; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setOnDownloadProgress = function (onDownloadProgress) { this.baseRequestOptions.onDownloadProgress = onDownloadProgress; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setTimeoutErrorMessage = function (timeoutErrorMessage) { this.baseRequestOptions.timeoutErrorMessage = timeoutErrorMessage; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setResponseType = function (responseType) { this.baseRequestOptions.responseType = responseType; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setResponseEncoding = function (responseEncoding) { this.baseRequestOptions.responseEncoding = responseEncoding; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxRedirects = function (maxRedirects) { this.baseRequestOptions.maxRedirects = maxRedirects; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetryDelay = function (retryDelay) { this.baseRequestOptions.retryDelay = retryDelay; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setDecompress = function (decompress) { this.baseRequestOptions.decompress = decompress; return this; }; ; /*-------------------------------------------------------*/ /*----------------LINE-------------BREAK-----------------*/ /*-------------------------------------------------------*/ /** * Sends a GET request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.get('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a GET request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET|MDN web docs} */ Core.prototype.get = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'GET'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a POST request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.post('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a POST request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST|MDN web docs} */ Core.prototype.post = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'POST'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a PUT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.put('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PUT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT|MDN web docs} */ Core.prototype.put = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'PUT'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a DELETE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.delete('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a DELETE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE|MDN web docs} */ Core.prototype.delete = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'DELETE'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a PATCH request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.patch('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PATCH request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH|MDN web docs} */ Core.prototype.patch = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'PATCH'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a HEAD request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.head('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a HEAD request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD|MDN web docs} */ Core.prototype.head = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'HEAD'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends an OPTIONS request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.options('https://jsonplaceholder.typicode.com/posts'); * @description This function sends an OPTIONS request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS|MDN web docs} */ Core.prototype.options = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'OPTIONS'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a CONNECT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.connect('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a CONNECT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT|MDN web docs} */ Core.prototype.connect = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'CONNECT'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a TRACE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.trace('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a TRACE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE|MDN web docs} */ Core.prototype.trace = function (url, options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: 'TRACE', url: url }))]; }); }); }; ; /** * Extends the default request options with the provided options. * * @param extendOptions - The options to extend the default request options with. * @returns An object with the execute function to make the request and the options used for the request. * @example Nyro.extend({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function allows you to create a new request with the provided options, while keeping the default options for future requests. */ Core.prototype.extend = function (extendOptions) { return __awaiter(this, void 0, void 0, function () { var options; return __generator(this, function (_a) { options = __assign(__assign({}, this.baseRequestOptions), extendOptions); return [2 /*return*/, new Core(options)]; }); }); }; ; /** * Creates a new instance of the Nyro library with the provided options. * * @param options - The request options. * @returns A new instance of the Nyro library with the provided options. * @example Nyro.create({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function creates a new instance of the Nyro library with the provided options. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} */ Core.prototype.create = function (options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Core(options)]; }); }); }; /** * Core function for handling HTTP requests. * * @param options - The request options. * @param currentRedirects - The number of redirects that have occurred. * @returns A promise that resolves with the HTTP response. */ Core.prototype.request = function (options_1) { return __awaiter(this, arguments, void 0, function (options, currentRedirects, attempt, visitedUrls) { var combinedURL, fullUrl, params, query, key, isHttps, lib, http2Lib, _a, username, password, token, requestOptions, proxyAuth, proxyUrl, protocol, dataString, startTimestamp, clientLib; var _this = this; var _b, _c; if (currentRedirects === void 0) { currentRedirects = 0; } if (attempt === void 0) { attempt = 1; } if (visitedUrls === void 0) { visitedUrls = new Set(); } return __generator(this, function (_d) { if (!options) { options = __assign({}, this.baseRequestOptions); } else { options = __assign(__assign({}, this.baseRequestOptions), options); } ; combinedURL = (0, combineUrl_1.default)((options === null || options === void 0 ? void 0 : options.baseURL) || '', (options === null || options === void 0 ? void 0 : options.url) || "", (options === null || options === void 0 ? void 0 : options.path) || ''); try { fullUrl = new url_1.URL(combinedURL); } catch (error) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid URL: ".concat(combinedURL), name: 'Request', requestOptions: options, }))]; } visitedUrls.add(fullUrl.toString()); if ((_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.aborted) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 0, message: 'Request aborted', name: 'Request', requestOptions: options, }))]; } ; if (options === null || options === void 0 ? void 0 : options.port) { options.port = (options === null || options === void 0 ? void 0 : options.port) || (fullUrl.protocol === 'https:' ? 443 : 80); } ; if (options === null || options === void 0 ? void 0 : options.path) { fullUrl.pathname += options.path; } if (options === null || options === void 0 ? void 0 : options.isStream) { options.responseType = 'stream'; } if (options === null || options === void 0 ? void 0 : options.params) { params = new url_1.URLSearchParams(options.params); fullUrl.search = params.toString(); } if (['json', 'text', 'blob', 'stream', 'arrayBuffer', 'document'].indexOf((options === null || options === void 0 ? void 0 : options.responseType) || 'json') === -1) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid response type: ".concat(options === null || options === void 0 ? void 0 : options.responseType), name: 'Request', requestOptions: options, }))]; } ; if (options && options.method && ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE'].indexOf(options.method) === -1) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid request method: ".concat(options.method), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.timeout) && options.timeout < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid timeout: ".concat(options.timeout), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxRedirects) && options.maxRedirects < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid number of redirects: ".concat(options.maxRedirects), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxBodyLength) && options.maxBodyLength < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max body length: ".concat(options.maxBodyLength), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxContentLength) && options.maxContentLength < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max content length: ".concat(options.maxContentLength), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxRate) && options.maxRate < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max rate: ".concat(options.maxRate), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.retryDelay) && options.retryDelay < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid retry delay: ".concat(options.retryDelay), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.retries) && options.retries < 0) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid number of retries: ".concat(options.retries), name: 'Request', requestOptions: options }))]; } ; if (options === null || options === void 0 ? void 0 : options.query) { query = new url_1.URLSearchParams(); for (key in options.query) { if (Object.prototype.hasOwnProperty.call(options.query, key)) { query.append(key, String(options.query[key])); } } fullUrl.search += (fullUrl.search ? '&' : '') + query.toString(); } isHttps = fullUrl.protocol === 'https:'; lib = isHttps ? https : http; http2Lib = options.useHttp2 ? http2 : null; if (!options.headers) options.headers = {}; if (options === null || options === void 0 ? void 0 : options.headers) { if (!options.headers['User-Agent']) options.headers['User-Agent'] = (0, utils_1.getDefaultUserAgent)(); if (!options.headers['Accept']) options.headers['Accept'] = "*/*"; if (!options.headers['Content-Type']) options.headers['Content-Type'] = 'application/json'; if (!options.headers['Content-Length']) options.headers['Content-Length'] = '0'; } if (options && !(options === null || options === void 0 ? void 0 : options.responseType)) { options.responseType = 'json'; } if ((options === null || options === void 0 ? void 0 : options.auth) && (options === null || options === void 0 ? void 0 : options.headers)) { _a = options.auth, username = _a.username, password = _a.password; token = Buffer.from("".concat(username, ":").concat(password)).toString('base64'); options.headers['Authorization'] = "Basic ".concat(token); } requestOptions = { method: options.method, headers: options === null || options === void 0 ? void 0 : options.headers, }; if (options === null || options === void 0 ? void 0 : options.timeout) { requestOptions.timeout = options.timeout; } if (options === null || options === void 0 ? void 0 : options.signal) { requestOptions.signal = options.signal; } if (options === null || options === void 0 ? void 0 : options.proxy) { proxyAuth = options.proxy.auth ? "".concat(options.proxy.auth.username, ":").concat(options.proxy.auth.password) : ''; proxyUrl = "".concat(options.proxy.host, ":").concat(options.proxy.port); protocol = ((_c = options.proxy) === null || _c === void 0 ? void 0 : _c.protocol) ? options.proxy.protocol : 'http'; requestOptions.agent = protocol.includes('socks') ? new socks_proxy_agent_1.SocksProxyAgent("".concat(protocol, "://").concat(proxyAuth ? "".concat(proxyAuth, "@") : '').concat(proxyUrl)) : isHttps ? new https_proxy_agent_1.HttpsProxyAgent("".concat(protocol, "://").concat(proxyAuth ? "".concat(proxyAuth, "@") : '').concat(proxyUrl)) : new http_proxy_agent_1.HttpProxyAgent("".concat(protocol, "://").concat(proxyAuth ? "".concat(proxyAuth, "@") : '').concat(proxyUrl)); } dataString = (options === null || options === void 0 ? void 0 : options.body) ? JSON.stringify(options.body) : null; if (dataString) { if ((options === null || options === void 0 ? void 0 : options.maxBodyLength) && Buffer.byteLength(dataString) > options.maxBodyLength) { return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 413, message: "Request body size exceeds maxBodyLength of ".concat(options.maxBodyLength, " bytes"), name: 'Request', requestOptions: options }))]; } requestOptions.headers['Content-Length'] = Buffer.byteLength(dataString).toString(); } startTimestamp = Date.now(); clientLib = options.useHttp2 ? http2Lib : lib; return [2 /*return*/, new Promise(function (resolve, reject) { var req = lib.request(fullUrl, requestOptions, function (res) { var _a; var chunks = []; var responseData; var totalLength = 0; var responseSize = 0; var downloaded = 0; var lastTimestamp = startTimestamp; var contentLength = parseInt((_a = res.headers['content-length']) !== null && _a !== void 0 ? _a : '0', 10) || null; var connectionReused = (0, utils_1.getReusedSocket)(res); var serverIp = (0, utils_1.getServerIp)(res); if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream') { var stream = new stream_1.PassThrough(); res.pipe(stream); var response = { request: req, response: res, headers: res.headers, config: options, requestInfo: { method: options === null || options === void 0 ? void 0 : options.method, url: options === null || options === void 0 ? void 0 : options.url, fullUrl: fullUrl.href, headers: (options === null || options === void 0 ? void 0 : options.headers) || {}, body: options === null || options === void 0 ? void 0 : options.body, httpVersion: res.httpVersion, startTimestamp: startTimestamp, timeout: options === null || options === void 0 ? void 0 : options.timeout, contentLength: dataString ? Buffer.byteLength(dataString) : 0, }, body: stream, statusCode: res.statusCode, statusText: res.statusMessage || '', timestamp: { startTimestamp: startTimestamp, endTimestamp: Date.now(), }, responseTime: Date.now() - startTimestamp, responseSize: 0, serverIp: serverIp, connectionReused: connectionReused || false, }; resolve(response); } else { res.on('data', function (chunk) { totalLength += chunk.length; responseSize += chunk.length; downloaded += chunk.length; var currentTimestamp = Date.now(); var timeElapsed = (currentTimestamp - lastTimestamp) / 1000; lastTimestamp = currentTimestamp; var rate = chunk.length / timeElapsed; if (contentLength && (options === null || options === void 0 ? void 0 : options.onDownloadProgress)) { var progress = Math.min(1, downloaded / contentLength); options.onDownloadProgress({ percent: progress * 100, transferredBytes: downloaded, totalBytes: contentLength, }); } ; if ((options === null || options === void 0 ? void 0 : options.maxContentLength) && responseSize > options.maxContentLength) { req.destroy(); reject(new errorHandler_1.default({ statusCode: 413, message: "Response size exceeds maxContentLength of ".concat(options.maxContentLength, " bytes"), name: 'Request', requestOptions: options, })); return; } ; if ((options === null || options === void 0 ? void 0 : options.maxRate) && rate > options.maxRate) { res.pause(); setTimeout(function () { res.resume(); }, (chunk.length / options.maxRate) * 1000); } ; chunks.push(chunk); }); res.on('end', function () { return __awaiter(_this, void 0, void 0, function () { var endTime, responseTime, rawData, encoding, validateStatus, newUrl, newOptions, currentCookies, newCookies, redirectResponse, error_1, response; var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: endTime = Date.now(); responseTime = endTime - startTimestamp; rawData = Buffer.concat(chunks); if (!(options === null || options === void 0 ? void 0 : options.decompress)) { encoding = res.headers['content-encoding']; if (encoding === 'gzip') { rawData = zlib.gunzipSync(rawData); } else if (encoding === 'deflate') { rawData = zlib.inflateSync(rawData); } else if (encoding === 'br') { rawData = zlib.brotliDecompressSync(rawData); } } validateStatus = (options === null || options === void 0 ? void 0 : options.validateStatus) || (function (status) { return status >= 200 && status < 300; }); if (!(res.statusCode && [301, 302, 303, 307, 308].includes(res.statusCode))) return [3 /*break*/, 5]; if (currentRedirects >= ((options === null || options === void 0 ? void 0 : options.maxRedirects) || 5)) { reject(new errorHandler_1.default({ statusCode: 310, message: "Exceeded maximum number of redirects: ".concat((options === null || options === void 0 ? void 0 : options.maxRedirects) || 5), name: 'Request', requestOptions: options, })); return [2 /*return*/]; } if (!res.headers.location) { reject(new errorHandler_1.default({ statusCode: 310, message: "Redirect location header missing", name: 'Request', requestOptions: options, })); return [2 /*return*/];