vite.config.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { defineConfig } from 'vite';
  2. import react from '@vitejs/plugin-react';
  3. import fs from 'node:fs';
  4. import path from 'node:path';
  5. import { DatabaseSync } from 'node:sqlite';
  6. const outDir = path.resolve(__dirname, '../internal/web/dist');
  7. const BACKEND_TARGET = 'http://localhost:2053';
  8. function resolveDBPath() {
  9. const envFolder = process.env.XUI_DB_FOLDER;
  10. if (envFolder) {
  11. const abs = path.isAbsolute(envFolder)
  12. ? envFolder
  13. : path.resolve(__dirname, '..', envFolder);
  14. return path.join(abs, 'x-ui.db');
  15. }
  16. const repoSubDB = path.resolve(__dirname, '..', 'x-ui', 'x-ui.db');
  17. if (fs.existsSync(repoSubDB)) return repoSubDB;
  18. const repoDB = path.resolve(__dirname, '..', 'x-ui.db');
  19. if (fs.existsSync(repoDB)) return repoDB;
  20. return '/etc/x-ui/x-ui.db';
  21. }
  22. const PANEL_API_PREFIXES = ['panel/api/', 'panel/csrf-token'];
  23. let cachedBasePath = '/';
  24. function readBasePathFromDB() {
  25. const dbPath = resolveDBPath();
  26. let db;
  27. try {
  28. db = new DatabaseSync(dbPath, { readOnly: true });
  29. } catch (_e) {
  30. return '/';
  31. }
  32. try {
  33. const row = db.prepare('SELECT value FROM settings WHERE key = ?').get('webBasePath');
  34. let value = row && typeof row.value === 'string' ? row.value : '/';
  35. if (!value.startsWith('/')) value = '/' + value;
  36. if (!value.endsWith('/')) value += '/';
  37. return value;
  38. } catch (_e) {
  39. return '/';
  40. } finally {
  41. db.close();
  42. }
  43. }
  44. function refreshBasePath() {
  45. cachedBasePath = readBasePathFromDB();
  46. return cachedBasePath;
  47. }
  48. function readPanelVersion() {
  49. try {
  50. const versionFile = path.resolve(__dirname, '..', 'config', 'version');
  51. return fs.readFileSync(versionFile, 'utf8').trim();
  52. } catch (_e) {
  53. return '';
  54. }
  55. }
  56. // `apply: 'serve'` keeps the injection out of `vite build` — dist.go
  57. // already injects webBasePath and version at runtime in production.
  58. function injectBasePathPlugin() {
  59. return {
  60. name: 'xui-inject-base-path',
  61. apply: 'serve',
  62. transformIndexHtml(html) {
  63. const basePath = refreshBasePath();
  64. const escaped = basePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  65. const version = readPanelVersion().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  66. const tag = `<script>window.X_UI_BASE_PATH="${escaped}";window.X_UI_CUR_VER="${version}";</script>`;
  67. return html.replace('</head>', `${tag}</head>`);
  68. },
  69. };
  70. }
  71. // Cloudflare Rocket Loader rewrites script tags and runs bundles through its
  72. // own loader, breaking ES-module semantics; data-cfasync="false" opts out.
  73. function rocketLoaderOptOutPlugin() {
  74. return {
  75. name: 'xui-rocket-loader-opt-out',
  76. apply: 'build',
  77. transformIndexHtml(html) {
  78. return html.replaceAll('<script ', '<script data-cfasync="false" ');
  79. },
  80. };
  81. }
  82. function bypassMigratedRoute(req) {
  83. if (req.method !== 'GET') return undefined;
  84. const url = req.url.split('?')[0];
  85. const basePath = refreshBasePath();
  86. if (url === basePath) return '/login.html';
  87. if (url.startsWith(basePath)) {
  88. const stripped = url.slice(basePath.length);
  89. for (const prefix of PANEL_API_PREFIXES) {
  90. if (prefix.endsWith('/')) {
  91. if (stripped.startsWith(prefix)) return undefined;
  92. } else if (stripped === prefix || stripped.startsWith(prefix + '/')) {
  93. return undefined;
  94. }
  95. }
  96. if (stripped === 'panel' || stripped === 'panel/' || stripped.startsWith('panel/')) {
  97. return '/index.html';
  98. }
  99. }
  100. return undefined;
  101. }
  102. function rewriteToBackend(p) {
  103. if (cachedBasePath === '/' || p.startsWith(cachedBasePath)) return p;
  104. return cachedBasePath + p.replace(/^\//, '');
  105. }
  106. function makeBackendProxy(target) {
  107. return {
  108. target,
  109. changeOrigin: true,
  110. rewrite: rewriteToBackend,
  111. bypass: bypassMigratedRoute,
  112. configure(proxy) {
  113. let warned = false;
  114. proxy.on('error', (err, req) => {
  115. const codes = new Set();
  116. if (err && err.code) codes.add(err.code);
  117. if (err && Array.isArray(err.errors)) {
  118. for (const inner of err.errors) {
  119. if (inner && inner.code) codes.add(inner.code);
  120. }
  121. }
  122. const offline = codes.has('ECONNREFUSED') || codes.has('ECONNRESET');
  123. if (offline) {
  124. if (!warned) {
  125. warned = true;
  126. // eslint-disable-next-line no-console
  127. console.warn(
  128. `[proxy] backend ${target} is not reachable — start the Go server (e.g. \`go run main.go\`) to forward ${req?.url || 'requests'}.`,
  129. );
  130. }
  131. return;
  132. }
  133. // eslint-disable-next-line no-console
  134. console.error('[proxy]', err);
  135. });
  136. },
  137. };
  138. }
  139. export default defineConfig({
  140. plugins: [react(), injectBasePathPlugin(), rocketLoaderOptOutPlugin()],
  141. resolve: {
  142. alias: {
  143. '@': path.resolve(__dirname, 'src'),
  144. },
  145. },
  146. experimental: {
  147. renderBuiltUrl(filename, { hostType }) {
  148. if (hostType === 'js') {
  149. return {
  150. runtime: `((window.X_UI_BASE_PATH||'/')+${JSON.stringify(filename)})`,
  151. };
  152. }
  153. return undefined;
  154. },
  155. },
  156. build: {
  157. outDir,
  158. emptyOutDir: true,
  159. sourcemap: true,
  160. target: 'es2020',
  161. chunkSizeWarningLimit: 1500,
  162. rollupOptions: {
  163. input: {
  164. index: path.resolve(__dirname, 'index.html'),
  165. login: path.resolve(__dirname, 'login.html'),
  166. subpage: path.resolve(__dirname, 'subpage.html'),
  167. },
  168. output: {
  169. manualChunks(id) {
  170. if (!id.includes('node_modules')) return undefined;
  171. if (id.includes('/node_modules/antd/')) return 'vendor-antd';
  172. if (id.includes('/@ant-design/icons/') || id.includes('/@ant-design/icons-svg/')) return 'vendor-icons';
  173. if (
  174. id.includes('/node_modules/@rc-component/')
  175. || id.includes('/node_modules/rc-')
  176. || id.includes('/@ant-design/cssinjs')
  177. || id.includes('/@ant-design/colors')
  178. || id.includes('/@ant-design/fast-color')
  179. || id.includes('/@ant-design/react-slick')
  180. || id.includes('/@ctrl/tinycolor')
  181. ) return 'vendor-antd';
  182. if (
  183. id.includes('/node_modules/react-i18next/')
  184. || id.includes('/node_modules/i18next/')
  185. ) return 'vendor-i18next';
  186. if (
  187. id.includes('/node_modules/react/')
  188. || id.includes('/node_modules/react-dom/')
  189. || id.includes('/node_modules/scheduler/')
  190. ) return 'vendor-react';
  191. if (
  192. id.includes('/node_modules/codemirror/')
  193. || id.includes('/node_modules/@codemirror/')
  194. || id.includes('/node_modules/@lezer/')
  195. ) return 'vendor-codemirror';
  196. if (id.includes('/node_modules/persian-calendar-suite/')) return 'vendor-jalali';
  197. if (id.includes('/node_modules/otpauth/')) return 'vendor-otpauth';
  198. if (id.includes('/node_modules/@tanstack/')) return 'vendor-tanstack';
  199. if (id.includes('/node_modules/react-router')) return 'vendor-router';
  200. if (
  201. id.includes('/node_modules/swagger-ui-react/')
  202. || id.includes('/node_modules/swagger-ui/')
  203. || id.includes('/node_modules/swagger-client/')
  204. ) return 'vendor-swagger';
  205. if (id.includes('/node_modules/uplot/')) return 'vendor-uplot';
  206. if (id.includes('dayjs')) return 'vendor-dayjs';
  207. return 'vendor';
  208. },
  209. },
  210. },
  211. },
  212. server: {
  213. port: 5173,
  214. strictPort: true,
  215. proxy: {
  216. '^/(?:[^/]+/)?(login|logout|getTwoFactorEnable|csrf-token|panel|server)(?:/|$)': makeBackendProxy(BACKEND_TARGET),
  217. '^/$': makeBackendProxy(BACKEND_TARGET),
  218. '^/[^/]+/$': makeBackendProxy(BACKEND_TARGET),
  219. '^/(?:[^/]+/)?ws$': {
  220. target: 'ws://localhost:2053',
  221. ws: true,
  222. changeOrigin: true,
  223. rewrite: rewriteToBackend,
  224. },
  225. },
  226. },
  227. });