-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathcode-runners.ts
245 lines (224 loc) · 7.67 KB
/
code-runners.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
235
236
237
238
239
240
241
242
243
244
245
import { createSingletonPromise } from '@antfu/utils'
import type { CodeRunner, CodeRunnerOutput, CodeRunnerOutputText, CodeRunnerOutputs } from '@slidev/types'
import type { CodeToHastOptions } from 'shiki'
import type ts from 'typescript'
import { ref } from 'vue'
import { isDark } from '../logic/dark'
import deps from '#slidev/monaco-run-deps'
import setups from '#slidev/setups/code-runners'
export default createSingletonPromise(async () => {
const runners: Record<string, CodeRunner> = {
javascript: runTypeScript,
js: runTypeScript,
typescript: runTypeScript,
ts: runTypeScript,
}
const { shiki, themes } = await import('#slidev/shiki')
const highlighter = await shiki
const highlight = (code: string, lang: string, options: Partial<CodeToHastOptions> = {}) => highlighter.codeToHtml(code, {
lang,
theme: typeof themes === 'string'
? themes
: isDark.value
? themes.dark || 'vitesse-dark'
: themes.light || 'vitesse-light',
...options,
})
const run = async (code: string, lang: string, options: Record<string, unknown>): Promise<CodeRunnerOutputs> => {
try {
const runner = runners[lang]
if (!runner)
throw new Error(`Runner for language "${lang}" not found`)
return await runner(
code,
{
options,
highlight,
run: async (code, lang) => {
return await run(code, lang, options)
},
},
)
}
catch (e) {
console.error(e)
return {
error: `${e}`,
}
}
}
for (const setup of setups) {
const result = await setup(runners)
Object.assign(runners, result)
}
return {
highlight,
run,
}
})
// Ported from https://github.com/microsoft/TypeScript-Website/blob/v2/packages/playground/src/sidebar/runtime.ts
function runJavaScript(code: string): CodeRunnerOutputs {
const result = ref<CodeRunnerOutput[]>([])
const onError = (error: any) => result.value.push({ error: String(error) })
const logger = (...objs: any[]) => result.value.push(objs.map(printObject))
const vmConsole = Object.assign({}, console)
vmConsole.info = vmConsole.log = vmConsole.debug = vmConsole.warn = vmConsole.error = logger
vmConsole.clear = () => result.value.length = 0
try {
const safeJS = `return async (console, __slidev_import, __slidev_on_error) => {
try {
${sanitizeJS(code)}
} catch (e) {
__slidev_on_error(e)
}
}`
// eslint-disable-next-line no-new-func
;(new Function(safeJS)())(vmConsole, (specifier: string) => {
const mod = deps[specifier]
if (!mod)
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`)
return mod
}, onError)
}
catch (error) {
onError(error)
}
function printObject(arg: any): CodeRunnerOutputText {
if (typeof arg === 'string') {
return {
text: arg,
}
}
return {
text: objectToText(arg),
highlightLang: 'javascript',
}
}
function objectToText(arg: any): string {
let textRep = ''
if (arg instanceof Error) {
textRep = `Error: ${JSON.stringify(arg.message)}`
}
else if (arg === null || arg === undefined || typeof arg === 'symbol') {
textRep = String(arg)
}
else if (Array.isArray(arg)) {
textRep = `[${arg.map(objectToText).join(', ')}]`
}
else if (arg instanceof Set) {
const setIter = [...arg]
textRep = `Set (${arg.size}) {${setIter.map(objectToText).join(', ')}}`
}
else if (arg instanceof Map) {
const mapIter = [...arg.entries()]
textRep
= `Map (${arg.size}) {${mapIter
.map(([k, v]) => `${objectToText(k)} => ${objectToText(v)}`)
.join(', ')
}}`
}
else if (arg instanceof RegExp) {
textRep = arg.toString()
}
else if (typeof arg === 'string') {
textRep = JSON.stringify(arg)
}
else if (typeof arg === 'object') {
const name = arg.constructor?.name ?? ''
// No one needs to know an obj is an obj
const nameWithoutObject = name && name === 'Object' ? '' : name
const prefix = nameWithoutObject ? `${nameWithoutObject}: ` : ''
// 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
textRep
= prefix
+ JSON.stringify(arg, (_, value) => (value === undefined ? '__undefined__' : value), 2).replace(
/"__undefined__"/g,
'undefined',
)
textRep = String(textRep)
}
else {
textRep = String(arg)
}
return textRep
}
function sanitizeJS(code: string) {
// The reflect-metadata runtime is available, so allow that to go through
code = code.replace(`import "reflect-metadata"`, '').replace(`require("reflect-metadata")`, '')
// Transpiled typescript sometimes contains an empty export, remove it.
code = code.replace('export {};', '')
return code
}
return result
}
let tsModule: typeof import('typescript') | undefined
export async function runTypeScript(code: string) {
tsModule ??= await import('typescript')
code = tsModule.transpileModule(code, {
compilerOptions: {
module: tsModule.ModuleKind.ESNext,
target: tsModule.ScriptTarget.ES2022,
},
transformers: {
after: [transformImports],
},
}).outputText
const importRegex = /import\s*\((.+)\)/g
code = code.replace(importRegex, (_full, specifier) => `__slidev_import(${specifier})`)
return runJavaScript(code)
}
/**
* Transform import statements to dynamic imports
*/
function transformImports(context: ts.TransformationContext): ts.Transformer<ts.SourceFile> {
const { factory } = context
const { isImportDeclaration, isNamedImports, NodeFlags } = tsModule!
return (sourceFile: ts.SourceFile) => {
const statements = [...sourceFile.statements]
for (let i = 0; i < statements.length; i++) {
const statement = statements[i]
if (!isImportDeclaration(statement))
continue
let bindingPattern: ts.ObjectBindingPattern | ts.Identifier
const namedBindings = statement.importClause?.namedBindings
const bindings: ts.BindingElement[] = []
if (statement.importClause?.name)
bindings.push(factory.createBindingElement(undefined, factory.createIdentifier('default'), statement.importClause.name))
if (namedBindings) {
if (isNamedImports(namedBindings)) {
for (const specifier of namedBindings.elements)
bindings.push(factory.createBindingElement(undefined, specifier.propertyName, specifier.name))
bindingPattern = factory.createObjectBindingPattern(bindings)
}
else {
bindingPattern = factory.createIdentifier(namedBindings.name.text)
}
}
else {
bindingPattern = factory.createObjectBindingPattern(bindings)
}
const newStatement = factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
bindingPattern,
undefined,
undefined,
factory.createAwaitExpression(
factory.createCallExpression(
factory.createIdentifier('import'),
undefined,
[statement.moduleSpecifier],
),
),
),
],
NodeFlags.Const,
),
)
statements[i] = newStatement
}
return factory.updateSourceFile(sourceFile, statements)
}
}