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()); }); }; import { request as httpReq } from 'http'; import { request as httpsReq } from 'https'; export class Follow { constructor(follow) { this.follow = follow; } } export class Stop { constructor(stop) { this.stop = stop; } } export function locationHeaderPlugin(url, response, previous) { return __awaiter(this, void 0, void 0, function* () { const { protocol, host } = url; if (response.headers.location) { const followUrl = new URL(response.headers.location.startsWith('http') ? response.headers.location : `${protocol}//${host}${response.headers.location}`); return new Follow(followUrl); } return previous; }); } const defaultOptions = { method: 'GET', maxRedirects: 3, headers: {}, timeout: 120000, plugins: [locationHeaderPlugin] }; function makeRequest(url, options) { return new Promise((resolve, reject) => { const request = url.protocol === 'https:' ? httpsReq : httpReq; const req = request(url, options, (response) => { resolve(response); }); req.on('error', reject); req.setTimeout(options.timeout, () => req.destroy()); req.end(); }); } export const tall = (url, options) => __awaiter(void 0, void 0, void 0, function* () { const opt = Object.assign({}, defaultOptions, options); if (opt.maxRedirects <= 0) { return url.toString(); } const parsedUrl = new URL(url); let prev = new Stop(parsedUrl); const response = yield makeRequest(parsedUrl, opt); for (const plugin of opt.plugins) { prev = yield plugin(parsedUrl, response, prev); } const maxRedirects = opt.maxRedirects - 1; if (prev instanceof Follow) { return yield tall(prev.follow.toString(), Object.assign(Object.assign({}, options), { maxRedirects })); } return prev.stop.toString(); }); //# sourceMappingURL=index.js.map