返回 slidev
code-runners.ts
根目录 / packages / client / setup / code-runners.ts
1 import type { CodeRunner, CodeRunnerOutput, CodeRunnerOutputs, CodeRunnerOutputText } from '@slidev/types'
2 import type { CodeToHastOptions } from 'shiki'
3 import type ts from 'typescript'
4 import { createSingletonPromise } from '@antfu/utils'
5 import { ref } from 'vue'
6 import deps from '#slidev/monaco-run-deps'
7 import setups from '#slidev/setups/code-runners'
8 import { configs } from '../env'
9
10 export default createSingletonPromise(async () => {
11 const runners: Record<string, CodeRunner> = {
12 javascript: runTypeScript,
13 js: runTypeScript,
14 typescript: runTypeScript,
15 ts: runTypeScript,
16 }
17
18 const { defaultHighlightOptions, getEagerHighlighter } = await (await import('./shiki')).default()
19
20 const highlighter = await getEagerHighlighter()
21 const highlight = (code: string, lang: string, options?: Partial<CodeToHastOptions>) => {
22 return highlighter.codeToHtml(code, {
23 ...defaultHighlightOptions,
24 lang,
25 ...options,
26 })
27 }
28
29 const run = async (code: string, lang: string, options: Record<string, unknown>): Promise<CodeRunnerOutputs> => {
30 try {
31 const runner = runners[lang]
32 if (!runner)
33 throw new Error(`Runner for language "${lang}" not found`)
34 return await runner(
35 code,
36 {
37 options,
38 highlight,
39 run: async (code, lang) => {
40 return await run(code, lang, options)
41 },
42 },
43 )
44 }
45 catch (e) {
46 console.error(e)
47 return {
48 error: `${e}`,
49 }
50 }
51 }
52
53 for (const setup of setups) {
54 const result = await setup(runners)
55 Object.assign(runners, result)
56 }
57
58 return {
59 highlight,
60 run,
61 }
62 })
63
64 // Ported from https://github.com/microsoft/TypeScript-Website/blob/v2/packages/playground/src/sidebar/runtime.ts
65 function runJavaScript(code: string): CodeRunnerOutputs {
66 const result = ref<CodeRunnerOutput[]>([])
67
68 const onError = (error: any) => result.value.push({
69 error: String(error),
70 })
71 const logger = (...objs: any[]) => result.value.push(objs.map(printObject))
72 const vmConsole = Object.assign({}, console)
73 vmConsole.info = vmConsole.log = vmConsole.debug = vmConsole.warn = vmConsole.error = logger
74 vmConsole.clear = () => result.value.length = 0
75 try {
76 const wrappedCode = `return async (console, __slidev_import, __slidev_on_error) => {
77 ${configs.monacoRunUseStrict
78 ? `"use strict";`
79 : ''}
80 try {
81 ${fixupCode(code)}
82 } catch (e) {
83 __slidev_on_error(e)
84 }
85 }`
86 // eslint-disable-next-line no-new-func
87 ;(new Function(wrappedCode)())(vmConsole, (specifier: string) => {
88 const mod = deps[specifier]
89 if (!mod)
90 throw new Error(`Module not found: ${specifier}.\nAvailable modules: ${Object.keys(deps).join(', ')}. Please refer to https://sli.dev/custom/config-code-runners#additional-runner-dependencies`)
91 return mod
92 }, onError)
93 }
94 catch (error) {
95 onError(error)
96 }
97
98 function printObject(arg: any): CodeRunnerOutputText {
99 if (typeof arg === 'string') {
100 return {
101 text: arg,
102 }
103 }
104 return {
105 text: objectToText(arg),
106 highlightLang: 'javascript',
107 }
108 }
109
110 function objectToText(arg: any): string {
111 let textRep = ''
112 if (arg instanceof Error) {
113 textRep = `Error: ${JSON.stringify(arg.message)}`
114 }
115 else if (arg === null || arg === undefined || typeof arg === 'symbol') {
116 textRep = String(arg)
117 }
118 else if (Array.isArray(arg)) {
119 textRep = `[${arg.map(objectToText).join(', ')}]`
120 }
121 else if (arg instanceof Set) {
122 const setIter = [...arg]
123 textRep = `Set (${arg.size}) {${setIter.map(objectToText).join(', ')}}`
124 }
125 else if (arg instanceof Map) {
126 const mapIter = [
127 ...arg.entries(),
128 ]
129 textRep
130 = `Map (${arg.size}) {${mapIter
131 .map(([k, v]) => `${objectToText(k)} => ${objectToText(v)}`)
132 .join(', ')
133 }}`
134 }
135 else if (arg instanceof RegExp) {
136 textRep = arg.toString()
137 }
138 else if (typeof arg === 'string') {
139 textRep = JSON.stringify(arg)
140 }
141 else if (typeof arg === 'object') {
142 const name = arg.constructor?.name ?? ''
143 // No one needs to know an obj is an obj
144 const nameWithoutObject = name && name === 'Object'
145 ? ''
146 : name
147 const prefix = nameWithoutObject
148 ? `${nameWithoutObject}: `
149 : ''
150
151 // JSON.stringify omits any keys with a value of undefined. To get around this, we replace undefined with the text __undefined__ and then do a global replace using regex back to keyword undefined
152 textRep
153 = prefix
154 + JSON.stringify(arg, (_, value) => (value === undefined
155 ? '__undefined__'
156 : value), 2).replace(
157 /"__undefined__"/g,
158 'undefined',
159 )
160
161 textRep = String(textRep)
162 }
163 else {
164 textRep = String(arg)
165 }
166 return textRep
167 }
168
169 function fixupCode(code: string) {
170 // The reflect-metadata runtime is available, so allow that to go through
171 code = code.replace(`import "reflect-metadata"`, '').replace(`require("reflect-metadata")`, '')
172 // Transpiled typescript sometimes contains an empty export, remove it.
173 code = code.replace('export {};', '')
174
175 return code
176 }
177
178 return result
179 }
180
181 let tsModule: typeof import('typescript') | undefined
182
183 export async function runTypeScript(code: string) {
184 tsModule ??= await import('typescript')
185
186 code = tsModule.transpileModule(code, {
187 compilerOptions: {
188 module: tsModule.ModuleKind.ESNext,
189 target: tsModule.ScriptTarget.ES2022,
190 },
191 transformers: {
192 after: [transformImports],
193 },
194 }).outputText
195
196 const importRegex = /\bimport\s*\((.+)\)/g
197 code = code.replace(importRegex, (_full, specifier) => `__slidev_import(${specifier})`)
198
199 return runJavaScript(code)
200 }
201
202 /**
203 * Transform import statements to dynamic imports
204 */
205 function transformImports(context: ts.TransformationContext): ts.Transformer<ts.SourceFile> {
206 const { factory } = context
207 const { isImportDeclaration, isNamedImports, NodeFlags } = tsModule!
208 return (sourceFile: ts.SourceFile) => {
209 const statements = [...sourceFile.statements]
210 for (let i = 0; i < statements.length; i++) {
211 const statement = statements[i]
212 if (!isImportDeclaration(statement))
213 continue
214 let bindingPattern: ts.ObjectBindingPattern | ts.Identifier
215 const namedBindings = statement.importClause?.namedBindings
216 const bindings: ts.BindingElement[] = []
217 if (statement.importClause?.name)
218 bindings.push(factory.createBindingElement(undefined, factory.createIdentifier('default'), statement.importClause.name))
219 if (namedBindings) {
220 if (isNamedImports(namedBindings)) {
221 for (const specifier of namedBindings.elements)
222 bindings.push(factory.createBindingElement(undefined, specifier.propertyName, specifier.name))
223 bindingPattern = factory.createObjectBindingPattern(bindings)
224 }
225 else {
226 bindingPattern = factory.createIdentifier(namedBindings.name.text)
227 }
228 }
229 else {
230 bindingPattern = factory.createObjectBindingPattern(bindings)
231 }
232
233 const newStatement = factory.createVariableStatement(
234 undefined,
235 factory.createVariableDeclarationList(
236 [
237 factory.createVariableDeclaration(
238 bindingPattern,
239 undefined,
240 undefined,
241 factory.createAwaitExpression(
242 factory.createCallExpression(
243 factory.createIdentifier('import'),
244 undefined,
245 [statement.moduleSpecifier],
246 ),
247 ),
248 ),
249 ],
250 NodeFlags.Const,
251 ),
252 )
253 statements[i] = newStatement
254 }
255 return factory.updateSourceFile(sourceFile, statements)
256 }
257 }
258
258 lines TYPESCRIPT