url-file-manager.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var tslib_1 = require("tslib");
  4. /* eslint-disable no-unused-vars */
  5. /**
  6. * @todo - remove top eslint rule when FileManagers have JSDoc type
  7. * and are TS-type-checked
  8. */
  9. var isUrlRe = /^(?:https?:)?\/\//i;
  10. var url_1 = tslib_1.__importDefault(require("url"));
  11. var request;
  12. var abstract_file_manager_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-file-manager.js"));
  13. var logger_1 = tslib_1.__importDefault(require("../less/logger"));
  14. var UrlFileManager = function () { };
  15. UrlFileManager.prototype = Object.assign(new abstract_file_manager_js_1.default(), {
  16. supports: function (filename, currentDirectory, options, environment) {
  17. return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
  18. },
  19. loadFile: function (filename, currentDirectory, options, environment) {
  20. return new Promise(function (fulfill, reject) {
  21. if (request === undefined) {
  22. try {
  23. request = require('needle');
  24. }
  25. catch (e) {
  26. request = null;
  27. }
  28. }
  29. if (!request) {
  30. reject({ type: 'File', message: 'optional dependency \'needle\' required to import over http(s)\n' });
  31. return;
  32. }
  33. var urlStr = isUrlRe.test(filename) ? filename : url_1.default.resolve(currentDirectory, filename);
  34. /** native-request currently has a bug */
  35. var hackUrlStr = urlStr.indexOf('?') === -1 ? urlStr + '?' : urlStr;
  36. request.get(hackUrlStr, { follow_max: 5 }, function (err, resp, body) {
  37. if (err || resp && resp.statusCode >= 400) {
  38. var message = resp && resp.statusCode === 404
  39. ? "resource '" + urlStr + "' was not found\n"
  40. : "resource '" + urlStr + "' gave this Error:\n " + (err || resp.statusMessage || resp.statusCode) + "\n";
  41. reject({ type: 'File', message: message });
  42. return;
  43. }
  44. if (resp.statusCode >= 300) {
  45. reject({ type: 'File', message: "resource '" + urlStr + "' caused too many redirects" });
  46. return;
  47. }
  48. body = body.toString('utf8');
  49. if (!body) {
  50. logger_1.default.warn("Warning: Empty body (HTTP " + resp.statusCode + ") returned by \"" + urlStr + "\"");
  51. }
  52. fulfill({ contents: body || '', filename: urlStr });
  53. });
  54. });
  55. }
  56. });
  57. exports.default = UrlFileManager;
  58. //# sourceMappingURL=url-file-manager.js.map