You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.5 KiB

4 years ago
  1. var extractImportUrlAndMedia = require('./extract-import-url-and-media');
  2. var restoreImport = require('./restore-import');
  3. var rewriteUrl = require('./rewrite-url');
  4. var Token = require('../tokenizer/token');
  5. var isImport = require('../utils/is-import');
  6. var SOURCE_MAP_COMMENT_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/;
  7. function rebase(tokens, rebaseAll, validator, rebaseConfig) {
  8. return rebaseAll ?
  9. rebaseEverything(tokens, validator, rebaseConfig) :
  10. rebaseAtRules(tokens, validator, rebaseConfig);
  11. }
  12. function rebaseEverything(tokens, validator, rebaseConfig) {
  13. var token;
  14. var i, l;
  15. for (i = 0, l = tokens.length; i < l; i++) {
  16. token = tokens[i];
  17. switch (token[0]) {
  18. case Token.AT_RULE:
  19. rebaseAtRule(token, validator, rebaseConfig);
  20. break;
  21. case Token.AT_RULE_BLOCK:
  22. rebaseProperties(token[2], validator, rebaseConfig);
  23. break;
  24. case Token.COMMENT:
  25. rebaseSourceMapComment(token, rebaseConfig);
  26. break;
  27. case Token.NESTED_BLOCK:
  28. rebaseEverything(token[2], validator, rebaseConfig);
  29. break;
  30. case Token.RULE:
  31. rebaseProperties(token[2], validator, rebaseConfig);
  32. break;
  33. }
  34. }
  35. return tokens;
  36. }
  37. function rebaseAtRules(tokens, validator, rebaseConfig) {
  38. var token;
  39. var i, l;
  40. for (i = 0, l = tokens.length; i < l; i++) {
  41. token = tokens[i];
  42. switch (token[0]) {
  43. case Token.AT_RULE:
  44. rebaseAtRule(token, validator, rebaseConfig);
  45. break;
  46. }
  47. }
  48. return tokens;
  49. }
  50. function rebaseAtRule(token, validator, rebaseConfig) {
  51. if (!isImport(token[1])) {
  52. return;
  53. }
  54. var uriAndMediaQuery = extractImportUrlAndMedia(token[1]);
  55. var newUrl = rewriteUrl(uriAndMediaQuery[0], rebaseConfig);
  56. var mediaQuery = uriAndMediaQuery[1];
  57. token[1] = restoreImport(newUrl, mediaQuery);
  58. }
  59. function rebaseSourceMapComment(token, rebaseConfig) {
  60. var matches = SOURCE_MAP_COMMENT_PATTERN.exec(token[1]);
  61. if (matches && matches[1].indexOf('data:') === -1) {
  62. token[1] = token[1].replace(matches[1], rewriteUrl(matches[1], rebaseConfig, true));
  63. }
  64. }
  65. function rebaseProperties(properties, validator, rebaseConfig) {
  66. var property;
  67. var value;
  68. var i, l;
  69. var j, m;
  70. for (i = 0, l = properties.length; i < l; i++) {
  71. property = properties[i];
  72. for (j = 2 /* 0 is Token.PROPERTY, 1 is name */, m = property.length; j < m; j++) {
  73. value = property[j][1];
  74. if (validator.isUrl(value)) {
  75. property[j][1] = rewriteUrl(value, rebaseConfig);
  76. }
  77. }
  78. }
  79. }
  80. module.exports = rebase;