1
- import { name as isIdentifierName } from 'estree-util-is-identifier-name'
2
1
import { valueToEstree } from 'estree-util-value-to-estree'
3
2
import { type Literal , type Root } from 'mdast'
4
3
import { parse as parseToml } from 'toml'
5
4
import { type Plugin } from 'unified'
5
+ import { define } from 'unist-util-mdx-define'
6
6
import { parse as parseYaml } from 'yaml'
7
7
8
8
type FrontmatterParsers = Record < string , ( value : string ) => unknown >
9
9
10
- export interface RemarkMdxFrontmatterOptions {
10
+ export interface RemarkMdxFrontmatterOptions extends define . Options {
11
11
/**
12
12
* If specified, the YAML data is exported using this name. Otherwise, each
13
13
* object key will be used as an export name.
@@ -34,19 +34,16 @@ export interface RemarkMdxFrontmatterOptions {
34
34
*/
35
35
const remarkMdxFrontmatter : Plugin < [ RemarkMdxFrontmatterOptions ?] , Root > = ( {
36
36
name = 'frontmatter' ,
37
- parsers
37
+ parsers,
38
+ ...options
38
39
} = { } ) => {
39
- if ( ! isIdentifierName ( name ) ) {
40
- throw new Error ( `Name should be a valid identifier, got: ${ JSON . stringify ( name ) } ` )
41
- }
42
-
43
40
const allParsers : FrontmatterParsers = {
44
41
yaml : parseYaml ,
45
42
toml : parseToml ,
46
43
...parsers
47
44
}
48
45
49
- return ( ast ) => {
46
+ return ( ast , file ) => {
50
47
let data : unknown
51
48
const node = ast . children . find ( ( child ) => Object . hasOwn ( allParsers , child . type ) )
52
49
@@ -57,33 +54,7 @@ const remarkMdxFrontmatter: Plugin<[RemarkMdxFrontmatterOptions?], Root> = ({
57
54
data = parser ( value )
58
55
}
59
56
60
- ast . children . unshift ( {
61
- type : 'mdxjsEsm' ,
62
- value : '' ,
63
- data : {
64
- estree : {
65
- type : 'Program' ,
66
- sourceType : 'module' ,
67
- body : [
68
- {
69
- type : 'ExportNamedDeclaration' ,
70
- specifiers : [ ] ,
71
- declaration : {
72
- type : 'VariableDeclaration' ,
73
- kind : 'const' ,
74
- declarations : [
75
- {
76
- type : 'VariableDeclarator' ,
77
- id : { type : 'Identifier' , name } ,
78
- init : valueToEstree ( data , { preserveReferences : true } )
79
- }
80
- ]
81
- }
82
- }
83
- ]
84
- }
85
- }
86
- } )
57
+ define ( ast , file , { [ name ] : valueToEstree ( data , { preserveReferences : true } ) } , options )
87
58
}
88
59
}
89
60
0 commit comments