import ServeRouter from "https://esm.sh/serve-router@latest";
const app = ServeRouter();
const USERNAME = "yieldray";
const gistList: Array<Gist> = await fetch(`https://api.github.com/users/${USERNAME}/gists`).then((res) => res.json());
app.get("/", (req) => {
return Response.json(
gistList.map((gist) => ({
id: gist.id,
description: gist.description,
url: new URL(`/${gist.id}`, req.url).toString(),
html_url: gist.html_url,
})),
);
});
app.get<{
id: string;
}>("/:id", (req, { params: { id } }) => {
const gist = gistList.find((gist) => gist.id === id) ?? gistList.find((gist) => gist.description === id);
if (!gist) return new Response("404 Gist Not Found", { status: 404 });
return Response.json(
Object.fromEntries(
Object.entries(gist.files).map(([fileName, file]) => [
fileName,
{
...file,
url: new URL(`/${gist.id}/${fileName}`, req.url).toString(),
},
]),
),
);
});
app.get<{
id: string;
file: string;
}>("/:id/:file", async (_req, { params: { id, file } }) => {
const gist = gistList.find((gist) => gist.id === id) ?? gistList.find((gist) => gist.description === id);
if (!gist) return new Response("404 Gist Not Found", { status: 404 });
const f = gist.files[file];
if (!f) return new Response("404 File Not Found", { status: 404 });
const res = await fetch(f.raw_url);
const headers = new Headers(res.headers);
headers.delete("content-security-policy");
headers.delete("cross-origin-resource-policy");
for (const key of headers.keys()) {
if (key.startsWith("x-")) headers.delete(key);
}
if ([".ts", ".sh", ".cmd", ".bat", ".ps1"].some((end) => file.endsWith(end))) {
headers.set("Content-Type", "text/plain;charset=UTF-8");
} else {
headers.set("Content-Type", f.type);
}
return new Response(res.body, {
...res,
headers,
});
});
const handler = app.fetch
export default handler
interface Gist {
url: string;
forks_url: string;
commits_url: string;
id: string;
node_id: string;
git_pull_url: string;
git_push_url: string;
html_url: string;
files: Record<
string,
{
filename: string;
type: string;
language: string;
raw_url: string;
size: number;
}
>;
public: boolean;
created_at: Date;
updated_at: Date;
description: string;
comments: number;
user: null;
comments_url: string;
owner: null;
truncated: boolean;
}