index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Module dependencies.
  3. */
  4. var css = require('css');
  5. var convertSourceMap = require('convert-source-map');
  6. var parse = css.parse;
  7. var stringify = css.stringify;
  8. /**
  9. * Expose `rework`.
  10. */
  11. exports = module.exports = rework;
  12. /**
  13. * Initialize a new stylesheet `Rework` with `str`.
  14. *
  15. * @param {String} str
  16. * @param {Object} options
  17. * @return {Rework}
  18. * @api public
  19. */
  20. function rework(str, options) {
  21. return new Rework(parse(str, options));
  22. }
  23. /**
  24. * Initialize a new stylesheet `Rework` with `obj`.
  25. *
  26. * @param {Object} obj
  27. * @api private
  28. */
  29. function Rework(obj) {
  30. this.obj = obj;
  31. }
  32. /**
  33. * Use the given plugin `fn(style, rework)`.
  34. *
  35. * @param {Function} fn
  36. * @return {Rework}
  37. * @api public
  38. */
  39. Rework.prototype.use = function(fn){
  40. fn(this.obj.stylesheet, this);
  41. return this;
  42. };
  43. /**
  44. * Stringify the stylesheet.
  45. *
  46. * @param {Object} options
  47. * @return {String}
  48. * @api public
  49. */
  50. Rework.prototype.toString = function(options){
  51. options = options || {};
  52. var result = stringify(this.obj, options);
  53. if (options.sourcemap && !options.sourcemapAsObject) {
  54. result = result.code + '\n' + sourcemapToComment(result.map);
  55. }
  56. return result;
  57. };
  58. /**
  59. * Convert sourcemap to base64-encoded comment
  60. *
  61. * @param {Object} map
  62. * @return {String}
  63. * @api private
  64. */
  65. function sourcemapToComment(map) {
  66. var content = convertSourceMap.fromObject(map).toBase64();
  67. return '/*# sourceMappingURL=data:application/json;base64,' + content + ' */';
  68. }