parse5-adapter.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.render = exports.parse = void 0;
  4. var tslib_1 = require("tslib");
  5. var domhandler_1 = require("domhandler");
  6. var parse5_1 = require("parse5");
  7. var parse5_htmlparser2_tree_adapter_1 = tslib_1.__importDefault(require("parse5-htmlparser2-tree-adapter"));
  8. function parse(content, options, isDocument) {
  9. var opts = {
  10. scriptingEnabled: typeof options.scriptingEnabled === 'boolean'
  11. ? options.scriptingEnabled
  12. : true,
  13. treeAdapter: parse5_htmlparser2_tree_adapter_1.default,
  14. sourceCodeLocationInfo: options.sourceCodeLocationInfo,
  15. };
  16. var context = options.context;
  17. // @ts-expect-error The tree adapter unfortunately doesn't return the exact types.
  18. return isDocument
  19. ? parse5_1.parse(content, opts)
  20. : // @ts-expect-error Same issue again.
  21. parse5_1.parseFragment(context, content, opts);
  22. }
  23. exports.parse = parse;
  24. function render(dom) {
  25. var _a;
  26. /*
  27. * `dom-serializer` passes over the special "root" node and renders the
  28. * node's children in its place. To mimic this behavior with `parse5`, an
  29. * equivalent operation must be applied to the input array.
  30. */
  31. var nodes = 'length' in dom ? dom : [dom];
  32. for (var index = 0; index < nodes.length; index += 1) {
  33. var node = nodes[index];
  34. if (domhandler_1.isDocument(node)) {
  35. (_a = Array.prototype.splice).call.apply(_a, tslib_1.__spreadArray([nodes, index, 1], node.children));
  36. }
  37. }
  38. // @ts-expect-error Types don't align here either.
  39. return parse5_1.serialize({ children: nodes }, { treeAdapter: parse5_htmlparser2_tree_adapter_1.default });
  40. }
  41. exports.render = render;