parse5-adapter.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.parseWithParse5 = parseWithParse5;
  4. exports.renderWithParse5 = renderWithParse5;
  5. const domhandler_1 = require("domhandler");
  6. const parse5_1 = require("parse5");
  7. const parse5_htmlparser2_tree_adapter_1 = require("parse5-htmlparser2-tree-adapter");
  8. /**
  9. * Parse the content with `parse5` in the context of the given `ParentNode`.
  10. *
  11. * @param content - The content to parse.
  12. * @param options - A set of options to use to parse.
  13. * @param isDocument - Whether to parse the content as a full HTML document.
  14. * @param context - The context in which to parse the content.
  15. * @returns The parsed content.
  16. */
  17. function parseWithParse5(content, options, isDocument, context) {
  18. var _a;
  19. (_a = options.treeAdapter) !== null && _a !== void 0 ? _a : (options.treeAdapter = parse5_htmlparser2_tree_adapter_1.adapter);
  20. if (options.scriptingEnabled !== false) {
  21. options.scriptingEnabled = true;
  22. }
  23. return isDocument
  24. ? (0, parse5_1.parse)(content, options)
  25. : (0, parse5_1.parseFragment)(context, content, options);
  26. }
  27. const renderOpts = { treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter };
  28. /**
  29. * Renders the given DOM tree with `parse5` and returns the result as a string.
  30. *
  31. * @param dom - The DOM tree to render.
  32. * @returns The rendered document.
  33. */
  34. function renderWithParse5(dom) {
  35. /*
  36. * `dom-serializer` passes over the special "root" node and renders the
  37. * node's children in its place. To mimic this behavior with `parse5`, an
  38. * equivalent operation must be applied to the input array.
  39. */
  40. const nodes = 'length' in dom ? dom : [dom];
  41. for (let index = 0; index < nodes.length; index += 1) {
  42. const node = nodes[index];
  43. if ((0, domhandler_1.isDocument)(node)) {
  44. Array.prototype.splice.call(nodes, index, 1, ...node.children);
  45. }
  46. }
  47. let result = '';
  48. for (let index = 0; index < nodes.length; index += 1) {
  49. const node = nodes[index];
  50. result += (0, parse5_1.serializeOuter)(node, renderOpts);
  51. }
  52. return result;
  53. }
  54. //# sourceMappingURL=parse5-adapter.js.map