-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.ts
executable file
·234 lines (193 loc) · 7.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import type { Node } from "unist"
import { TwoslashError, TwoSlashReturn } from "@typescript/twoslash"
import visit from "unist-util-visit"
import { lex, parse } from "fenceparser"
import { Lang, Highlighter, getHighlighter } from "shiki"
import { UserConfigSettings, renderCodeToHTML } from "shiki-twoslash"
import { cachedTwoslashCall } from "./caching"
import { addIncludes, replaceIncludesInCode } from "./includes"
import { setupNodeForTwoslashException } from "./exceptionMessageDOM"
type Fence = {
lang: string
meta: NonNullable<ReturnType<typeof parse>>
}
// A set of includes which can be pulled via a set ID
const includes = new Map<string, string>()
function getHTML(
code: string,
fence: Fence,
highlighters: Highlighter[],
twoslash: TwoSlashReturn | undefined,
twoslashSettings: UserConfigSettings
) {
// Shiki doesn't respect json5 as an input, so switch it
// to json, which can handle comments in the syntax highlight
const replacer: Record<string, string> = {
json5: "json",
}
if (replacer[fence.lang]) fence.lang = replacer[fence.lang]
let results
// Support 'twoslash' includes
if (fence.lang === "twoslash") {
if (!fence.meta.include || typeof fence.meta.include !== "string") {
throw new Error("A twoslash code block needs a pragma like 'twoslash include [name]'")
}
addIncludes(includes, fence.meta.include as string, code)
results = twoslashSettings.wrapFragments ? `<div class="shiki-twoslash-fragment"></div>` : ""
} else {
// All good, get each highlighter and render the shiki output for it
const output = highlighters.map(highlighter => {
// @ts-ignore
const themeName: string = highlighter.customName.split("/").pop().replace(".json", "")
return renderCodeToHTML(code, fence.lang, fence.meta, { themeName, ...twoslashSettings }, highlighter, twoslash)
})
results = output.join("\n")
if (highlighters.length > 1 && twoslashSettings.wrapFragments) {
results = `<div class="shiki-twoslash-fragment">${results}</div>`
}
}
return results
}
/**
* Runs twoslash across an AST node, switching out the text content, and lang
* and adding a `twoslash` property to the node.
*/
export const runTwoSlashOnNode = (code: string, { lang, meta }: Fence, settings: UserConfigSettings = {}) => {
// Offer a way to do high-perf iterations, this is less useful
// given that we cache the results of twoslash in the file-system
const shouldDisableTwoslash = typeof process !== "undefined" && process.env && !!process.env.TWOSLASH_DISABLE
if (shouldDisableTwoslash) return undefined
// Only run twoslash when the meta has the attribute twoslash
if (meta.twoslash) {
const importedCode = replaceIncludesInCode(includes, code)
return cachedTwoslashCall(importedCode, lang, settings)
}
return undefined
}
// To make sure we only have one highlighter per theme in a process
const highlighterCache = new Map<UserConfigSettings, Promise<Highlighter[]>>()
/** Sets up the highlighters, and cache's for recalls */
export const highlightersFromSettings = (settings: UserConfigSettings) => {
// console.log("i should only log once per theme")
// ^ uncomment this to debug if required
const themes = settings.themes || (settings.theme ? [settings.theme] : ["light-plus"])
return Promise.all(
themes.map(async theme => {
// You can put a string, a path, or the JSON theme obj
const themeName = (theme as any).name || theme
const highlighter = await getHighlighter({ ...settings, theme, themes: undefined })
// @ts-ignore - https://github.com/shikijs/shiki/pull/162 will fix this
highlighter.customName = themeName
return highlighter
})
)
}
const parsingNewFile = () => includes.clear()
const parseFence = (fence: string): Fence => {
const [lang, ...tokens] = lex(fence)
// if the language is twoslash and include key is found
// insert an `=` after include to make it `include=[name]`
// which yields better meta
if (lang === "twoslash") {
// Search for `include` in tokens
const index = tokens.indexOf("include")
if (index !== -1) {
tokens.splice(index + 1, 0, "=")
}
}
const meta = parse(tokens) ?? {}
return {
lang: (lang || "").toString(),
meta,
}
}
// --- The Remark API ---
/* A rich AST node for uninst with twoslash'd data */
type RemarkCodeNode = Node & {
lang?: Lang
meta?: string
// ^ according to mdast
type: string
value: string
children: Node[]
twoslash?: TwoSlashReturn
}
export type Options = UserConfigSettings
/**
* Synchronous outer function, async inner function, which is how the remark
* async API works.
*/
function remarkTwoslash(settings: Options = {}) {
if (!highlighterCache.has(settings)) {
highlighterCache.set(settings, highlightersFromSettings(settings))
}
const transform = async (markdownAST: any) => {
const highlighters = await highlighterCache.get(settings)!
parsingNewFile()
visit(markdownAST, "code", remarkVisitor(highlighters, settings))
}
return transform
}
/**
* The function doing the work of transforming any codeblock samples in a remark AST.
*/
export const remarkVisitor =
(highlighters: Highlighter[], twoslashSettings: UserConfigSettings = {}) =>
(node: RemarkCodeNode) => {
const code = node.value
let fence: Fence = undefined!
try {
fence = parseFence([node.lang, node.meta].filter(Boolean).join(" "))
} catch (error) {
const twoslashError = new TwoslashError("Codefence error", "Could not parse the codefence for this code sample", "It's usually an unclosed string", code)
return setupNodeForTwoslashException(code, node, twoslashError)
}
// Do nothing if the node has an attribute to ignore
if (Object.keys(fence.meta).filter(key => (twoslashSettings.ignoreCodeblocksWithCodefenceMeta || []).includes(key)).length > 0) {
return
}
let twoslash: TwoSlashReturn | undefined
try {
// By allowing node.twoslash to already exist you can set it up yourself in a browser
twoslash = node.twoslash || runTwoSlashOnNode(code, fence, twoslashSettings)
} catch (error) {
const shouldAlwaysRaise = process && process.env && !!process.env.CI
const yeahButNotInTests = typeof jest === "undefined"
if ((shouldAlwaysRaise && yeahButNotInTests) || twoslashSettings.alwayRaiseForTwoslashExceptions) {
throw error
} else {
return setupNodeForTwoslashException(code, node, error)
}
}
if (twoslash) {
node.value = twoslash.code
node.lang = twoslash.extension as Lang
node.twoslash = twoslash
}
const shikiHTML = getHTML(node.value, fence, highlighters, twoslash, twoslashSettings)
node.type = "html"
node.value = shikiHTML
node.children = []
}
export default remarkTwoslash
// --- The Markdown-it API ---
/** Only the inner function exposed as a synchronous API for markdown-it */
export const setupForFile = async (settings: UserConfigSettings = {}) => {
parsingNewFile()
if (!highlighterCache.has(settings)) {
highlighterCache.set(settings, highlightersFromSettings(settings))
}
let highlighters = await highlighterCache.get(settings)!
return { settings, highlighters }
}
export const transformAttributesToHTML = (
code: string,
fenceString: string,
highlighters: Highlighter[],
settings: UserConfigSettings
) => {
const fence = parseFence(fenceString)
const twoslash = runTwoSlashOnNode(code, fence, settings)
const newCode = (twoslash && twoslash.code) || code
return getHTML(newCode, fence, highlighters, twoslash, settings)
}