index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. module.exports = (function() {
  2. var __MODS__ = {};
  3. var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };
  4. var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };
  5. var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };
  6. var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };
  7. __DEFINE__(1662612701770, function(require, module, exports) {
  8. var url = require("url");
  9. var URL = url.URL;
  10. var http = require("http");
  11. var https = require("https");
  12. var Writable = require("stream").Writable;
  13. var assert = require("assert");
  14. var debug = require("./debug");
  15. // Create handlers that pass events from native requests
  16. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  17. var eventHandlers = Object.create(null);
  18. events.forEach(function (event) {
  19. eventHandlers[event] = function (arg1, arg2, arg3) {
  20. this._redirectable.emit(event, arg1, arg2, arg3);
  21. };
  22. });
  23. // Error types with codes
  24. var RedirectionError = createErrorType(
  25. "ERR_FR_REDIRECTION_FAILURE",
  26. "Redirected request failed"
  27. );
  28. var TooManyRedirectsError = createErrorType(
  29. "ERR_FR_TOO_MANY_REDIRECTS",
  30. "Maximum number of redirects exceeded"
  31. );
  32. var MaxBodyLengthExceededError = createErrorType(
  33. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  34. "Request body larger than maxBodyLength limit"
  35. );
  36. var WriteAfterEndError = createErrorType(
  37. "ERR_STREAM_WRITE_AFTER_END",
  38. "write after end"
  39. );
  40. // An HTTP(S) request that can be redirected
  41. function RedirectableRequest(options, responseCallback) {
  42. // Initialize the request
  43. Writable.call(this);
  44. this._sanitizeOptions(options);
  45. this._options = options;
  46. this._ended = false;
  47. this._ending = false;
  48. this._redirectCount = 0;
  49. this._redirects = [];
  50. this._requestBodyLength = 0;
  51. this._requestBodyBuffers = [];
  52. // Attach a callback if passed
  53. if (responseCallback) {
  54. this.on("response", responseCallback);
  55. }
  56. // React to responses of native requests
  57. var self = this;
  58. this._onNativeResponse = function (response) {
  59. self._processResponse(response);
  60. };
  61. // Perform the first request
  62. this._performRequest();
  63. }
  64. RedirectableRequest.prototype = Object.create(Writable.prototype);
  65. RedirectableRequest.prototype.abort = function () {
  66. abortRequest(this._currentRequest);
  67. this.emit("abort");
  68. };
  69. // Writes buffered data to the current native request
  70. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  71. // Writing is not allowed if end has been called
  72. if (this._ending) {
  73. throw new WriteAfterEndError();
  74. }
  75. // Validate input and shift parameters if necessary
  76. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  77. throw new TypeError("data should be a string, Buffer or Uint8Array");
  78. }
  79. if (typeof encoding === "function") {
  80. callback = encoding;
  81. encoding = null;
  82. }
  83. // Ignore empty buffers, since writing them doesn't invoke the callback
  84. // https://github.com/nodejs/node/issues/22066
  85. if (data.length === 0) {
  86. if (callback) {
  87. callback();
  88. }
  89. return;
  90. }
  91. // Only write when we don't exceed the maximum body length
  92. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  93. this._requestBodyLength += data.length;
  94. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  95. this._currentRequest.write(data, encoding, callback);
  96. }
  97. // Error when we exceed the maximum body length
  98. else {
  99. this.emit("error", new MaxBodyLengthExceededError());
  100. this.abort();
  101. }
  102. };
  103. // Ends the current native request
  104. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  105. // Shift parameters if necessary
  106. if (typeof data === "function") {
  107. callback = data;
  108. data = encoding = null;
  109. }
  110. else if (typeof encoding === "function") {
  111. callback = encoding;
  112. encoding = null;
  113. }
  114. // Write data if needed and end
  115. if (!data) {
  116. this._ended = this._ending = true;
  117. this._currentRequest.end(null, null, callback);
  118. }
  119. else {
  120. var self = this;
  121. var currentRequest = this._currentRequest;
  122. this.write(data, encoding, function () {
  123. self._ended = true;
  124. currentRequest.end(null, null, callback);
  125. });
  126. this._ending = true;
  127. }
  128. };
  129. // Sets a header value on the current native request
  130. RedirectableRequest.prototype.setHeader = function (name, value) {
  131. this._options.headers[name] = value;
  132. this._currentRequest.setHeader(name, value);
  133. };
  134. // Clears a header value on the current native request
  135. RedirectableRequest.prototype.removeHeader = function (name) {
  136. delete this._options.headers[name];
  137. this._currentRequest.removeHeader(name);
  138. };
  139. // Global timeout for all underlying requests
  140. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  141. var self = this;
  142. // Destroys the socket on timeout
  143. function destroyOnTimeout(socket) {
  144. socket.setTimeout(msecs);
  145. socket.removeListener("timeout", socket.destroy);
  146. socket.addListener("timeout", socket.destroy);
  147. }
  148. // Sets up a timer to trigger a timeout event
  149. function startTimer(socket) {
  150. if (self._timeout) {
  151. clearTimeout(self._timeout);
  152. }
  153. self._timeout = setTimeout(function () {
  154. self.emit("timeout");
  155. clearTimer();
  156. }, msecs);
  157. destroyOnTimeout(socket);
  158. }
  159. // Stops a timeout from triggering
  160. function clearTimer() {
  161. // Clear the timeout
  162. if (self._timeout) {
  163. clearTimeout(self._timeout);
  164. self._timeout = null;
  165. }
  166. // Clean up all attached listeners
  167. self.removeListener("abort", clearTimer);
  168. self.removeListener("error", clearTimer);
  169. self.removeListener("response", clearTimer);
  170. if (callback) {
  171. self.removeListener("timeout", callback);
  172. }
  173. if (!self.socket) {
  174. self._currentRequest.removeListener("socket", startTimer);
  175. }
  176. }
  177. // Attach callback if passed
  178. if (callback) {
  179. this.on("timeout", callback);
  180. }
  181. // Start the timer if or when the socket is opened
  182. if (this.socket) {
  183. startTimer(this.socket);
  184. }
  185. else {
  186. this._currentRequest.once("socket", startTimer);
  187. }
  188. // Clean up on events
  189. this.on("socket", destroyOnTimeout);
  190. this.on("abort", clearTimer);
  191. this.on("error", clearTimer);
  192. this.on("response", clearTimer);
  193. return this;
  194. };
  195. // Proxy all other public ClientRequest methods
  196. [
  197. "flushHeaders", "getHeader",
  198. "setNoDelay", "setSocketKeepAlive",
  199. ].forEach(function (method) {
  200. RedirectableRequest.prototype[method] = function (a, b) {
  201. return this._currentRequest[method](a, b);
  202. };
  203. });
  204. // Proxy all public ClientRequest properties
  205. ["aborted", "connection", "socket"].forEach(function (property) {
  206. Object.defineProperty(RedirectableRequest.prototype, property, {
  207. get: function () { return this._currentRequest[property]; },
  208. });
  209. });
  210. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  211. // Ensure headers are always present
  212. if (!options.headers) {
  213. options.headers = {};
  214. }
  215. // Since http.request treats host as an alias of hostname,
  216. // but the url module interprets host as hostname plus port,
  217. // eliminate the host property to avoid confusion.
  218. if (options.host) {
  219. // Use hostname if set, because it has precedence
  220. if (!options.hostname) {
  221. options.hostname = options.host;
  222. }
  223. delete options.host;
  224. }
  225. // Complete the URL object when necessary
  226. if (!options.pathname && options.path) {
  227. var searchPos = options.path.indexOf("?");
  228. if (searchPos < 0) {
  229. options.pathname = options.path;
  230. }
  231. else {
  232. options.pathname = options.path.substring(0, searchPos);
  233. options.search = options.path.substring(searchPos);
  234. }
  235. }
  236. };
  237. // Executes the next native request (initial or redirect)
  238. RedirectableRequest.prototype._performRequest = function () {
  239. // Load the native protocol
  240. var protocol = this._options.protocol;
  241. var nativeProtocol = this._options.nativeProtocols[protocol];
  242. if (!nativeProtocol) {
  243. this.emit("error", new TypeError("Unsupported protocol " + protocol));
  244. return;
  245. }
  246. // If specified, use the agent corresponding to the protocol
  247. // (HTTP and HTTPS use different types of agents)
  248. if (this._options.agents) {
  249. var scheme = protocol.slice(0, -1);
  250. this._options.agent = this._options.agents[scheme];
  251. }
  252. // Create the native request and set up its event handlers
  253. var request = this._currentRequest =
  254. nativeProtocol.request(this._options, this._onNativeResponse);
  255. request._redirectable = this;
  256. for (var event of events) {
  257. request.on(event, eventHandlers[event]);
  258. }
  259. // RFC7230§5.3.1: When making a request directly to an origin server, […]
  260. // a client MUST send only the absolute path […] as the request-target.
  261. this._currentUrl = /^\//.test(this._options.path) ?
  262. url.format(this._options) :
  263. // When making a request to a proxy, […]
  264. // a client MUST send the target URI in absolute-form […].
  265. this._currentUrl = this._options.path;
  266. // End a redirected request
  267. // (The first request must be ended explicitly with RedirectableRequest#end)
  268. if (this._isRedirect) {
  269. // Write the request entity and end
  270. var i = 0;
  271. var self = this;
  272. var buffers = this._requestBodyBuffers;
  273. (function writeNext(error) {
  274. // Only write if this request has not been redirected yet
  275. /* istanbul ignore else */
  276. if (request === self._currentRequest) {
  277. // Report any write errors
  278. /* istanbul ignore if */
  279. if (error) {
  280. self.emit("error", error);
  281. }
  282. // Write the next buffer if there are still left
  283. else if (i < buffers.length) {
  284. var buffer = buffers[i++];
  285. /* istanbul ignore else */
  286. if (!request.finished) {
  287. request.write(buffer.data, buffer.encoding, writeNext);
  288. }
  289. }
  290. // End the request if `end` has been called on us
  291. else if (self._ended) {
  292. request.end();
  293. }
  294. }
  295. }());
  296. }
  297. };
  298. // Processes a response from the current native request
  299. RedirectableRequest.prototype._processResponse = function (response) {
  300. // Store the redirected response
  301. var statusCode = response.statusCode;
  302. if (this._options.trackRedirects) {
  303. this._redirects.push({
  304. url: this._currentUrl,
  305. headers: response.headers,
  306. statusCode: statusCode,
  307. });
  308. }
  309. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  310. // that further action needs to be taken by the user agent in order to
  311. // fulfill the request. If a Location header field is provided,
  312. // the user agent MAY automatically redirect its request to the URI
  313. // referenced by the Location field value,
  314. // even if the specific status code is not understood.
  315. // If the response is not a redirect; return it as-is
  316. var location = response.headers.location;
  317. if (!location || this._options.followRedirects === false ||
  318. statusCode < 300 || statusCode >= 400) {
  319. response.responseUrl = this._currentUrl;
  320. response.redirects = this._redirects;
  321. this.emit("response", response);
  322. // Clean up
  323. this._requestBodyBuffers = [];
  324. return;
  325. }
  326. // The response is a redirect, so abort the current request
  327. abortRequest(this._currentRequest);
  328. // Discard the remainder of the response to avoid waiting for data
  329. response.destroy();
  330. // RFC7231§6.4: A client SHOULD detect and intervene
  331. // in cyclical redirections (i.e., "infinite" redirection loops).
  332. if (++this._redirectCount > this._options.maxRedirects) {
  333. this.emit("error", new TooManyRedirectsError());
  334. return;
  335. }
  336. // Store the request headers if applicable
  337. var requestHeaders;
  338. var beforeRedirect = this._options.beforeRedirect;
  339. if (beforeRedirect) {
  340. requestHeaders = Object.assign({
  341. // The Host header was set by nativeProtocol.request
  342. Host: response.req.getHeader("host"),
  343. }, this._options.headers);
  344. }
  345. // RFC7231§6.4: Automatic redirection needs to done with
  346. // care for methods not known to be safe, […]
  347. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  348. // the request method from POST to GET for the subsequent request.
  349. var method = this._options.method;
  350. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  351. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  352. // the server is redirecting the user agent to a different resource […]
  353. // A user agent can perform a retrieval request targeting that URI
  354. // (a GET or HEAD request if using HTTP) […]
  355. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  356. this._options.method = "GET";
  357. // Drop a possible entity and headers related to it
  358. this._requestBodyBuffers = [];
  359. removeMatchingHeaders(/^content-/i, this._options.headers);
  360. }
  361. // Drop the Host header, as the redirect might lead to a different host
  362. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  363. // If the redirect is relative, carry over the host of the last request
  364. var currentUrlParts = url.parse(this._currentUrl);
  365. var currentHost = currentHostHeader || currentUrlParts.host;
  366. var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
  367. url.format(Object.assign(currentUrlParts, { host: currentHost }));
  368. // Determine the URL of the redirection
  369. var redirectUrl;
  370. try {
  371. redirectUrl = url.resolve(currentUrl, location);
  372. }
  373. catch (cause) {
  374. this.emit("error", new RedirectionError(cause));
  375. return;
  376. }
  377. // Create the redirected request
  378. debug("redirecting to", redirectUrl);
  379. this._isRedirect = true;
  380. var redirectUrlParts = url.parse(redirectUrl);
  381. Object.assign(this._options, redirectUrlParts);
  382. // Drop confidential headers when redirecting to a less secure protocol
  383. // or to a different domain that is not a superdomain
  384. if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
  385. redirectUrlParts.protocol !== "https:" ||
  386. redirectUrlParts.host !== currentHost &&
  387. !isSubdomain(redirectUrlParts.host, currentHost)) {
  388. removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
  389. }
  390. // Evaluate the beforeRedirect callback
  391. if (typeof beforeRedirect === "function") {
  392. var responseDetails = {
  393. headers: response.headers,
  394. statusCode: statusCode,
  395. };
  396. var requestDetails = {
  397. url: currentUrl,
  398. method: method,
  399. headers: requestHeaders,
  400. };
  401. try {
  402. beforeRedirect(this._options, responseDetails, requestDetails);
  403. }
  404. catch (err) {
  405. this.emit("error", err);
  406. return;
  407. }
  408. this._sanitizeOptions(this._options);
  409. }
  410. // Perform the redirected request
  411. try {
  412. this._performRequest();
  413. }
  414. catch (cause) {
  415. this.emit("error", new RedirectionError(cause));
  416. }
  417. };
  418. // Wraps the key/value object of protocols with redirect functionality
  419. function wrap(protocols) {
  420. // Default settings
  421. var exports = {
  422. maxRedirects: 21,
  423. maxBodyLength: 10 * 1024 * 1024,
  424. };
  425. // Wrap each protocol
  426. var nativeProtocols = {};
  427. Object.keys(protocols).forEach(function (scheme) {
  428. var protocol = scheme + ":";
  429. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  430. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  431. // Executes a request, following redirects
  432. function request(input, options, callback) {
  433. // Parse parameters
  434. if (typeof input === "string") {
  435. var urlStr = input;
  436. try {
  437. input = urlToOptions(new URL(urlStr));
  438. }
  439. catch (err) {
  440. /* istanbul ignore next */
  441. input = url.parse(urlStr);
  442. }
  443. }
  444. else if (URL && (input instanceof URL)) {
  445. input = urlToOptions(input);
  446. }
  447. else {
  448. callback = options;
  449. options = input;
  450. input = { protocol: protocol };
  451. }
  452. if (typeof options === "function") {
  453. callback = options;
  454. options = null;
  455. }
  456. // Set defaults
  457. options = Object.assign({
  458. maxRedirects: exports.maxRedirects,
  459. maxBodyLength: exports.maxBodyLength,
  460. }, input, options);
  461. options.nativeProtocols = nativeProtocols;
  462. assert.equal(options.protocol, protocol, "protocol mismatch");
  463. debug("options", options);
  464. return new RedirectableRequest(options, callback);
  465. }
  466. // Executes a GET request, following redirects
  467. function get(input, options, callback) {
  468. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  469. wrappedRequest.end();
  470. return wrappedRequest;
  471. }
  472. // Expose the properties on the wrapped protocol
  473. Object.defineProperties(wrappedProtocol, {
  474. request: { value: request, configurable: true, enumerable: true, writable: true },
  475. get: { value: get, configurable: true, enumerable: true, writable: true },
  476. });
  477. });
  478. return exports;
  479. }
  480. /* istanbul ignore next */
  481. function noop() { /* empty */ }
  482. // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
  483. function urlToOptions(urlObject) {
  484. var options = {
  485. protocol: urlObject.protocol,
  486. hostname: urlObject.hostname.startsWith("[") ?
  487. /* istanbul ignore next */
  488. urlObject.hostname.slice(1, -1) :
  489. urlObject.hostname,
  490. hash: urlObject.hash,
  491. search: urlObject.search,
  492. pathname: urlObject.pathname,
  493. path: urlObject.pathname + urlObject.search,
  494. href: urlObject.href,
  495. };
  496. if (urlObject.port !== "") {
  497. options.port = Number(urlObject.port);
  498. }
  499. return options;
  500. }
  501. function removeMatchingHeaders(regex, headers) {
  502. var lastValue;
  503. for (var header in headers) {
  504. if (regex.test(header)) {
  505. lastValue = headers[header];
  506. delete headers[header];
  507. }
  508. }
  509. return (lastValue === null || typeof lastValue === "undefined") ?
  510. undefined : String(lastValue).trim();
  511. }
  512. function createErrorType(code, defaultMessage) {
  513. function CustomError(cause) {
  514. Error.captureStackTrace(this, this.constructor);
  515. if (!cause) {
  516. this.message = defaultMessage;
  517. }
  518. else {
  519. this.message = defaultMessage + ": " + cause.message;
  520. this.cause = cause;
  521. }
  522. }
  523. CustomError.prototype = new Error();
  524. CustomError.prototype.constructor = CustomError;
  525. CustomError.prototype.name = "Error [" + code + "]";
  526. CustomError.prototype.code = code;
  527. return CustomError;
  528. }
  529. function abortRequest(request) {
  530. for (var event of events) {
  531. request.removeListener(event, eventHandlers[event]);
  532. }
  533. request.on("error", noop);
  534. request.abort();
  535. }
  536. function isSubdomain(subdomain, domain) {
  537. const dot = subdomain.length - domain.length - 1;
  538. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  539. }
  540. // Exports
  541. module.exports = wrap({ http: http, https: https });
  542. module.exports.wrap = wrap;
  543. }, function(modId) {var map = {"http":1662612701771,"https":1662612701772,"./debug":1662612701773}; return __REQUIRE__(map[modId], modId); })
  544. __DEFINE__(1662612701771, function(require, module, exports) {
  545. module.exports = require("./").http;
  546. }, function(modId) { var map = {"./":1662612701770}; return __REQUIRE__(map[modId], modId); })
  547. __DEFINE__(1662612701772, function(require, module, exports) {
  548. module.exports = require("./").https;
  549. }, function(modId) { var map = {"./":1662612701770}; return __REQUIRE__(map[modId], modId); })
  550. __DEFINE__(1662612701773, function(require, module, exports) {
  551. var debug;
  552. module.exports = function () {
  553. if (!debug) {
  554. try {
  555. /* eslint global-require: off */
  556. debug = require("debug")("follow-redirects");
  557. }
  558. catch (error) { /* */ }
  559. if (typeof debug !== "function") {
  560. debug = function () { /* */ };
  561. }
  562. }
  563. debug.apply(null, arguments);
  564. };
  565. }, function(modId) { var map = {"debug":1662612701773}; return __REQUIRE__(map[modId], modId); })
  566. return __REQUIRE__(1662612701770);
  567. })()
  568. //miniprogram-npm-outsideDeps=["url","stream","assert"]
  569. //# sourceMappingURL=index.js.map