processor.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const PostHTML = require('posthtml');
  2. const parser = require('./parser');
  3. const renderer = require('./renderer');
  4. /**
  5. * @typedef {Object} PostHTMLTree
  6. * @see https://github.com/posthtml/posthtml/blob/master/docs/tree.md#json
  7. */
  8. class PostHTMLProcessingResult {
  9. constructor(tree) {
  10. this.tree = tree;
  11. }
  12. get html() {
  13. return this.toString();
  14. }
  15. toString() {
  16. return renderer(this.tree, this.tree.options);
  17. }
  18. render() {
  19. return this.toString();
  20. }
  21. }
  22. class Processor {
  23. /**
  24. * @param {Array<Function>} [plugins]
  25. */
  26. constructor(plugins) {
  27. const posthtml = this.posthtml = PostHTML(plugins);
  28. this.version = posthtml.version;
  29. this.name = posthtml.name;
  30. this.plugins = posthtml.plugins;
  31. }
  32. /**
  33. * @param {...Function} plugins
  34. * @return {Processor}
  35. */
  36. use(...plugins) {
  37. this.posthtml.use.apply(this, ...plugins);
  38. return this;
  39. }
  40. /**
  41. * @param {string|PostHTMLTree} ast
  42. * @param {Object} options {@see https://github.com/posthtml/posthtml-render#options}
  43. * @return {Promise<PostHTMLProcessingResult>}
  44. */
  45. process(ast, options = null) {
  46. const opts = Object.assign({ parser }, options);
  47. return this.posthtml.process(ast, opts).then(({ tree }) => new PostHTMLProcessingResult(tree));
  48. }
  49. }
  50. Processor.parser = parser;
  51. Processor.render = renderer;
  52. /**
  53. * @param {Array<Function>} [plugins]
  54. * @return {Processor}
  55. */
  56. module.exports = plugins => new Processor(plugins);
  57. module.exports.parser = parser;
  58. module.exports.renderer = renderer;
  59. module.exports.Processor = Processor;
  60. module.exports.Result = PostHTMLProcessingResult;