Brak opisu

url-rewriter.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var path = require('path');
  2. var url = require('url');
  3. module.exports = {
  4. process: function(data, options) {
  5. var tempData = [];
  6. var nextStart = 0;
  7. var nextEnd = 0;
  8. var cursor = 0;
  9. for (; nextEnd < data.length;) {
  10. nextStart = data.indexOf('url(', nextEnd);
  11. if (nextStart == -1)
  12. break;
  13. nextEnd = data.indexOf(')', nextStart + 4);
  14. if (nextEnd == -1)
  15. break;
  16. tempData.push(data.substring(cursor, nextStart));
  17. var url = data.substring(nextStart + 4, nextEnd);
  18. if (!/\/\*|\*\//.test(url))
  19. url = url.replace(/['"]/g, '');
  20. tempData.push('url(' + this._rebased(url, options) + ')');
  21. cursor = nextEnd + 1;
  22. }
  23. return tempData.length > 0 ?
  24. tempData.join('') + data.substring(cursor, data.length) :
  25. data;
  26. },
  27. _rebased: function(resource, options) {
  28. var specialUrl = resource[0] == '/' ||
  29. resource[0] == '#' ||
  30. resource.substring(resource.length - 4) == '.css' ||
  31. resource.indexOf('data:') === 0 ||
  32. /^https?:\/\//.exec(resource) !== null ||
  33. /__\w+__/.exec(resource) !== null;
  34. var rebased;
  35. if (specialUrl)
  36. return resource;
  37. if (/https?:\/\//.test(options.toBase))
  38. return url.resolve(options.toBase, resource);
  39. if (options.absolute) {
  40. rebased = path
  41. .resolve(path.join(options.fromBase, resource))
  42. .replace(options.toBase, '');
  43. } else {
  44. rebased = path.relative(options.toBase, path.join(options.fromBase, resource));
  45. }
  46. return process.platform == 'win32' ?
  47. rebased.replace(/\\/g, '/') :
  48. rebased;
  49. }
  50. };