Skip to content

Commit

Permalink
chore: update server logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Oct 8, 2024
1 parent 449fc4b commit f31203a
Show file tree
Hide file tree
Showing 7 changed files with 256 additions and 253 deletions.
11 changes: 3 additions & 8 deletions examples/vue3/farm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ function myCustomPlugin() {
apply: "serve",
config(config, { command }) {},
configureServer(server) {
server.httpServer?.once?.("listening", () => {
const { port } = server.config.server;
});
server.middlewares.use((req, res, next) => {
next();
});
console.log(server.moduleGraph.getModuleById);
},
transformIndexHtml(c) {
return c.replace(
Expand Down Expand Up @@ -92,7 +87,7 @@ export default defineConfig({
// enabled: true,
// }),
// compressionMiddleware(),
// myCustomPlugin(),
myCustomPlugin(),
// createHtmlPlugin({
// minify: true,
// /**
Expand Down Expand Up @@ -141,7 +136,7 @@ export default defineConfig({
progress: false,
resolve: {
// alias: {
// "@": path.resolve("src"),
// "@": path.resolve("src"),
// },
alias: [{ find: "@", replacement: path.resolve("src") }],
},
Expand Down
14 changes: 0 additions & 14 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,22 +191,8 @@ export async function resolveConfig(
inlineConfig
});

// Temporarily dealing with alias objects and arrays in js will be unified in rust in the future.]
// if (vitePlugins.length) {
// resolvedUserConfig.compilation.resolve.alias = getAliasEntries(
// resolvedUserConfig.compilation.resolve.alias,
// );
// }

await resolveConfigResolvedHook(resolvedUserConfig, sortFarmJsPlugins); // Fix: Await the Promise<void> and pass the resolved value to the function.

//TODO solve the problem of alias adaptation to vite we should resolve this in rust side
// if (resolvedUserConfig.compilation?.resolve?.alias && vitePlugins.length) {
// resolvedUserConfig.compilation.resolve.alias = transformAliasWithVite(
// resolvedUserConfig.compilation.resolve.alias as unknown as Array<Alias>,
// );
// }

await handleLazyCompilation(
resolvedUserConfig,
command as keyof typeof COMMANDS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import path from 'node:path';

import { RustPlugin } from '../../plugin/index.js';
import { Config } from '../../types/binding.js';
import { Logger } from '../../utils/logger.js';
import { traceDependencies } from '../../utils/trace-dependencies.js';
import { isDisableCache } from '../env.js';
import { ResolvedUserConfig } from '../index.js';
Expand Down
51 changes: 26 additions & 25 deletions packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,16 +159,17 @@ export class Server extends httpServer {

this.#resolveOptions();

// TODO createCompiler 到底在何时创建
this.compiler = await createCompiler(this.resolvedUserConfig);
await resolveConfigureCompilerHook(
this.compiler,
this.resolvedUserConfig
);
this.httpsOptions = await this.resolveHttpsConfig(
this.serverOptions.https
);
this.publicFiles = await this.#handlePublicFiles();
const [httpsOptions, publicFiles] = await Promise.all([
this.resolveHttpsConfig(this.serverOptions.https),
this.#handlePublicFiles()
]);
this.httpsOptions = httpsOptions;
this.publicFiles = publicFiles;
this.middlewares = connect() as connect.Server;
this.httpServer = this.serverOptions.middlewareMode
? null
Expand Down Expand Up @@ -216,26 +217,26 @@ export class Server extends httpServer {
}

/**
*
* create watcher
*/
async #createWatcher() {
this.watcher = new Watcher(this.resolvedUserConfig);

await this.watcher.createWatcher();

this.watcher.watcher.on('add', async (file: string | string[] | any) => {
this.watcher.watcher.on('add', async (file: string) => {
// TODO pluginContainer hooks
});

this.watcher.watcher.on('unlink', async (file: string | string[] | any) => {
this.watcher.watcher.on('unlink', async (file: string) => {
const parentFiles = this.compiler.getParentFiles(file);
const normalizeParentFiles = parentFiles.map((file) =>
normalizePath(file)
);
this.hmrEngine.hmrUpdate(normalizeParentFiles, true);
});

this.watcher.watcher.on('change', async (file: string | string[] | any) => {
this.watcher.watcher.on('change', async (file: string) => {
file = normalizePath(file);
const shortFile = getShortName(file, this.resolvedUserConfig.root);
const isConfigFile = this.resolvedUserConfig.configFilePath === file;
Expand Down Expand Up @@ -400,16 +401,9 @@ export class Server extends httpServer {
this.resolvedUserConfig.compilation.define.FARM_HMR_PORT =
serverPort.toString();

// this.compiler = await createCompiler(this.resolvedUserConfig);
// await resolveConfigureCompilerHook(
// this.compiler,
// this.resolvedUserConfig,
// );

this.resolvedUrls = await resolveServerUrls(
this.httpServer,
this.serverOptions,
this.publicPath
this.resolvedUserConfig
);
// compile the project and start the dev server
await this.#startCompile();
Expand All @@ -423,7 +417,9 @@ export class Server extends httpServer {

__FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__ && this.printUrls();
} catch (error) {
// this.resolvedUserConfig.logger.error(`start farm dev server error: ${error}`);
this.resolvedUserConfig.logger.error(
`start farm dev server error: ${error}`
);
// throw error;
}
}
Expand Down Expand Up @@ -453,7 +449,7 @@ export class Server extends httpServer {
this.httpServer.removeListener('error', onError);
reject(new Error(`Port ${port} is already in use`));
} else {
this.logger.info(`Port ${port} is in use, trying another one...`);
this.logger.warn(`Port ${port} is in use, trying another one...`);
this.httpServer.listen(++port, host);
}
} else {
Expand Down Expand Up @@ -527,14 +523,19 @@ export class Server extends httpServer {
* @returns { void }
*/
#resolveOptions() {
const { compilation, server } = this.resolvedUserConfig;
this.publicPath = compilation.output.publicPath;

this.publicDir = compilation.assets.publicDir;
const {
compilation: {
output: { publicPath },
assets: { publicDir }
},
root,
server
} = this.resolvedUserConfig;
this.publicPath = publicPath;
this.publicDir = publicDir;

this.serverOptions = server as CommonServerOptions & NormalizedServerConfig;

this.root = compilation.root;
this.root = root;
}

/**
Expand Down
85 changes: 61 additions & 24 deletions packages/core/src/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
* https://github.com/vitejs/vite/blob/main/LICENSE
*/

import { promises as dns } from 'node:dns';
import type { AddressInfo, Server } from 'node:net';
import os from 'node:os';
import { UserServerConfig } from '../index.js';
import { ResolvedUserConfig, UserServerConfig } from '../index.js';

export interface ResolvedServerUrls {
local: string[];
Expand Down Expand Up @@ -38,35 +39,37 @@ export const wildcardHosts = new Set([

export async function resolveServerUrls(
server: Server,
options: UserServerConfig,
publicPath?: string
config: ResolvedUserConfig
): Promise<ResolvedServerUrls> {
const address = server.address();
const isAddressInfo = (x: any): x is AddressInfo => x?.address;

if (!isAddressInfo(address)) {
return { local: [], network: [] };
}

const serverOptions = config.server;
const local: string[] = [];
const network: string[] = [];
const hostname = await resolveHostname(options.host);
const protocol = options.https ? 'https' : 'http';
const { port } = getAddressHostnamePort(address);
const base = publicPath || '';
const hostname = await resolveHostname(serverOptions.host);
const protocol = serverOptions.https ? 'https' : 'http';
const port = address.port;
const base = config.compilation.output.publicPath;

if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) {
const url = createServerUrl(protocol, hostname.name, port, base);
let hostnameName = hostname.name;
// ipv6 host
if (hostnameName.includes(':')) {
hostnameName = `[${hostnameName}]`;
}
const address = `${protocol}://${hostnameName}:${port}${base}`;
if (loopbackHosts.has(hostname.host)) {
local.push(url);
local.push(address);
} else {
network.push(url);
network.push(address);
}
} else {
const networkInterfaces = Object.values(os.networkInterfaces()).flatMap(
(nInterface) => nInterface || []
);
networkInterfaces
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
detail &&
Expand All @@ -77,14 +80,18 @@ export async function resolveServerUrls(
)
.forEach((detail) => {
let host = detail.address.replace('127.0.0.1', hostname.name);
host = host.includes(':') ? `[${host}]` : host;
const url = createServerUrl(protocol, host, port, base);
detail.address.includes('127.0.0.1')
? local.push(url)
: network.push(url);
// ipv6 host
if (host.includes(':')) {
host = `[${host}]`;
}
const url = `${protocol}://${host}:${port}${base}`;
if (detail.address.includes('127.0.0.1')) {
local.push(url);
} else {
network.push(url);
}
});
}

return { local, network };
}

Expand All @@ -93,15 +100,25 @@ export async function resolveHostname(
): Promise<Hostname> {
let host: string | undefined;
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = 'localhost';
} else if (optionsHost === true) {
host = undefined;
// If passed --host in the CLI without arguments
host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
} else {
host = optionsHost;
}

const name =
host === undefined || wildcardHosts.has(host) ? 'localhost' : host;
// Set host name to localhost when possible
let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host;

if (host === 'localhost') {
// See #8647 for more details.
const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
if (localhostAddr) {
name = localhostAddr;
}
}

return { host, name };
}
Expand Down Expand Up @@ -133,3 +150,23 @@ export const teardownSIGTERMListener = (
process.stdin.off('end', callback);
}
};

/**
* Returns resolved localhost address when `dns.lookup` result differs from DNS
*
* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
* For example, when IPv6 is not supported on that machine/network.
*/
export async function getLocalhostAddressIfDiffersFromDNS(): Promise<
string | undefined
> {
const [nodeResult, dnsResult] = await Promise.all([
dns.lookup('localhost'),
dns.lookup('localhost', { verbatim: true })
]);
const isSame =
nodeResult.family === dnsResult.family &&
nodeResult.address === dnsResult.address;
return isSame ? undefined : nodeResult.address;
}
4 changes: 1 addition & 3 deletions packages/core/src/watcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import { arraify, getCacheDir } from '../utils/index.js';

export const debugWatcher = createDebugger('farm:watcher');

// TODO remove FileWatcher
interface ImplFileWatcher {}
export default class Watcher implements ImplFileWatcher {
export default class Watcher {
private watchedFiles = new Set<string>();
resolvedWatchOptions: WatchOptions;
watcher: FSWatcher;
Expand Down
Loading

0 comments on commit f31203a

Please sign in to comment.