const { resolve } = require("path");
import fs from "fs";
import { defineConfig, loadEnv } from "vite";
import { createVuePlugin } from "vite-plugin-vue2";
import vueJsx from "@vitejs/plugin-vue-jsx";
import pageData from "vite-plugin-pagedata";
import vitefunc from "./vite-plugin/vite-plugin-func";
import autoPausePlugin from "./vite-plugin/vite-plugin-auto-pause";
import { injectHtml } from "vite-plugin-html";

const pkg = require("./package.json");

// let dependencies = [];
// for(let key in pkg.dependencies){
//     if(['font-awesome'].indexOf(key)==-1)
//     dependencies.push(key)
// }
// console.log('------dependencies------',dependencies)


const projectName = pkg.name == "hi-vui-template" ? "project" : pkg.name;

// https://vitejs.dev/config/
export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
  let aliases = {};
  let build = {
    sourcemap: false,
    //编译
    //指定 多个 .html 文件作为入口点
    rollupOptions: {
      // 请确保外部化那些你的库中不需要的依赖
      // external: ['vue'],
      input: {
        main: resolve(__dirname, "index.html"),
        nested: resolve(__dirname, "nested/index.html"),
      },
      output: {
        format: "umd",
      },
    },
  };
  if (mode == "development") {
    aliases = {
      "@project": resolve(`${projectName}`),
      "@main": resolve(`${projectName}/hivuiMain`),
      "@birt": resolve(`${projectName}/hivuiBirt`),
      "@sam": resolve(`${projectName}/hivuiSam`),
      pinyin: "js-pinyin",
      //预览使用全局的vue
      vue: resolve(__dirname, `./build/vite_preview/vue.js`),
      //预览引用指定目录下的element
      //开启本地调试时，禁用掉下面这行
      "element-ui": resolve(__dirname, `./build/vite_preview/element_ui.js`),
      //开启本地调试时，启用scp5.0本地调式指定
      //'@':resolve(__dirname, './hi-ui/src'),
    };
  }
  const postDataName = "scpRequestData";
  return defineConfig({
    root:resolve(__dirname),
    // 被监听的包必须被排除在优化之外，
    // 预览时,预编译这些包,以防vite 启动后,浏览器通过自动模块加载导致刷新页面
    optimizeDeps: {
      //预编译加载这些，提升速度
      include: [
        "axios",
        "babel-polyfill",
        "classnames",
        "echarts",
        "enquire.js",
        "js-cookie",
        "js-md5",
        "js-pinyin",
        "lodash",
        "lodash/findIndex",
        "lodash/cloneDeep",
        "lodash/isPlainObject",
        "lodash/defaultsDeep",
        "lodash/bind",
        "screenfull",
        "sortablejs",
        "vue",
        "vue-draggable-resizable",
        "vue-gemini-scrollbar",
        "vue-jstree",
        //以下第一次预览时启动不了
        // 'hi-ui','hi-taskcenter','zhc-flowchart','zhc-birt-cmps
      ],
      // 排除
      // exclude: []
    },
    build: build,
    define: {
      "process.env": {
        /**
                 * 启用时在入口页中，有一段以下代码，因为ELEMENT有全局、import、两次，所以在调试hiui时，在初始化一次才行
                    if(process.env.hiui_debug){
                        //这样多次引用element
                        //hiui调试时用
                        Vue.use(ELEMENT)
                    }
                 *
                 */
        //开启本地调试时，启用
        hiui_debug: false,
        //配合 webpack 环境，在vite 下定义一个空的
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    resolve: {
      extensions: [
        ".mjs",
        ".js",
        ".ts",
        ".jsx",
        ".tsx",
        ".json",
        ".vue",
        ".dtvevt",
        ".dtv",
        ".dvue",
        ".es6",
      ],
      alias: aliases,
    },
    plugins: [
      /*
                通过 URL @fs/ftp/a.txt?import&raw?? 访问服务器文件的行为，通常意味着访问了不应公开的目录或文件。为了阻止这种情况，我们需要确保以下几方面的安全性：
                限制文件访问路径
                禁止特定的 URL 查询参数
                加强 Vite 配置的文件系统安全性
            */
      {
        name: "restrict-query-params",
        configureServer(server) {
          server.middlewares.use((req, res, next) => {
            const url = req.url;
            //攻击读取文件 ftp/a.txt   http://192.168.18.161:3000/@fs/ftp/a.txt?import&raw??
             const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
             if (url && SPECIAL_QUERY_RE.test(url)) {
               res.statusCode = 403;
               res.end("Forbidden");
               return;
             }
             next();
 
          });
        },
      },
      pkg.preview && pkg.preview.autoStopTime > 0 ? autoPausePlugin() : null,
      vitefunc({
        varName: postDataName,
        global: {
          env: "dev",
        },
        htmlWebpackPlugin: {
          vite: true,
          project: projectName,
          mode: mode,
        },
      }),
      injectHtml({
        // 向预览时注入变量，这个变量跟打包时 html-webpack-plugin 注入的一致，用户判断是否是编译状态
        injectData: {
          htmlWebpackPlugin: {
            vite: true,
            project: projectName,
            mode: mode,
          },
        },
      }),
      pageData({
        varName: postDataName,
        global: {
          env: "dev",
        },
      }),
      createVuePlugin({
        include: /\.(dvue|vue)$/,
      }),
      vueJsx({
        // options are passed on to @vue/babel-plugin-jsx
      }),
      //影响到eap.umd.min.js 里的require ELEMENT 全局
      // requireTransform({
      //     fileRegex:/.ts$|.tsx$|.vue$|.js$|.jsx$/
      // })
    ],
    server: {
      fs: {
        strict: true, //限制为工作区 root 路径以外的文件的访问
        allow: [
          resolve(__dirname, "."), // 允许为项目想目录的上一级提供服务
        ],
      },
      hmr: {
        overlay: false, //不遮罩输出错误信息，但输出控制台
      },
    },
  });
};
