-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.tsx
More file actions
238 lines (212 loc) · 6.43 KB
/
runtime.tsx
File metadata and controls
238 lines (212 loc) · 6.43 KB
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
"use client";
import {
useState,
useRef,
useCallback,
ReactNode,
createContext,
useContext,
useEffect,
} from "react";
import { SyntaxStatus, ReplOutput, ReplCommand } from "../repl";
import { Mutex, MutexInterface } from "async-mutex";
import { RuntimeContext } from "../runtime";
const JavaScriptContext = createContext<RuntimeContext>(null!);
export function useJavaScript(): RuntimeContext {
const context = useContext(JavaScriptContext);
if (!context) {
throw new Error("useJavaScript must be used within a JavaScriptProvider");
}
return context;
}
type MessageToWorker =
| {
type: "init";
payload?: undefined;
}
| {
type: "runJavaScript";
payload: { code: string };
}
| {
type: "checkSyntax";
payload: { code: string };
}
| {
type: "restoreState";
payload: { commands: string[] };
};
type MessageFromWorker =
| { id: number; payload: unknown }
| { id: number; error: string };
type InitPayloadFromWorker = { success: boolean };
type RunPayloadFromWorker = {
output: ReplOutput[];
updatedFiles: [string, string][];
};
type StatusPayloadFromWorker = { status: SyntaxStatus };
export function JavaScriptProvider({ children }: { children: ReactNode }) {
const workerRef = useRef<Worker | null>(null);
const [ready, setReady] = useState<boolean>(false);
const mutex = useRef<MutexInterface>(new Mutex());
const messageCallbacks = useRef<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Map<number, [(payload: any) => void, (error: string) => void]>
>(new Map());
const nextMessageId = useRef<number>(0);
const executedCommands = useRef<string[]>([]);
function postMessage<T>({ type, payload }: MessageToWorker) {
const id = nextMessageId.current++;
return new Promise<T>((resolve, reject) => {
messageCallbacks.current.set(id, [resolve, reject]);
workerRef.current?.postMessage({ id, type, payload });
});
}
const initializeWorker = useCallback(() => {
const worker = new Worker("/javascript.worker.js");
workerRef.current = worker;
worker.onmessage = (event) => {
const data = event.data as MessageFromWorker;
if (messageCallbacks.current.has(data.id)) {
const [resolve, reject] = messageCallbacks.current.get(data.id)!;
if ("error" in data) {
reject(data.error);
} else {
resolve(data.payload);
}
messageCallbacks.current.delete(data.id);
}
};
return postMessage<InitPayloadFromWorker>({
type: "init",
}).then(({ success }) => {
if (success) {
setReady(true);
}
return worker;
});
}, []);
useEffect(() => {
let worker: Worker | null = null;
initializeWorker().then((w) => {
worker = w;
});
return () => {
worker?.terminate();
};
}, [initializeWorker]);
const interrupt = useCallback(() => {
// Since we can't interrupt JavaScript execution directly,
// we terminate the worker and restart it, then restore state
// Reject all pending callbacks before terminating
const error = "Worker interrupted";
messageCallbacks.current.forEach(([, reject]) => reject(error));
messageCallbacks.current.clear();
// Terminate the current worker
workerRef.current?.terminate();
// Reset ready state
setReady(false);
mutex.current.runExclusive(async () => {
// Create a new worker and wait for it to be ready
await initializeWorker();
// Restore state by re-executing previous commands
if (executedCommands.current.length > 0) {
await postMessage<{ success: boolean }>({
type: "restoreState",
payload: { commands: executedCommands.current },
});
}
});
}, [initializeWorker]);
const runCommand = useCallback(
async (code: string): Promise<ReplOutput[]> => {
if (!mutex.current.isLocked()) {
throw new Error(
"mutex of JavaScriptContext must be locked for runCommand"
);
}
if (!workerRef.current || !ready) {
return [{ type: "error", message: "JavaScript runtime is not ready yet." }];
}
try {
const { output } = await postMessage<RunPayloadFromWorker>({
type: "runJavaScript",
payload: { code },
});
// Save successfully executed command
executedCommands.current.push(code);
return output;
} catch (error) {
// Handle errors (including "Worker interrupted")
if (error instanceof Error) {
return [{ type: "error", message: error.message }];
}
return [{ type: "error", message: String(error) }];
}
},
[ready]
);
const checkSyntax = useCallback(
async (code: string): Promise<SyntaxStatus> => {
if (!workerRef.current || !ready) return "invalid";
const { status } = await mutex.current.runExclusive(() =>
postMessage<StatusPayloadFromWorker>({
type: "checkSyntax",
payload: { code },
})
);
return status;
},
[ready]
);
const runFiles = useCallback(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async (_filenames: string[]): Promise<ReplOutput[]> => {
return [
{
type: "error",
message: "JavaScript file execution is not supported in this runtime",
},
];
},
[]
);
const splitReplExamples = useCallback((content: string): ReplCommand[] => {
const initCommands: { command: string; output: ReplOutput[] }[] = [];
for (const line of content.split("\n")) {
if (line.startsWith("> ")) {
// Remove the prompt from the command
initCommands.push({ command: line.slice(2), output: [] });
} else {
// Lines without prompt are output from the previous command
if (initCommands.length > 0) {
initCommands[initCommands.length - 1].output.push({
type: "stdout",
message: line,
});
}
}
}
return initCommands;
}, []);
const getCommandlineStr = useCallback(
(filenames: string[]) => `node ${filenames[0]}`,
[]
);
return (
<JavaScriptContext.Provider
value={{
ready,
runCommand,
checkSyntax,
mutex: mutex.current,
runFiles,
interrupt,
splitReplExamples,
getCommandlineStr,
}}
>
{children}
</JavaScriptContext.Provider>
);
}