d2/d2js/js/dev-server.js

73 lines
2 KiB
JavaScript
Raw Normal View History

2025-01-15 18:37:04 +00:00
const fs = require("fs/promises");
const path = require("path");
2025-01-12 14:41:58 +00:00
const MIME_TYPES = {
".html": "text/html",
".js": "text/javascript",
".mjs": "text/javascript",
".css": "text/css",
".wasm": "application/wasm",
".svg": "image/svg+xml",
};
const server = Bun.serve({
port: 3000,
async fetch(request) {
const url = new URL(request.url);
2025-01-15 18:37:04 +00:00
let filePath = url.pathname.slice(1); // Remove leading "/"
2025-01-12 14:41:58 +00:00
2025-01-15 18:37:04 +00:00
if (filePath === "") {
filePath = "examples/";
2025-01-12 14:41:58 +00:00
}
try {
2025-01-15 18:37:04 +00:00
const fullPath = path.join(process.cwd(), filePath);
const stats = await fs.stat(fullPath);
2025-01-12 14:41:58 +00:00
2025-01-15 18:37:04 +00:00
if (stats.isDirectory()) {
const entries = await fs.readdir(fullPath);
const links = await Promise.all(
entries.map(async (entry) => {
const entryPath = path.join(fullPath, entry);
const isDir = (await fs.stat(entryPath)).isDirectory();
const slash = isDir ? "/" : "";
return `<li><a href="${filePath}${entry}${slash}">${entry}${slash}</a></li>`;
})
);
const html = `
<html>
<body>
<h1>Examples</h1>
<ul>
${links.join("")}
</ul>
</body>
</html>
`;
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
} else {
const ext = path.extname(filePath);
const mimeType = MIME_TYPES[ext] || "application/octet-stream";
2025-01-12 14:41:58 +00:00
2025-01-15 18:37:04 +00:00
const file = Bun.file(filePath);
return new Response(file, {
headers: {
"Content-Type": mimeType,
"Access-Control-Allow-Origin": "*",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
},
});
}
2025-01-12 14:41:58 +00:00
} catch (err) {
2025-01-15 18:37:04 +00:00
console.error(`Error serving ${filePath}:`, err);
return new Response(`File not found: ${filePath}`, { status: 404 });
2025-01-12 14:41:58 +00:00
}
},
});
console.log(`Server running at http://localhost:3000`);