vite.config.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. // Everything in outDir is embedded into the Go binary via embed.FS, so
  160. // production sourcemaps (~18MB across 112 files, 72% of dist) ship inside
  161. // every release build. Nothing consumes them there; `npm run dev` serves
  162. // its own maps regardless of this setting. To debug a minified bundle
  163. // (including the XUI_DEBUG serve-from-disk path), build once with
  164. // XUI_SOURCEMAP=true — no tracked-file edit to accidentally commit.
  165. sourcemap: process.env.XUI_SOURCEMAP === 'true',
  166. target: 'es2020',
  167. chunkSizeWarningLimit: 1500,
  168. rollupOptions: {
  169. input: {
  170. index: path.resolve(__dirname, 'index.html'),
  171. login: path.resolve(__dirname, 'login.html'),
  172. subpage: path.resolve(__dirname, 'subpage.html'),
  173. },
  174. output: {
  175. manualChunks(id) {
  176. if (!id.includes('node_modules')) return undefined;
  177. if (id.includes('/node_modules/antd/')) return 'vendor-antd';
  178. if (id.includes('/@ant-design/icons/') || id.includes('/@ant-design/icons-svg/')) return 'vendor-icons';
  179. if (
  180. id.includes('/node_modules/@rc-component/')
  181. || id.includes('/node_modules/rc-')
  182. || id.includes('/@ant-design/cssinjs')
  183. || id.includes('/@ant-design/colors')
  184. || id.includes('/@ant-design/fast-color')
  185. || id.includes('/@ant-design/react-slick')
  186. || id.includes('/@ctrl/tinycolor')
  187. ) return 'vendor-antd';
  188. if (
  189. id.includes('/node_modules/react-i18next/')
  190. || id.includes('/node_modules/i18next/')
  191. ) return 'vendor-i18next';
  192. if (
  193. id.includes('/node_modules/react/')
  194. || id.includes('/node_modules/react-dom/')
  195. || id.includes('/node_modules/scheduler/')
  196. ) return 'vendor-react';
  197. if (
  198. id.includes('/node_modules/codemirror/')
  199. || id.includes('/node_modules/@codemirror/')
  200. || id.includes('/node_modules/@lezer/')
  201. ) return 'vendor-codemirror';
  202. if (id.includes('/node_modules/persian-calendar-suite/')) return 'vendor-jalali';
  203. if (id.includes('/node_modules/otpauth/')) return 'vendor-otpauth';
  204. if (id.includes('/node_modules/@tanstack/')) return 'vendor-tanstack';
  205. if (id.includes('/node_modules/react-router')) return 'vendor-router';
  206. if (
  207. id.includes('/node_modules/swagger-ui-react/')
  208. || id.includes('/node_modules/swagger-ui/')
  209. || id.includes('/node_modules/swagger-client/')
  210. ) return 'vendor-swagger';
  211. if (id.includes('/node_modules/uplot/')) return 'vendor-uplot';
  212. if (id.includes('dayjs')) return 'vendor-dayjs';
  213. return 'vendor';
  214. },
  215. },
  216. },
  217. },
  218. server: {
  219. port: 5173,
  220. strictPort: true,
  221. proxy: {
  222. '^/(?:[^/]+/)?(login|logout|getTwoFactorEnable|csrf-token|panel|server)(?:/|$)': makeBackendProxy(BACKEND_TARGET),
  223. '^/$': makeBackendProxy(BACKEND_TARGET),
  224. '^/[^/]+/$': makeBackendProxy(BACKEND_TARGET),
  225. '^/(?:[^/]+/)?ws$': {
  226. target: 'ws://localhost:2053',
  227. ws: true,
  228. changeOrigin: true,
  229. rewrite: rewriteToBackend,
  230. },
  231. },
  232. },
  233. });