2024-02-17 14:56:17 +01:00
|
|
|
let outputIndex = 0;
|
|
|
|
|
|
|
|
let debugLog = console.log;
|
|
|
|
|
|
|
|
globalThis.console = {
|
2024-02-16 22:01:19 +01:00
|
|
|
log(...message) {
|
|
|
|
postMessage({
|
|
|
|
kind: "output",
|
|
|
|
output: {
|
|
|
|
kind: "log",
|
|
|
|
message: [...message],
|
2024-02-17 14:56:17 +01:00
|
|
|
},
|
|
|
|
outputIndex,
|
2024-02-16 22:01:19 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-02-17 14:56:17 +01:00
|
|
|
async function withTemporaryGlobalScope(callback) {
|
|
|
|
let state = {
|
|
|
|
oldValues: {},
|
|
|
|
set(key, value) {
|
|
|
|
this.oldValues[key] = globalThis[key];
|
|
|
|
globalThis[key] = value;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
await callback(state);
|
|
|
|
for (let key in state.oldValues) {
|
|
|
|
globalThis[key] = state.oldValues[key];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
addEventListener("message", async event => {
|
2024-02-16 22:01:19 +01:00
|
|
|
let message = event.data;
|
|
|
|
if (message.action == "eval") {
|
2024-02-17 14:56:17 +01:00
|
|
|
outputIndex = 0;
|
2024-02-16 22:01:19 +01:00
|
|
|
try {
|
2024-02-17 14:56:17 +01:00
|
|
|
await withTemporaryGlobalScope(async scope => {
|
|
|
|
for (let command of message.input) {
|
|
|
|
if (command.kind == "module") {
|
|
|
|
let blobUrl = URL.createObjectURL(new Blob([command.source], { type: "text/javascript" }));
|
|
|
|
let module = await import(blobUrl);
|
|
|
|
for (let exportedKey in module) {
|
|
|
|
scope.set(exportedKey, module[exportedKey]);
|
|
|
|
}
|
|
|
|
} else if (command.kind == "output") {
|
|
|
|
++outputIndex;
|
|
|
|
}
|
2024-02-16 22:01:19 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
postMessage({
|
|
|
|
kind: "output",
|
|
|
|
output: {
|
|
|
|
kind: "error",
|
|
|
|
message: [error.toString()],
|
2024-02-17 14:56:17 +01:00
|
|
|
},
|
|
|
|
outputIndex,
|
2024-02-16 22:01:19 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
postMessage({
|
|
|
|
kind: "evalComplete",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|