UNPKG

rekwest

Version:

The robust request library that humanity deserves 🌐

108 lines (107 loc) 3.26 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mixin = void 0; var _nodeBuffer = require("node:buffer"); var _nodeHttp = _interopRequireDefault(require("node:http2")); var _utils = require("./utils"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const { HTTP2_HEADER_CONTENT_ENCODING, HTTP2_HEADER_CONTENT_TYPE } = _nodeHttp.default.constants; const mixin = (res, { digest = false, parse = false } = {}) => { if (!digest) { Object.defineProperties(res, { arrayBuffer: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); parse &&= false; const { buffer, byteLength, byteOffset } = await this.body(); return buffer.slice(byteOffset, byteOffset + byteLength); } }, blob: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); const val = await this.arrayBuffer(); return new _nodeBuffer.Blob([val]); } }, bytes: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); return new Uint8Array(await this.arrayBuffer()); } }, json: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); const val = await this.text(); return JSON.parse(val); } }, text: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); const blob = await this.blob(); return blob.text(); } } }); } return Object.defineProperties(res, { body: { enumerable: true, value: async function () { (0, _utils.brandCheck)(this, res?.constructor); if (this.bodyUsed) { throw new TypeError('Response stream already read'); } let body = []; for await (const chunk of (0, _utils.decompress)(this, this.headers[HTTP2_HEADER_CONTENT_ENCODING])) { body.push(chunk); } body = Buffer.concat(body); if (!body.length && parse) { return null; } if (body.length && parse) { const contentType = this.headers[HTTP2_HEADER_CONTENT_TYPE] ?? ''; const charset = contentType.split(';').find(it => /charset=/i.test(it))?.toLowerCase().replace('charset=', '').replace('iso-8859-1', 'latin1').trim() || 'utf-8'; if (/\bjson\b/i.test(contentType)) { body = JSON.parse(body.toString(charset)); } else if (/\b(?:text|xml)\b/i.test(contentType)) { if (/\b(?:latin1|ucs-2|utf-(?:8|16le))\b/i.test(charset)) { body = body.toString(charset); } else { body = new TextDecoder(charset).decode(body); } } } return body; }, writable: true }, bodyUsed: { enumerable: true, get() { return this.readableEnded; } } }); }; exports.mixin = mixin;