-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.tsx
More file actions
224 lines (203 loc) · 6.17 KB
/
runtime.tsx
File metadata and controls
224 lines (203 loc) · 6.17 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
"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 { useEmbedContext } from "../embedContext";
import { RuntimeContext } from "../runtime";
const RubyContext = createContext<RuntimeContext>(null!);
export function useRuby(): RuntimeContext {
const context = useContext(RubyContext);
if (!context) {
throw new Error("useRuby must be used within a RubyProvider");
}
return context;
}
type MessageToWorker =
| {
type: "init";
payload: { RUBY_WASM_URL: string };
}
| {
type: "runRuby";
payload: { code: string };
}
| {
type: "checkSyntax";
payload: { code: string };
}
| {
type: "runFile";
payload: { name: string; files: Record<string, 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 RubyProvider({ children }: { children: ReactNode }) {
const workerRef = useRef<Worker | null>(null);
const [ready, setReady] = useState<boolean>(false);
const mutex = useRef<MutexInterface>(new Mutex());
const { files, writeFile } = useEmbedContext();
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);
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 });
});
}
useEffect(() => {
const worker = new Worker("/ruby.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);
}
};
// Use CDN URL for Ruby WASM with stdlib
const RUBY_WASM_URL =
"https://cdn.jsdelivr.net/npm/@ruby/3.3-wasm-wasi@2.7.2/dist/ruby+stdlib.wasm";
postMessage<InitPayloadFromWorker>({
type: "init",
payload: { RUBY_WASM_URL },
}).then(({ success }) => {
if (success) {
setReady(true);
}
});
return () => {
workerRef.current?.terminate();
};
}, []);
const interrupt = useCallback(() => {
// TODO: Implement interrupt functionality for Ruby
// Ruby WASM doesn't currently support interrupts like Pyodide does
console.warn("Ruby interrupt is not yet implemented");
}, []);
const runCommand = useCallback(
async (code: string): Promise<ReplOutput[]> => {
if (!mutex.current.isLocked()) {
throw new Error("mutex of RubyContext must be locked for runCommand");
}
if (!workerRef.current || !ready) {
return [{ type: "error", message: "Ruby VM is not ready yet." }];
}
const { output, updatedFiles } = await postMessage<RunPayloadFromWorker>({
type: "runRuby",
payload: { code },
});
for (const [name, content] of updatedFiles) {
writeFile(name, content);
}
return output;
},
[ready, writeFile]
);
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(
async (filenames: string[]): Promise<ReplOutput[]> => {
if (filenames.length !== 1) {
return [
{
type: "error",
message: "Ruby execution requires exactly one filename",
},
];
}
if (!workerRef.current || !ready) {
return [{ type: "error", message: "Ruby VM is not ready yet." }];
}
return mutex.current.runExclusive(async () => {
const { output, updatedFiles } =
await postMessage<RunPayloadFromWorker>({
type: "runFile",
payload: { name: filenames[0], files },
});
for (const [newName, content] of updatedFiles) {
writeFile(newName, content);
}
return output;
});
},
[files, ready, writeFile]
);
const splitReplExamples = useCallback((content: string): ReplCommand[] => {
const initCommands: { command: string; output: ReplOutput[] }[] = [];
for (const line of content.split("\n")) {
if (line.startsWith(">> ")) {
// Ruby IRB uses >> as the prompt
initCommands.push({ command: line.slice(3), output: [] });
} else if (line.startsWith("?> ")) {
// Ruby IRB uses ?> for continuation
if (initCommands.length > 0) {
initCommands[initCommands.length - 1].command += "\n" + line.slice(3);
}
} 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[]) => `ruby ${filenames[0]}`,
[]
);
return (
<RubyContext.Provider
value={{
ready,
runCommand,
checkSyntax,
mutex: mutex.current,
runFiles,
interrupt,
splitReplExamples,
getCommandlineStr,
}}
>
{children}
</RubyContext.Provider>
);
}