diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts index 891ed234b..1b174798b 100644 --- a/packages/core/src/config/schema.ts +++ b/packages/core/src/config/schema.ts @@ -189,6 +189,7 @@ const serverSchema = z middlewares: z.array(z.any()).optional(), middlewareMode: z.boolean().optional(), writeToDisk: z.boolean().optional(), + origin: z.string().optional(), preview: previewServerSchema.optional() }) .strict(); diff --git a/packages/core/src/server/index.ts b/packages/core/src/server/index.ts index 912099173..3bac08ff5 100644 --- a/packages/core/src/server/index.ts +++ b/packages/core/src/server/index.ts @@ -122,7 +122,7 @@ export class Server extends httpServer { middlewares: connect.Server; compiler: CompilerType; root: string; - resolvedUserConfig: ResolvedUserConfig; + config: ResolvedUserConfig; closeHttpServerFn: () => Promise; terminateServerFn: (_: unknown, exitCode?: number) => Promise; postConfigureServerHooks: ((() => void) | void)[] = []; @@ -155,21 +155,21 @@ export class Server extends httpServer { */ async createServer(): Promise { try { - this.resolvedUserConfig = await resolveConfig( + this.config = await resolveConfig( this.inlineConfig, 'start', 'development', 'development' ); - this.logger = this.resolvedUserConfig.logger; + this.logger = this.config.logger; this.#resolveOptions(); - this.compiler = createCompiler(this.resolvedUserConfig); + this.compiler = createCompiler(this.config); for (const hook of getPluginHooks( - this.resolvedUserConfig.jsPlugins, + this.config.jsPlugins, 'configureCompiler' )) { await hook?.(this.compiler); @@ -244,7 +244,7 @@ export class Server extends httpServer { * create watcher */ async #createWatcher() { - this.watcher = new Watcher(this.resolvedUserConfig); + this.watcher = new Watcher(this.config); await this.watcher.createWatcher(); @@ -262,15 +262,12 @@ export class Server extends httpServer { this.watcher.on('change', async (file: string) => { file = normalizePath(file); - const shortFile = getShortName(file, this.resolvedUserConfig.root); - const isConfigFile = this.resolvedUserConfig.configFilePath === file; - const isConfigDependencyFile = - this.resolvedUserConfig.configFileDependencies.some( - (name) => file === name - ); - const isEnvFile = this.resolvedUserConfig.envFiles.some( + const shortFile = getShortName(file, this.config.root); + const isConfigFile = this.config.configFilePath === file; + const isConfigDependencyFile = this.config.configFileDependencies.some( (name) => file === name ); + const isEnvFile = this.config.envFiles.some((name) => file === name); if (isConfigFile || isConfigDependencyFile || isEnvFile) { __FARM_GLOBAL__.__FARM_RESTART_DEV_SERVER__ = true; this.logger.info( @@ -281,13 +278,13 @@ export class Server extends httpServer { try { await this.restartServer(); } catch (e) { - this.resolvedUserConfig.logger.error(`restart server error ${e}`); + this.config.logger.error(`restart server error ${e}`); } } try { this.hmrEngine.hmrUpdate(file); } catch (error) { - this.resolvedUserConfig.logger.error(`Farm Hmr Update Error: ${error}`); + this.config.logger.error(`Farm Hmr Update Error: ${error}`); } }); const handleUpdateFinish = (updateResult: JsUpdateResult) => { @@ -425,13 +422,9 @@ export class Server extends httpServer { host: hostname.host }); - this.resolvedUserConfig.compilation.define.FARM_HMR_PORT = - serverPort.toString(); + this.config.compilation.define.FARM_HMR_PORT = serverPort.toString(); - this.resolvedUrls = await resolveServerUrls( - this.httpServer, - this.resolvedUserConfig - ); + this.resolvedUrls = await resolveServerUrls(this.httpServer, this.config); // compile the project and start the dev server await this.#startCompile(); @@ -442,7 +435,7 @@ export class Server extends httpServer { this.#openServerBrowser(); } } catch (error) { - this.resolvedUserConfig.logger.error( + this.config.logger.error( `Start DevServer Error: ${error} \n ${error.stack}` ); // throw error; @@ -486,7 +479,7 @@ export class Server extends httpServer { return true; } }); - const { jsPlugins } = this.resolvedUserConfig; + const { jsPlugins } = this.config; for (const hook of getSortedPluginHooksBindThis( jsPlugins, @@ -512,12 +505,12 @@ export class Server extends httpServer { }, root, server - } = this.resolvedUserConfig; + } = this.config; this.publicPath = publicPath; this.publicDir = publicDir; if (server.origin?.endsWith('/')) { server.origin = server.origin.slice(0, -1); - this.resolvedUserConfig.logger.warn( + this.config.logger.warn( `${colors.bold('(!)')} server.origin should not end with "/". Using "${ server.origin }" instead.` @@ -563,7 +556,7 @@ export class Server extends httpServer { this.middlewares.use(publicMiddleware(this)); } - if (this.resolvedUserConfig.compilation.lazyCompilation) { + if (this.config.compilation.lazyCompilation) { this.middlewares.use(lazyCompilationMiddleware(this)); } @@ -590,11 +583,11 @@ export class Server extends httpServer { async #compile(): Promise { try { await this.compiler.compile(); - await (this.resolvedUserConfig.server.writeToDisk + await (this.config.server.writeToDisk ? this.compiler.writeResourcesToDisk() : this.compiler.callWriteResourcesHook()); } catch (err) { - this.resolvedUserConfig.logger.error( + this.config.logger.error( `Compilation failed: ${convertErrorMessage(err)}` ); // throw err; @@ -634,7 +627,7 @@ export class Server extends httpServer { * @returns {Promise>} A promise that resolves to a set of public file paths. */ async #handlePublicFiles(): Promise> { - const initPublicFilesPromise = initPublicFiles(this.resolvedUserConfig); + const initPublicFilesPromise = initPublicFiles(this.config); return await initPublicFilesPromise; } @@ -648,9 +641,7 @@ export class Server extends httpServer { this.ws.wss.on('vite:invalidate', ({ path, message }: any) => { // find hmr boundary starting from the parent of the file - this.resolvedUserConfig.logger.info( - `HMR invalidate: ${path}. ${message ?? ''} ` - ); + this.config.logger.info(`HMR invalidate: ${path}. ${message ?? ''} `); const parentFiles = this.compiler.getParentFiles(path); const normalizeParentFiles = parentFiles.map((file) => normalizePath(file) @@ -725,7 +716,7 @@ export class Server extends httpServer { printServerUrls( this.resolvedUrls, this.serverOptions.host, - this.resolvedUserConfig.logger + this.config.logger ); } else if (this.serverOptions.middlewareMode) { throw new Error('cannot print server URLs in middleware mode.'); diff --git a/packages/core/src/server/middlewares/htmlFallback.ts b/packages/core/src/server/middlewares/htmlFallback.ts index 4d1265511..51c829fb0 100644 --- a/packages/core/src/server/middlewares/htmlFallback.ts +++ b/packages/core/src/server/middlewares/htmlFallback.ts @@ -25,7 +25,7 @@ export function htmlFallbackMiddleware( } const url = cleanUrl(req.url); const pathname = removeSlash(decodeURIComponent(url)); - const headers = app.resolvedUserConfig.server.headers; + const headers = app.config.server.headers; if (pathname.endsWith('.html')) { const html = app.compiler.resource(pathname); diff --git a/packages/core/src/server/middlewares/lazyCompilation.ts b/packages/core/src/server/middlewares/lazyCompilation.ts index dbd66bf50..bad1b9749 100644 --- a/packages/core/src/server/middlewares/lazyCompilation.ts +++ b/packages/core/src/server/middlewares/lazyCompilation.ts @@ -20,7 +20,7 @@ export function lazyCompilationMiddleware( app: Server ): Connect.NextHandleFunction { return async function handleLazyCompilationMiddleware(req, res, next) { - const { resolvedUserConfig, compiler } = app; + const { config, compiler } = app; if (!req.url.startsWith(DEFAULT_LAZY_COMPILATION_PATH)) { return await next(); @@ -44,7 +44,7 @@ export function lazyCompilationMiddleware( }) .join(', '); - resolvedUserConfig.logger.info( + config.logger.info( `${bold(green('✨Lazy compiling'))} ${bold(cyan(pathsStr))}`, true ); @@ -62,19 +62,15 @@ export function lazyCompilationMiddleware( return next(); } - if (isNodeEnvironment || resolvedUserConfig.server.writeToDisk) { + if (isNodeEnvironment || config.server.writeToDisk) { compiler.writeResourcesToDisk(); } - resolvedUserConfig.logger.info( + config.logger.info( `${bold(green(`✓ Lazy compilation done`))} ${bold( cyan(pathsStr) )} in ${bold( - green( - resolvedUserConfig.logger.formatExecutionTime( - performance.now() - start - ) - ) + green(config.logger.formatExecutionTime(performance.now() - start)) )}.` ); diff --git a/packages/core/src/server/middlewares/proxy.ts b/packages/core/src/server/middlewares/proxy.ts index f4699b3b7..dee3c6f0a 100644 --- a/packages/core/src/server/middlewares/proxy.ts +++ b/packages/core/src/server/middlewares/proxy.ts @@ -27,7 +27,7 @@ export function proxyMiddleware( middlewareServer: HttpServer, config: NonNullable ): Connect.NextHandleFunction { - const { resolvedUserConfig } = app; + const { config: resolvedUserConfig } = app; const proxies: Record = {}; Object.keys(config).forEach((context) => { diff --git a/packages/core/src/server/middlewares/resource.ts b/packages/core/src/server/middlewares/resource.ts index d3e08f7a3..8ab26a75f 100644 --- a/packages/core/src/server/middlewares/resource.ts +++ b/packages/core/src/server/middlewares/resource.ts @@ -26,7 +26,7 @@ export function resourceMiddleware(app: Server): Connect.NextHandleFunction { return next(); } const url = cleanUrl(req.url); - const { compiler, resolvedUserConfig: config, publicPath } = app; + const { compiler, config, publicPath } = app; if (compiler._isInitialCompile) { await compiler.waitForInitialCompileFinish(); diff --git a/packages/core/src/server/middlewares/static.ts b/packages/core/src/server/middlewares/static.ts index 342edd6ed..483d815bc 100644 --- a/packages/core/src/server/middlewares/static.ts +++ b/packages/core/src/server/middlewares/static.ts @@ -23,12 +23,12 @@ import sirv, { Options } from 'sirv'; import type { Server } from '../index.js'; export function staticMiddleware(app: Server): Connect.NextHandleFunction { - const { resolvedUserConfig, compiler } = app; + const { config, compiler } = app; const root = compiler.config.root; const serve = sirv( root, sirvOptions({ - getHeaders: () => resolvedUserConfig.server.headers + getHeaders: () => config.server.headers }) ); return function handleStaticMiddleware(req, res, next) { @@ -61,7 +61,7 @@ export function staticMiddleware(app: Server): Connect.NextHandleFunction { } export function publicMiddleware(app: Server): Connect.NextHandleFunction { - const { resolvedUserConfig: config, publicDir, publicFiles } = app; + const { config: config, publicDir, publicFiles } = app; const serve = sirv( publicDir, sirvOptions({ diff --git a/packages/core/src/server/preview.ts b/packages/core/src/server/preview.ts index 600e273ae..13c000ddb 100644 --- a/packages/core/src/server/preview.ts +++ b/packages/core/src/server/preview.ts @@ -50,7 +50,7 @@ export interface PreviewServerOptions extends CommonServerOptions { * @class */ export class PreviewServer extends httpServer { - resolvedUserConfig: ResolvedUserConfig; + config: ResolvedUserConfig; previewServerOptions: PreviewServerOptions; httpsOptions: SecureServerOptions; @@ -77,7 +77,7 @@ export class PreviewServer extends httpServer { * @throws {Error} If the server cannot be started. */ async createPreviewServer(): Promise { - this.resolvedUserConfig = await resolveConfig( + this.config = await resolveConfig( this.inlineConfig, 'preview', 'production', @@ -85,7 +85,7 @@ export class PreviewServer extends httpServer { true ); - this.logger = this.resolvedUserConfig.logger; + this.logger = this.config.logger; await this.#resolveOptions(); @@ -115,7 +115,7 @@ export class PreviewServer extends httpServer { */ #initializeMiddlewares() { const { cors, proxy } = this.previewServerOptions; - const { appType, middlewareMode } = this.resolvedUserConfig.server; + const { appType, middlewareMode } = this.config.server; if (cors !== false) { this.app.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); @@ -154,7 +154,7 @@ export class PreviewServer extends httpServer { const { server, compilation: { root, output } - } = this.resolvedUserConfig; + } = this.config; this.publicPath = output.publicPath ?? '/'; const preview = server?.preview; @@ -174,7 +174,7 @@ export class PreviewServer extends httpServer { this.serve = sirv(distDir, { etag: true, dev: true, - single: this.resolvedUserConfig.server.appType === 'spa', + single: this.config.server.appType === 'spa', ignores: false, setHeaders: (res, pathname) => { if (knownJavascriptExtensionRE.test(pathname)) { @@ -224,13 +224,13 @@ export class PreviewServer extends httpServer { this.resolvedUrls = await resolveServerUrls( this.httpServer, - this.resolvedUserConfig, + this.config, 'preview' ); const shortFile = getShortName( - this.resolvedUserConfig.configFilePath, - this.resolvedUserConfig.root + this.config.configFilePath, + this.config.root ); this.logger.info(`Using config file at ${bold(green(shortFile))}`); diff --git a/packages/core/src/server/ws.ts b/packages/core/src/server/ws.ts index 292ac430f..56678e9b2 100644 --- a/packages/core/src/server/ws.ts +++ b/packages/core/src/server/ws.ts @@ -115,7 +115,7 @@ export class WsServer { */ constructor(private readonly app: any) { this.logger = app.logger ?? new Logger(); - this.serverConfig = app.resolvedUserConfig.server as ServerOptions; + this.serverConfig = app.config.server as ServerOptions; this.createWebSocketServer(); }