Last active
June 10, 2022 23:20
-
-
Save piscisaureus/9957d25b865d2449446eb9bd6aeecd5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const resources = { | |
"/": file("text/html")` | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<script type="module" src="main.js"></script> | |
</head> | |
<body> | |
<p>Open developer tools. There will be nothing to see here.</p> | |
</body> | |
</html>`, | |
"/main.js": file("text/javascript")` | |
import { throwAnError } from "./imports/as-specified.js"; | |
try { | |
throwAnError(); | |
} catch (error) { | |
console.log("Caught:", error); | |
}`, | |
"/imports/actual-module.js": file("text/javascript")` | |
console.log("Hello from the imported module. My import.meta.url is '" + | |
import.meta.url + "'"); | |
export function throwAnError() { | |
throw new Error("throw from actual-module.js"); | |
}`, | |
"/imports/as-specified.js": redir("intermediate-redirect.js", 307), | |
"/imports/intermediate-redirect.js": redir("actual-module.js", 302), | |
"/favicon.ico": file("image/svg+xml")` | |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> | |
<text y=".9em" font-size="90">🦕</text> | |
</svg>`, | |
}; | |
function file(contentType) { | |
return function template(tpl, ...ins) { | |
let lines = tpl.raw | |
.map((s, i) => `${s}${i in ins ? ins[i] : ""}`) | |
.join("") | |
.split(/\r?\n/); | |
lines.length > 1 && lines[0] === "" && lines.shift(); | |
const undent = /^\s*/.exec(lines[0])[0]; | |
const text = lines | |
.map((l) => (l.startsWith(undent) ? l.slice(undent.length) : l)) | |
.join("\n"); | |
const body = new TextEncoder().encode(text); | |
const headers = { | |
"Content-Type": contentType, | |
"Content-Length": body.length, | |
}; | |
return function respond() { | |
return new Response(body, { headers }); | |
}; | |
}; | |
} | |
function redir(toUrl, status = 302) { | |
return function respond(fromUrl) { | |
let url = new URL(toUrl, fromUrl).toString(); | |
return Response.redirect(url, status); | |
}; | |
} | |
addEventListener("fetch", (event) => { | |
const { | |
request: { url }, | |
} = event; | |
const { pathname } = new URL(url); | |
const response = resources[pathname](url) || Response.error(); | |
event.respondWith(response); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment