Skip to content

Commit

Permalink
Fix to deep clone unknown nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Jan 15, 2023
1 parent 386d2f3 commit 9910e6b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
44 changes: 27 additions & 17 deletions lib/index.js
Expand Up @@ -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} */
Expand Down Expand Up @@ -282,23 +283,18 @@ function stitch(node, state) {
state.stitches = true

/** @type {Node} */
let clone
const clone = cloneWithoutChildren(node)

// Recurse, because to somewhat handle `[<x>]</x>` (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
Expand Down Expand Up @@ -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)
}
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -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",
Expand Down

0 comments on commit 9910e6b

Please sign in to comment.