rekwest
Version:
The robust request library that humanity deserves 🌐
88 lines (87 loc) • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transfer = void 0;
var _nodeHttp = _interopRequireDefault(require("node:http"));
var _nodeHttp2 = _interopRequireDefault(require("node:http2"));
var _nodeHttps = _interopRequireDefault(require("node:https"));
var _ackn = require("./ackn.cjs");
var _errors = require("./errors.cjs");
var _postflight = require("./postflight.cjs");
var _preflight = require("./preflight.cjs");
var _retries = require("./retries.cjs");
var _transform = require("./transform.cjs");
var _utils = require("./utils.cjs");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const transfer = async options => {
const {
digest,
redirected,
thenable,
url
} = options;
if (options.follow === 0) {
throw new _errors.RequestError(`Maximum redirect reached at: ${url.href}`);
}
if (url.protocol === 'https:') {
options = !options.h2 ? await (0, _ackn.ackn)(options) : {
...options,
createConnection: null,
protocol: url.protocol
};
} else if (Reflect.has(options, 'alpnProtocol')) {
for (const it of ['alpnProtocol', 'createConnection', 'h2', 'protocol']) {
Reflect.deleteProperty(options, it);
}
}
try {
options = await (0, _transform.transform)((0, _preflight.preflight)(options));
} catch (ex) {
options.createConnection?.().destroy();
throw ex;
}
const promise = new Promise((resolve, reject) => {
let client, req;
if (options.h2) {
client = _nodeHttp2.default.connect(url.origin, options);
req = client.request(options.headers, options);
} else {
const {
request
} = url.protocol === 'http:' ? _nodeHttp.default : _nodeHttps.default;
req = request(url, options);
}
(0, _utils.snoop)(client, req, options);
req.once('aborted', reject);
req.once('error', reject);
req.once('frameError', reject);
req.once('goaway', reject);
req.once('response', res => (0, _postflight.postflight)(req, res, options, {
reject,
resolve
}));
(0, _utils.dispatch)(req, options);
});
try {
const res = await promise;
if (digest && !redirected) {
res.body = await res.body();
}
return res;
} catch (ex) {
const result = (0, _retries.retries)(ex, options);
if (result) {
return result;
}
if (digest && !redirected && ex.body) {
ex.body = await ex.body();
}
if (!thenable) {
throw ex;
} else {
return ex;
}
}
};
exports.transfer = transfer;