Skip to content

Commit 9910e6b

Browse files
committed
Fix to deep clone unknown nodes
1 parent 386d2f3 commit 9910e6b

File tree

2 files changed

+28
-17
lines changed

2 files changed

+28
-17
lines changed

lib/index.js

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,13 @@
4848
* User configuration.
4949
*/
5050

51-
import {Parser, Token, TokenizerMode, html} from 'parse5'
52-
import {pointStart, pointEnd} from 'unist-util-position'
53-
import {visit} from 'unist-util-visit'
51+
import extend from 'extend'
5452
import {fromParse5} from 'hast-util-from-parse5'
5553
import {toParse5} from 'hast-util-to-parse5'
5654
import {htmlVoidElements} from 'html-void-elements'
55+
import {Parser, Token, TokenizerMode, html} from 'parse5'
56+
import {pointStart, pointEnd} from 'unist-util-position'
57+
import {visit} from 'unist-util-visit'
5758
import {zwitch} from 'zwitch'
5859

5960
/** @type {ParserOptions} */
@@ -282,23 +283,18 @@ function stitch(node, state) {
282283
state.stitches = true
283284

284285
/** @type {Node} */
285-
let clone
286+
const clone = cloneWithoutChildren(node)
286287

287288
// Recurse, because to somewhat handle `[<x>]</x>` (where `[]` denotes the
288289
// passed through node).
289-
if ('children' in node) {
290-
// To do: deep clone.
291-
clone = {
292-
...node,
293-
children: raw(
294-
{type: 'root', children: node.children},
295-
state.file,
296-
state.options
297-
// @ts-expect-error Assume a given parent yields a parent.
298-
).children
299-
}
300-
} else {
301-
clone = {...node}
290+
if ('children' in node && 'children' in clone) {
291+
const fakeRoot = raw(
292+
{type: 'root', children: node.children},
293+
state.file,
294+
state.options
295+
)
296+
// @ts-expect-error Assume a given parent yields a parent.
297+
clone.children = fakeRoot.children
302298
}
303299

304300
// Hack: `value` is supposed to be a string, but as none of the tools
@@ -641,3 +637,17 @@ function createParse5Location(node) {
641637
function isOptions(value) {
642638
return Boolean(value && !('message' in value && 'messages' in value))
643639
}
640+
641+
/**
642+
* @template {Node} NodeType
643+
* Node type.
644+
* @param {NodeType} node
645+
* Node to clone.
646+
* @returns {NodeType}
647+
* Cloned node, without children.
648+
*/
649+
function cloneWithoutChildren(node) {
650+
return 'children' in node
651+
? extend(true, {}, {...node, children: []})
652+
: extend(true, {}, node)
653+
}

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
],
3737
"dependencies": {
3838
"@types/hast": "^2.0.0",
39+
"extend": "^3.0.0",
3940
"hast-util-from-parse5": "^7.0.0",
4041
"hast-util-to-parse5": "^7.0.0",
4142
"html-void-elements": "^2.0.0",

0 commit comments

Comments
 (0)