forked from lobehub/lobehub
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
374 lines (344 loc) · 12.9 KB
/
Copy pathvite.config.ts
File metadata and controls
374 lines (344 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { DevTools } from '@vitejs/devtools';
import type { PluginOption, ViteDevServer } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import { viteEnvRestartKeys } from './plugins/vite/envRestartKeys';
import {
createSharedRolldownOutput,
sharedModulePreload,
sharedOptimizeDeps,
sharedPwaGlobIgnores,
sharedPwaRuntimeCaching,
sharedRendererDefine,
sharedRendererPlugins,
} from './plugins/vite/sharedRendererConfig';
import { vercelSkewProtection } from './plugins/vite/vercelSkewProtection';
import { createViteWatchOptions } from './plugins/vite/watchOptions';
const isMobile = process.env.MOBILE === 'true';
const isAuth = process.env.AUTH === 'true';
const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
Object.assign(process.env, loadEnv(mode, process.cwd(), ''));
const isDev = process.env.NODE_ENV !== 'production';
const platform = isAuth ? 'auth' : isMobile ? 'mobile' : 'web';
const enableViteDevTools = process.env.LOBE_VITE_DEVTOOLS === 'true';
const resolveCommandExecutable = (cmd: string) => {
const pathValue = process.env.PATH;
if (!pathValue) return;
if (process.platform === 'win32') {
const pathExt = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
.split(';')
.filter(Boolean)
.map((ext) => ext.toLowerCase());
const candidateNames = cmd.includes('.') ? [cmd] : pathExt.map((ext) => `${cmd}${ext}`);
for (const entry of pathValue.split(path.delimiter).filter(Boolean)) {
for (const candidate of candidateNames) {
const resolved = path.win32.join(entry, candidate);
if (fs.existsSync(resolved)) return resolved;
}
}
return;
}
for (const entry of pathValue.split(path.delimiter).filter(Boolean)) {
const resolved = path.join(entry, cmd);
if (fs.existsSync(resolved)) return resolved;
}
};
const openExternalBrowser = async (
url: string,
logger?: { warn: (msg: string) => void },
): Promise<boolean> => {
const command =
process.platform === 'win32'
? {
args: ['url.dll,FileProtocolHandler', url],
cmd: 'rundll32',
}
: {
args: [url],
cmd: process.platform === 'darwin' ? 'open' : 'xdg-open',
};
const executable = resolveCommandExecutable(command.cmd);
if (!executable) {
logger?.warn(`openExternalBrowser: ${command.cmd} not found on PATH`);
return false;
}
return new Promise<boolean>((resolve) => {
try {
const child = spawn(executable, command.args, {
detached: true,
stdio: 'ignore',
});
let settled = false;
const done = (ok: boolean, reason?: string) => {
if (settled) return;
settled = true;
if (!ok && reason) logger?.warn(`openExternalBrowser: ${reason}`);
resolve(ok);
};
child.once('error', (err) => done(false, (err as Error).message));
child.once('spawn', () => {
child.unref();
done(true);
});
setTimeout(() => done(true), 200);
} catch (e) {
logger?.warn(`openExternalBrowser: ${(e as Error).message}`);
resolve(false);
}
});
};
export default defineConfig({
base: isDev ? '/' : process.env.VITE_CDN_BASE || (isAuth ? '/_spa-auth/' : '/_spa/'),
build: {
modulePreload: sharedModulePreload,
outDir: isAuth ? 'dist/auth' : isMobile ? 'dist/mobile' : 'dist/desktop',
reportCompressedSize: false,
rolldownOptions: {
...(enableViteDevTools && { devtools: {} }),
input: path.resolve(
__dirname,
isAuth ? 'index.auth.html' : isMobile ? 'index.mobile.html' : 'index.html',
),
output: createSharedRolldownOutput({ strictExecutionOrder: true }),
},
},
define: sharedRendererDefine({ isMobile, isElectron: false }),
experimental: {
bundledDev: false,
},
resolve: {
tsconfigPaths: true,
},
optimizeDeps: sharedOptimizeDeps,
plugins: [
vercelSkewProtection(),
viteEnvRestartKeys(['APP_URL']),
enableViteDevTools &&
DevTools({
build: {
withApp: true,
},
}),
...sharedRendererPlugins({ platform }),
isDev && {
name: 'lobe-dev-proxy-print',
configureServer(server: ViteDevServer) {
const ONLINE_HOST = 'https://app.lobehub.com';
const c = {
green: (s: string) => `\x1B[32m${s}\x1B[0m`,
bold: (s: string) => `\x1B[1m${s}\x1B[0m`,
cyan: (s: string) => `\x1B[36m${s}\x1B[0m`,
};
const { info } = server.config.logger;
const isBundledDev = (server.config.experimental as any)?.bundledDev;
const getProxyUrl = () => {
const urls = server.resolvedUrls;
if (!urls?.local?.[0]) return;
const localHost = urls.local[0].replace(/\/$/, '');
return `${ONLINE_HOST}/_dangerous_local_dev_proxy?debug-host=${encodeURIComponent(localHost)}`;
};
const printProxyUrl = () => {
const proxyUrl = getProxyUrl();
if (!proxyUrl) return;
const colorUrl = (url: string) =>
c.cyan(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
info(` ${c.green('➜')} ${c.bold('Debug Proxy')}: ${colorUrl(proxyUrl)}`);
};
const openProxyUrl = async () => {
const proxyUrl = getProxyUrl();
if (!proxyUrl) return;
const opened = await openExternalBrowser(proxyUrl, server.config.logger);
if (!opened) {
server.config.logger.warn(`Failed to open Debug Proxy automatically: ${proxyUrl}`);
}
};
if (isBundledDev) {
// Disable Vite's built-in browser opening. We always open the debug
// proxy URL after the first bundled compile finishes instead.
server.openBrowser = () => {};
const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
let spinnerIdx = 0;
let spinnerTimer: NodeJS.Timeout | null = null;
const formatElapsed = (ms: number) =>
ms < 1000 ? `${Math.max(0, Math.round(ms))}ms` : `${(ms / 1000).toFixed(1)}s`;
const startSpinner = (msg: string, since: number) => {
spinnerIdx = 0;
spinnerTimer = setInterval(() => {
const elapsed = formatElapsed(Date.now() - since);
process.stdout.write(`\r${c.cyan(spinnerFrames[spinnerIdx])} ${msg} (${elapsed})`);
spinnerIdx = (spinnerIdx + 1) % spinnerFrames.length;
}, 80);
};
const stopSpinner = (clearLine = true) => {
if (spinnerTimer) {
clearInterval(spinnerTimer);
spinnerTimer = null;
}
if (clearLine) process.stdout.write('\r\x1B[K');
};
server.httpServer?.once('listening', () => {
void (async () => {
const rootUrl =
server.resolvedUrls?.local?.[0] ||
`http://localhost:${String(server.config.server.port || 9876)}/`;
const startedAt = Date.now();
const timeout = 180_000;
const interval = 400;
let ready = false;
startSpinner('Vite: compile and bundle...', startedAt);
try {
while (Date.now() - startedAt < timeout) {
try {
const res = await fetch(rootUrl, { signal: AbortSignal.timeout(5_000) });
const text = await res.text();
if (text.includes('Bundling in progress')) {
await new Promise((r) => setTimeout(r, interval));
continue;
}
ready = true;
stopSpinner();
info(
` ${c.green('✅')} Vite: compile and bundle finished (${res.status}) ${rootUrl}`,
);
void openProxyUrl();
break;
} catch {
await new Promise((r) => setTimeout(r, interval));
}
}
} catch (e) {
stopSpinner();
console.warn('⚠️ Vite: could not wait for compile and bundle:', e);
}
if (!ready && spinnerTimer) {
stopSpinner();
console.warn(`⚠️ Vite: compile and bundle timed out after ${timeout / 1000}s`);
}
printProxyUrl();
})();
});
}
return () => {
server.printUrls = () => {
if (isBundledDev) return;
printProxyUrl();
};
};
},
},
!isAuth &&
VitePWA({
injectRegister: null,
manifest: false,
registerType: 'prompt',
workbox: {
globIgnores: sharedPwaGlobIgnores,
globPatterns: ['**/*.{js,css,html,woff2}'],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
runtimeCaching: [
...sharedPwaRuntimeCaching,
{
handler: 'StaleWhileRevalidate',
options: { cacheName: 'google-fonts-stylesheets' },
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
},
{
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-webfonts',
expiration: { maxAgeSeconds: 60 * 60 * 24 * 365, maxEntries: 30 },
},
urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
},
{
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'image-assets',
expiration: { maxAgeSeconds: 60 * 60 * 24 * 30, maxEntries: 100 },
},
urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp|ico|avif)$/i,
},
{
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: { maxAgeSeconds: 60 * 5, maxEntries: 50 },
},
urlPattern: /\/(api|trpc)\/.*/i,
},
],
},
}),
].filter(Boolean) as PluginOption[],
server: {
cors: true,
host: true,
port: isMobile
? Number(process.env.MOBILE_SPA_PORT) || 3012
: isAuth
? Number(process.env.AUTH_SPA_PORT) || 3013
: Number(process.env.SPA_PORT) || 9876,
// The dev orchestrator (scripts/devStartupSequence.mts) pre-resolves a free
// port and injects it via env; never silently drift to another port, since
// downstream consumers locate this server through that env contract.
strictPort: true,
proxy: {
'/api': `http://localhost:${process.env.PORT || 3010}`,
'/oidc': `http://localhost:${process.env.PORT || 3010}`,
'/trpc': `http://localhost:${process.env.PORT || 3010}`,
'/webapi': `http://localhost:${process.env.PORT || 3010}`,
},
warmup: {
clientFiles: [
// src/ business code
'./src/initialize.ts',
'./src/spa/**/*.tsx',
'./src/business/**/*.{ts,tsx}',
'./src/components/**/*.{ts,tsx}',
'./src/const/**/*.ts',
'./src/features/**/*.{ts,tsx}',
'./src/helpers/**/*.ts',
'./src/hooks/**/*.{ts,tsx}',
'./src/layout/**/*.{ts,tsx}',
'./src/libs/**/*.{ts,tsx}',
'./src/routes/**/*.{ts,tsx}',
'./src/services/**/*.ts',
'./src/store/**/*.{ts,tsx}',
'./src/styles/**/*.ts',
'./src/utils/**/*.{ts,tsx}',
// monorepo packages
'./packages/types/src/**/*.ts',
'./packages/const/src/**/*.ts',
'./packages/utils/src/**/*.ts',
'./packages/context-engine/src/**/*.ts',
'./packages/prompts/src/**/*.ts',
'./packages/model-bank/src/**/*.ts',
'./packages/model-runtime/src/**/*.ts',
'./packages/agent-runtime/src/**/*.ts',
'./packages/conversation-flow/src/**/*.ts',
'./packages/electron-client-ipc/src/**/*.ts',
'./packages/builtin-agents/src/**/*.ts',
'./packages/builtin-skills/src/**/*.ts',
'./packages/builtin-tool-*/src/**/*.ts',
'./packages/builtin-tools/src/**/*.ts',
'./packages/business/*/src/**/*.ts',
'./packages/business-server/src/**/*.ts',
'./packages/config/src/**/*.ts',
'./packages/edge-config/src/**/*.ts',
'./packages/editor-runtime/src/**/*.ts',
'./packages/env/src/**/*.ts',
'./packages/trpc/src/**/*.{ts,tsx}',
'./packages/app-config/src/**/*.ts',
'./packages/locales/src/**/*.ts',
'./packages/fetch-sse/src/**/*.ts',
'./packages/desktop-bridge/src/**/*.ts',
'./packages/python-interpreter/src/**/*.ts',
'./packages/agent-manager-runtime/src/**/*.ts',
],
},
watch: createViteWatchOptions([__dirname]),
},
});