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.

33 lines
1.0 KiB

4 years ago
  1. var UNICODE = '\\\\[0-9a-f]{1,6}(\\r\\n|[ \\n\\r\\t\\f])?';
  2. var ESCAPE = '(' + UNICODE + '|\\\\[^\\n\\r\\f0-9a-fA-F])';
  3. var NONPRINTABLE = '\u0000\u0008\u000b\u000e-\u001f\u007f';
  4. var SAFE_URL = new RegExp('^(' + ESCAPE + '|[^\"\'\\(\\)\\\\\\s' + NONPRINTABLE + '])*$', 'i');
  5. module.exports = function(node) {
  6. var value = node.value;
  7. if (value.type !== 'String') {
  8. return;
  9. }
  10. var quote = value.value[0];
  11. var url = value.value.substr(1, value.value.length - 2);
  12. // convert `\\` to `/`
  13. url = url.replace(/\\\\/g, '/');
  14. // remove quotes when safe
  15. // https://www.w3.org/TR/css-syntax-3/#url-unquoted-diagram
  16. if (SAFE_URL.test(url)) {
  17. node.value = {
  18. type: 'Raw',
  19. loc: node.value.loc,
  20. value: url
  21. };
  22. } else {
  23. // use double quotes if string has no double quotes
  24. // otherwise use original quotes
  25. // TODO: make better quote type selection
  26. node.value.value = url.indexOf('"') === -1 ? '"' + url + '"' : quote + url + quote;
  27. }
  28. };