export default async function main(req: Request): Promise<Response> {
const url = new URL(req.url);
const valName = url.searchParams.get("val");
if (!valName) {
return new Response("Val name not provided", { status: 400 });
}
try {
const module = await import(`https://esm.town/v/${valName}`);
const valFunction = module.default;
if (typeof valFunction !== "function") {
throw new Error("Imported val is not a function");
}
const response = await valFunction(req);
const originalHtml = await response.text();
if (!originalHtml.trim() || originalHtml.length < 50 || !/<html/i.test(originalHtml)) {
return createErrorResponse("Val returned invalid or empty response");
}
const modifiedHtml = injectErrorHandlingScript(originalHtml);
return new Response(modifiedHtml, {
headers: { "Content-Type": "text/html" },
});
} catch (error) {
return createErrorResponse(error instanceof Error ? error.message : String(error));
}
}
function injectErrorHandlingScript(html: string): string {
const script = `
<script>
window.onerror = function(message, source, lineno, colno, error) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "window.onerror: " + message }, "*");
};
window.addEventListener('unhandledrejection', function(event) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "unhandledrejection: " + event.reason }, "*");
});
console.error = function(...args) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "console.error: " + args.join(' ') }, "*");
};
window.addEventListener('load', function() {
setTimeout(function() {
window.parent.postMessage({ messageType: "success" }, "*");
}, 3000);
});
</script>
`;
return script + html;
}
function createErrorResponse(errorString: string): Response {
const errorHtml = `
<html>
<head>
<script>
window.parent.postMessage({ messageType: "valCallError", errorString: ${JSON.stringify(errorString)} }, "*");
</script>
</head>
<body></body>
</html>
`;
return new Response(errorHtml, {
headers: { "Content-Type": "text/html" },
});
}