diff --git a/lib/index.js b/lib/index.js index ff6b55b..a945fd4 100644 --- a/lib/index.js +++ b/lib/index.js @@ -48,12 +48,13 @@ * User configuration. */ -import {Parser, Token, TokenizerMode, html} from 'parse5' -import {pointStart, pointEnd} from 'unist-util-position' -import {visit} from 'unist-util-visit' +import extend from 'extend' import {fromParse5} from 'hast-util-from-parse5' import {toParse5} from 'hast-util-to-parse5' import {htmlVoidElements} from 'html-void-elements' +import {Parser, Token, TokenizerMode, html} from 'parse5' +import {pointStart, pointEnd} from 'unist-util-position' +import {visit} from 'unist-util-visit' import {zwitch} from 'zwitch' /** @type {ParserOptions} */ @@ -282,23 +283,18 @@ function stitch(node, state) { state.stitches = true /** @type {Node} */ - let clone + const clone = cloneWithoutChildren(node) // Recurse, because to somewhat handle `[]` (where `[]` denotes the // passed through node). - if ('children' in node) { - // To do: deep clone. - clone = { - ...node, - children: raw( - {type: 'root', children: node.children}, - state.file, - state.options - // @ts-expect-error Assume a given parent yields a parent. - ).children - } - } else { - clone = {...node} + if ('children' in node && 'children' in clone) { + const fakeRoot = raw( + {type: 'root', children: node.children}, + state.file, + state.options + ) + // @ts-expect-error Assume a given parent yields a parent. + clone.children = fakeRoot.children } // Hack: `value` is supposed to be a string, but as none of the tools @@ -641,3 +637,17 @@ function createParse5Location(node) { function isOptions(value) { return Boolean(value && !('message' in value && 'messages' in value)) } + +/** + * @template {Node} NodeType + * Node type. + * @param {NodeType} node + * Node to clone. + * @returns {NodeType} + * Cloned node, without children. + */ +function cloneWithoutChildren(node) { + return 'children' in node + ? extend(true, {}, {...node, children: []}) + : extend(true, {}, node) +} diff --git a/package.json b/package.json index e3fbb3b..4bd7712 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ ], "dependencies": { "@types/hast": "^2.0.0", + "extend": "^3.0.0", "hast-util-from-parse5": "^7.0.0", "hast-util-to-parse5": "^7.0.0", "html-void-elements": "^2.0.0",