1+ import 'core-js/full/array/from-async' ;
2+
13import Router , { RouterParamContext } from '@koa/router' ;
24import { Context , Middleware } from 'koa' ;
35import { HTTPError } from 'koajax' ;
@@ -58,14 +60,25 @@ export interface ArticleMeta {
5860
5961const MDX_pattern = / \. m d x ? $ / ;
6062
61- export async function frontMatterOf ( path : string ) {
63+ export async function splitFrontMatter ( path : string ) {
6264 const { readFile } = await import ( 'fs/promises' ) ;
6365
6466 const file = await readFile ( path , 'utf-8' ) ;
6567
66- const [ , frontMatter ] = file . match ( / ^ - - - [ \r \n ] ( [ \s \S ] + ?[ \r \n ] ) - - - / ) || [ ] ;
68+ const [ , frontMatter , markdown ] =
69+ file . trim ( ) . match ( / ^ - - - [ \r \n ] ( [ \s \S ] + ?[ \r \n ] ) - - - [ \r \n ] ( [ \s \S ] * ) / ) || [ ] ;
70+
71+ if ( ! frontMatter ) return { markdown : file } ;
72+
73+ try {
74+ const meta = parse ( frontMatter ) as DataObject ;
75+
76+ return { markdown, meta } ;
77+ } catch ( error ) {
78+ console . error ( `Error reading front matter for ${ path } :` , error ) ;
6779
68- return frontMatter && parse ( frontMatter ) ;
80+ return { markdown } ;
81+ }
6982}
7083
7184export async function * pageListOf ( path : string , prefix = 'pages' ) : AsyncGenerator < ArticleMeta > {
@@ -85,13 +98,11 @@ export async function* pageListOf(path: string, prefix = 'pages'): AsyncGenerato
8598
8699 if ( node . isFile ( ) && isMDX ) {
87100 const article : ArticleMeta = { name, path, subs : [ ] } ;
88- try {
89- const meta = await frontMatterOf ( `${ node . path } /${ node . name } ` ) ;
90101
91- if ( meta ) article . meta = meta ;
92- } catch ( error ) {
93- console . error ( `Error reading front matter for ${ node . path } / ${ node . name } :` , error ) ;
94- }
102+ const { meta } = await splitFrontMatter ( ` ${ node . path } / ${ node . name } ` ) ;
103+
104+ if ( meta ) article . meta = meta ;
105+
95106 yield article ;
96107 }
97108 if ( ! node . isDirectory ( ) ) continue ;
@@ -106,9 +117,12 @@ export type TreeNode<K extends string> = {
106117 [ key in K ] : TreeNode < K > [ ] ;
107118} ;
108119
109- export function * traverseTree < K extends string > ( tree : TreeNode < K > , key : K ) : Generator < TreeNode < K > > {
120+ export function * traverseTree < K extends string , N extends TreeNode < K > > (
121+ tree : N ,
122+ key : K ,
123+ ) : Generator < N > {
110124 for ( const node of tree [ key ] || [ ] ) {
111- yield node ;
112- yield * traverseTree ( node , key ) ;
125+ yield node as N ;
126+ yield * traverseTree ( node as N , key ) ;
113127 }
114128}
0 commit comments