const { defineConfig } = require("vite");
const { svelte } = require("@sveltejs/vite-plugin-svelte");
const zlib = require("zlib");

// https://vitejs.dev/config/
module.exports = defineConfig({
   optimizeDeps: {
      exclude: ["@roxi/routify"],
   },
   server: {
      proxy: {
         "/peerjs": {
            target: "http://localhost:5000/",
            changeOrigin: true,
            ws: true,
            rewrite: (path) => path.replace(/^\/peerjs/, ""),
         },
         "*": "/index.html",
      },
   },
   plugins: [svelte()],
   build: {
      sourcemap: false,
      rollupOptions: {
         plugins: [
            {
               name: "pregzip-files",
               generateBundle: async function (options, bundle) {
                  let prms = [];
                  for (const fileName in bundle) {
                     const file = bundle[fileName];
                     // if (fileName.startsWith("assets/")) {
                     let src;
                     if (file.type === "asset") {
                        src = file.source;
                     } else {
                        src = file.code;
                     }
                     // console.log("Compressing asset:", typeof file.source == "undefined" ? file : undefined)

                     prms.push(
                        new Promise((yes, no) =>
                           zlib.gzip(
                              src,
                              {
                                 level: 6,
                              },
                              (err, res) => (err ? no(err) : yes(res))
                           )
                        ).then((gzip) => {
                           this.emitFile({
                              type: "asset",
                              name: file.name + ".gz",
                              fileName: file.fileName + ".gz",
                              source: gzip,
                           });
                        }),
                        new Promise((yes, no) =>
                           zlib.brotliCompress(src, (err, res) =>
                              err ? no(err) : yes(res)
                           )
                        ).then((br) => {
                           this.emitFile({
                              type: "asset",
                              name: file.name + ".br",
                              fileName: file.fileName + ".br",
                              source: br,
                           });
                        })
                     );
                     // }
                  }

                  await Promise.all(prms);
               },
            },
         ],
      },
   },
});
