enh: pyodide

This commit is contained in:
Timothy Jaeryang Baek 2025-02-02 21:18:52 -08:00
parent eb1ede119e
commit 0d33725d21
2 changed files with 46 additions and 6 deletions

View File

@ -396,7 +396,7 @@ __builtins__.input = input`);
{#if result}
<div class=" ">
<div class=" text-gray-500 text-xs mb-1">RESULT</div>
<div class="text-sm">{`${result}`}</div>
<div class="text-sm">{`${JSON.stringify(result)}`}</div>
</div>
{/if}
{/if}

View File

@ -62,11 +62,10 @@ self.onmessage = async (event) => {
try {
self.result = await self.pyodide.runPythonAsync(code);
try {
self.result = self.result.toJSON();
} catch (error) {
console.error(error);
}
// Safely process and recursively serialize the result
self.result = processResult(self.result);
console.log('Python result:', self.result);
} catch (error) {
self.stderr = error.toString();
}
@ -74,4 +73,45 @@ self.onmessage = async (event) => {
self.postMessage({ id, result: self.result, stdout: self.stdout, stderr: self.stderr });
};
function processResult(result: any): any {
// Handle null and undefined
if (result == null) {
return result;
}
// Handle primitive types
if (typeof result !== 'object') {
return result;
}
// Handle Date objects
if (result instanceof Date) {
return result.toISOString();
}
// Handle Arrays
if (Array.isArray(result)) {
return result.map((item) => processResult(item));
}
// Handle Proxy objects (assuming they're from Pyodide)
if (typeof result.toJs === 'function') {
return processResult(result.toJs());
}
// Handle regular objects
if (typeof result === 'object') {
const processedObject: { [key: string]: any } = {};
for (const key in result) {
if (Object.prototype.hasOwnProperty.call(result, key)) {
processedObject[key] = processResult(result[key]);
}
}
return processedObject;
}
// If we can't process it, return null or a placeholder
return null;
}
export default {};