File size: 1,367 Bytes
022cb3a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import { createReadStream, cpSync, mkdirSync, readdirSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
// Keep the compiler's relative WASM/sysroot URLs intact. These large assets
// are served locally and only fetched when the user first compiles a program.
export function trainingCompilerPlugin() {
const source = dirname(fileURLToPath(import.meta.resolve("@yowasp/clang")));
const files = new Set(readdirSync(source));
let outDir;
return {
name: "training-compiler",
configResolved(config) { outDir = resolve(config.root, config.build.outDir); },
configureServer(server) {
server.middlewares.use("/training-compiler", (req, res, next) => {
const name = req.url.split("?")[0].slice(1);
if (!files.has(name)) return next();
const path = join(source, name);
res.setHeader("Content-Type", name.endsWith(".js") ? "text/javascript" : name.endsWith(".wasm") ? "application/wasm" : "application/octet-stream");
res.setHeader("Content-Length", statSync(path).size);
createReadStream(path).on("error", next).pipe(res);
});
},
closeBundle() {
mkdirSync(join(outDir, "training-compiler"), { recursive: true });
cpSync(source, join(outDir, "training-compiler"), { recursive: true });
},
};
}
|