No Description

comments.js 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var EscapeStore = require('./escape-store');
  2. var QuoteScanner = require('./quote-scanner');
  3. module.exports = function Comments(context, keepSpecialComments, keepBreaks, lineBreak) {
  4. var comments = new EscapeStore('COMMENT');
  5. return {
  6. // Strip special comments (/*! ... */) by replacing them by a special marker
  7. // for further restoring. Plain comments are removed. It's done by scanning data using
  8. // String#indexOf scanning instead of regexps to speed up the process.
  9. escape: function(data) {
  10. var tempData = [];
  11. var nextStart = 0;
  12. var nextEnd = 0;
  13. var cursor = 0;
  14. var isQuotedAt = (function () {
  15. var quoteMap = [];
  16. new QuoteScanner(data).each(function (quotedString, _, startsAt) {
  17. quoteMap.push([startsAt, startsAt + quotedString.length]);
  18. });
  19. return function (position) {
  20. for (var i = 0, l = quoteMap.length; i < l; i++) {
  21. if (quoteMap[i][0] < position && quoteMap[i][1] > position)
  22. return true;
  23. }
  24. return false;
  25. };
  26. })();
  27. for (; nextEnd < data.length;) {
  28. nextStart = data.indexOf('/*', cursor);
  29. if (nextStart == -1)
  30. break;
  31. if (isQuotedAt(nextStart)) {
  32. tempData.push(data.substring(cursor, nextStart + 2));
  33. cursor = nextStart + 2;
  34. continue;
  35. }
  36. nextEnd = data.indexOf('*/', nextStart + 2);
  37. if (nextEnd == -1) {
  38. context.warnings.push('Broken comment: \'' + data.substring(nextStart) + '\'.');
  39. nextEnd = data.length - 2;
  40. }
  41. tempData.push(data.substring(cursor, nextStart));
  42. if (data[nextStart + 2] == '!') {
  43. // in case of special comments, replace them with a placeholder
  44. var comment = data.substring(nextStart, nextEnd + 2);
  45. var placeholder = comments.store(comment);
  46. tempData.push(placeholder);
  47. }
  48. cursor = nextEnd + 2;
  49. }
  50. return tempData.length > 0 ?
  51. tempData.join('') + data.substring(cursor, data.length) :
  52. data;
  53. },
  54. restore: function(data) {
  55. var restored = 0;
  56. var breakSuffix = keepBreaks ? lineBreak : '';
  57. return data.replace(new RegExp(comments.placeholderPattern + '(' + lineBreak + '| )?', 'g'), function(match, placeholder) {
  58. restored++;
  59. switch (keepSpecialComments) {
  60. case '*':
  61. return comments.restore(placeholder) + breakSuffix;
  62. case 1:
  63. case '1':
  64. return restored == 1 ?
  65. comments.restore(placeholder) + breakSuffix :
  66. '';
  67. case 0:
  68. case '0':
  69. return '';
  70. }
  71. });
  72. }
  73. };
  74. };