Skip to content

Commit

Permalink
Add improved error message for MDX nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Jan 15, 2023
1 parent d1d95a1 commit 8e7f703
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ import {pointStart, pointEnd} from 'unist-util-position'
import {visit} from 'unist-util-visit'
import {zwitch} from 'zwitch'

// Node types associated with MDX.
// <https://github.com/mdx-js/mdx/blob/641eb91/packages/mdx/lib/node-types.js>
const knownMdxNames = new Set([
'mdxFlowExpression',
'mdxJsxFlowElement',
'mdxJsxTextElement',
'mdxTextExpression',
'mdxjsEsm'
])

/** @type {ParserOptions} */
const parseOptions = {sourceCodeLocationInfo: true, scriptingEnabled: false}

Expand Down Expand Up @@ -392,8 +402,14 @@ function unknown(node_, state) {
) {
stitch(node, state)
} else {
// To do: add improved error message.
throw new Error('Cannot compile `' + node.type + '` node')
let extra = ''

if (knownMdxNames.has(node.type)) {
extra =
". It looks like you are using MDX nodes with `hast-util-raw` (or `rehype-raw`). If you use this because you are using remark or rehype plugins that inject `'html'` nodes, then please raise an issue with that plugin, as its a bad and slow idea. If you use this because you are using markdown syntax, then you have to configure this utility (or plugin) to pass through these nodes (see `passThrough` in docs), but you can also migrate to use the MDX syntax"
}

throw new Error('Cannot compile `' + node.type + '` node' + extra)
}
}

Expand Down
5 changes: 5 additions & 0 deletions test-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ export interface CustomLiteral extends Literal {
type: 'customLiteral'
}

export interface MdxjsEsm extends Literal {
type: 'mdxjsEsm'
}

declare module 'hast' {
interface RootContentMap {
customLiteral: CustomLiteral
customParent: CustomParent
mdxjsEsm: MdxjsEsm
}

interface ElementContentMap {
Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ test('raw', () => {
'should throw for unknown nodes'
)

assert.throws(
() => {
raw(u('root', [u('mdxjsEsm', '')]))
},
/^Error: Cannot compile `mdxjsEsm` node. It looks like you are using MDX nodes/,
'should throw for unknown nodes'
)

assert.deepEqual(
raw(h('#foo.bar', 'baz')),
h('#foo.bar', 'baz'),
Expand Down

0 comments on commit 8e7f703

Please sign in to comment.