1
+ import { defineCodeRunnersSetup } from '@slidev/types'
2
+ import { CodeRunnerOutputs } from '@slidev/types'
3
+
4
+ export default defineCodeRunnersSetup ( ( ) => {
5
+ return {
6
+ async python ( code ) {
7
+ const results = await godboltPythonRequest ( code ) ;
8
+ return results ;
9
+ }
10
+ }
11
+ } )
12
+
13
+ async function godboltPythonRequest ( code : string ) : Promise < CodeRunnerOutputs > {
14
+ try {
15
+ // Godbolt API URL for Python 3.12
16
+ const apiUrl = 'https://godbolt.org/api/compiler/python312/compile' ;
17
+
18
+ // Make an asynchronous POST request to the Godbolt API with the Python code
19
+ const response = await fetch ( apiUrl , {
20
+ method : 'POST' ,
21
+ headers : {
22
+ 'Content-Type' : 'application/json' ,
23
+ 'Accept' : 'application/json' // We need to explicitly ask for a JSON response, text is the default
24
+ } ,
25
+ body : JSON . stringify ( {
26
+ source : code ,
27
+ options : {
28
+ compilerOptions : { "executorRequest" : true } , // We want to compile + execute
29
+ executeParameters : { } ,
30
+ }
31
+ } )
32
+ } ) ;
33
+
34
+ // Check if the response is successful
35
+ if ( ! response . ok ) {
36
+ return {
37
+ error : `Bad response: ${ response . statusText } `
38
+ } ;
39
+ }
40
+
41
+ // Parse the response as JSON
42
+ const result = await response . json ( ) ;
43
+
44
+ // Extract stdout lines and convert them into CodeRunnerOutputText objects
45
+ const stdout = result . stdout . map ( ( line : any ) => ( {
46
+ text : line . text
47
+ // Hack to keep leading whitespace
48
+ . replace ( / \s / g, " " )
49
+ . replace ( / \t / g, " " )
50
+ }
51
+ ) ) ;
52
+
53
+ // Extract stderr lines and convert them into CodeRunnerOutputText objects
54
+ const stderr = result . stderr . map ( ( line : any ) => ( {
55
+ text : line . text
56
+ // Hack to keep leading whitespace
57
+ . replace ( / \s / g, " " )
58
+ . replace ( / \t / g, " " ) ,
59
+ class : 'text-red-500'
60
+ }
61
+ ) ) ;
62
+
63
+ if ( stderr . length !== 0 ) {
64
+ return stderr ;
65
+ } else if ( stdout . length !== 0 ) {
66
+ return stdout ;
67
+ } else {
68
+ return {
69
+ text : 'No output received'
70
+ } ;
71
+ }
72
+ } catch ( error ) {
73
+ console . error ( 'Failed to execute Python code:' , error ) ;
74
+ return {
75
+ error : `Failed to execute Python code: ${ error . message } `
76
+ } ;
77
+ }
78
+ }
79
+
0 commit comments