import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import * as zlib from "zlib";

// https://vitejs.dev/config/
export default 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: Promise<any>[] = [];
                  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<any>((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 as Uint8Array,
                           });
                        })
                     );
                     // }
                  }

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