11import type { HighlightResult , RehypeHighlightOption } from '@nuxtjs/mdc'
22import { rehypeHighlight as rehypeHighlightUniversal } from './rehype'
3+ import { useRuntimeConfig } from '#imports'
4+
5+ class HighlighterError extends Error {
6+ constructor (
7+ message : string ,
8+ public readonly httpStatus ?: number ,
9+ ) {
10+ super ( message )
11+ this . name = 'HighlighterError'
12+ }
13+ }
14+
15+ function isHighlightResult ( res ?: HighlightResult ) : res is HighlightResult {
16+ if ( ! res ) return false
17+ return 'tree' in res
18+ }
319
420const defaults : RehypeHighlightOption = {
521 theme : { } ,
@@ -9,17 +25,32 @@ const defaults: RehypeHighlightOption = {
925 return import ( '#mdc-highlighter' ) . then ( h => h . default ( code , lang , theme , options ) ) . catch ( ( ) => ( { } ) )
1026 }
1127
12- return await $fetch ( '/api/_mdc/highlight' , {
28+ if ( import . meta. client ) {
29+ const highlight = useRuntimeConfig ( ) . public . mdc . highlight
30+ if ( highlight === false ) {
31+ return Promise . resolve ( { tree : [ { type : 'text' , value : code } ] , className : '' , style : '' } as HighlightResult )
32+ }
33+ // https://github.com/nuxt-content/mdc/blob/690fd5359e743db04edf21bcd488f2c5292db176/src/module.ts#L78
34+ if ( highlight ?. noApiRoute === true ) {
35+ return import ( '#mdc-highlighter' ) . then ( h => h . default ( code , lang , theme , options ) ) . catch ( ( ) => ( { } ) )
36+ }
37+ }
38+
39+ const result = await $fetch < HighlightResult | undefined > ( '/api/_mdc/highlight' , {
1340 params : {
1441 code,
1542 lang,
1643 theme : JSON . stringify ( theme ) ,
1744 options : JSON . stringify ( options ) ,
1845 } ,
1946 } )
47+ if ( ! isHighlightResult ( result ) ) {
48+ throw new HighlighterError ( `result:${ result } ` )
49+ }
50+ return result
2051 }
2152 catch ( e : any ) {
22- if ( import . meta. client && e ?. response ?. status === 404 ) {
53+ if ( import . meta. client && ( e ?. response ?. status > 399 || e ?. name == 'HighlighterError' ) ) {
2354 window . sessionStorage . setItem ( 'mdc-shiki-highlighter' , 'browser' )
2455 return this . highlighter ?.( code , lang , theme , options )
2556 }
0 commit comments