Skip to content

Commit

Permalink
chore: add more vite compabitabilities
Browse files Browse the repository at this point in the history
  • Loading branch information
wre232114 committed Dec 12, 2023
1 parent b21a835 commit f2d7330
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 65 deletions.
4 changes: 2 additions & 2 deletions js-plugins/record-viewer/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"root": true,
"extends": "../../.eslintrc.base.json",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
"project": ["./js-plugins/record-viewer/tsconfig.json"]
}
}
18 changes: 10 additions & 8 deletions js-plugins/record-viewer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,16 @@ export default function farmRecorderPlugin(
});
},
configureCompiler: (compiler) => {
const middleware = createDateSourceMiddleware(compiler);

createRecordViewerServer({
host: recordViewerOptions.host,
port: recordViewerOptions.port,
clientPath: PLUGIN_DIR_CLIENT,
middleware
});
if (farmConfig?.mode !== 'development') {
const middleware = createDateSourceMiddleware(compiler);

createRecordViewerServer({
host: recordViewerOptions.host,
port: recordViewerOptions.port,
clientPath: PLUGIN_DIR_CLIENT,
middleware
});
}
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export async function normalizePersistentCache(
packages.push(...(rustPlugins ?? []));

if (packages?.length) {
console.log('packages', config);
// console.log('packages', config);
const require = createRequire(path.join(config.root, 'package.json'));

for (const p of packages) {
Expand Down
13 changes: 7 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ export async function start(
);

const compiler = new Compiler(normalizedConfig);
normalizedConfig.jsPlugins.forEach((plugin: JsPlugin) =>
plugin.configureCompiler?.(compiler)
);
for (const plugin of normalizedConfig.jsPlugins) {
await plugin.configureCompiler?.(compiler);
}

const devServer = new DevServer(compiler, logger, config, normalizedConfig);
devServer.createFarmServer(devServer.userConfig.server);

Expand Down Expand Up @@ -316,9 +317,9 @@ export async function createBundleHandler(
) {
const compiler = new Compiler(normalizedConfig);

normalizedConfig.jsPlugins.forEach((plugin: JsPlugin) =>
plugin.configureCompiler?.(compiler)
);
for (const plugin of normalizedConfig.jsPlugins) {
await plugin.configureCompiler?.(compiler);
}

await compilerHandler(async () => {
compiler.removeOutputPathDir();
Expand Down
14 changes: 5 additions & 9 deletions packages/core/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { rustPluginResolver } from './rust/index.js';
import type { JsPlugin } from './type.js';
import { ConfigEnv, type UserConfig } from '../config/index.js';
import merge from 'lodash.merge';
import { Config } from '../../binding/index.js';

export * from './js/index.js';
export * from './rust/index.js';
Expand Down Expand Up @@ -85,9 +86,7 @@ export async function resolveConfigHook(
}

for (const p of uniqueVitePlugins.values()) {
const hook = p.config;

if (hook) {
if (p.config) {
const res = await p.config(conf, configEnv);

if (res) {
Expand All @@ -100,15 +99,12 @@ export async function resolveConfigHook(
}

export async function resolveConfigResolvedHook(
config: Config,
config: Config['config'],
plugins: JsPlugin[]
) {
const conf = config;

for (const p of plugins) {
const hook = p.configResolved;
if (hook) {
await p.configResolved(conf.config);
if (p.configResolved) {
await p.configResolved(config);
}
}
}
Expand Down
34 changes: 28 additions & 6 deletions packages/core/src/plugin/js/farm-to-vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
throwIncompatibleError
} from './utils.js';
import merge from 'lodash.merge';
import { Logger } from '../../index.js';

export function farmConfigToViteConfig(config: UserConfig): ViteUserConfig {
const vitePlugins = config.vitePlugins.map((plugin) => {
Expand Down Expand Up @@ -63,7 +64,8 @@ export function farmConfigToViteConfig(config: UserConfig): ViteUserConfig {

export function proxyViteConfig(
viteConfig: ViteUserConfig,
pluginName: string
pluginName: string,
logger: Logger
): ViteUserConfig {
return new Proxy(viteConfig, {
get(target, key) {
Expand All @@ -88,11 +90,14 @@ export function proxyViteConfig(
'isProduction',
'css',
'build',
'logger',
// these fields are always undefined in farm
// they are only used for compatibility
'legacy',
'optimizeDeps',
'ssr'
'ssr',
'logLevel',
'experimental'
];

if (allowedKeys.includes(String(key))) {
Expand All @@ -107,7 +112,7 @@ export function proxyViteConfig(
'dedupe'
];

return new Proxy(target.resolve, {
return new Proxy(target.resolve || {}, {
get(resolveTarget, resolveKey) {
if (typeof resolveKey !== 'string') {
return target[resolveKey as unknown as keyof typeof target];
Expand Down Expand Up @@ -145,7 +150,7 @@ export function proxyViteConfig(
'origin'
];

return new Proxy(target.server, {
return new Proxy(target.server || {}, {
get(serverTarget, serverKey) {
if (typeof serverKey !== 'string') {
return target[serverKey as unknown as keyof typeof target];
Expand Down Expand Up @@ -174,7 +179,7 @@ export function proxyViteConfig(
} else if (key === 'css') {
const allowedCssKeys = ['devSourcemap'];

return new Proxy(target.css, {
return new Proxy(target.css || {}, {
get(cssTarget, cssKey) {
if (typeof cssKey !== 'string') {
return target[cssKey as unknown as keyof typeof target];
Expand Down Expand Up @@ -209,7 +214,7 @@ export function proxyViteConfig(
'ssr'
];

return new Proxy(target.build, {
return new Proxy(target.build || {}, {
get(buildTarget, buildKey) {
if (typeof buildKey !== 'string') {
return target[buildKey as unknown as keyof typeof target];
Expand All @@ -234,6 +239,23 @@ export function proxyViteConfig(
);
}
});
} else if (key === 'optimizeDeps') {
return new Proxy(target.optimizeDeps || {}, {
get(_, optimizeDepsKey) {
logger.warn(
`[vite-plugin] ${pluginName}: config "optimizeDeps" is not needed in farm, all of its options will be ignored. Current ignored option is: "${String(
optimizeDepsKey
)}"`
);

if (optimizeDepsKey === 'esbuildOptions') {
return {};
}
return undefined;
}
});
} else if (key === 'logger') {
return logger;
}

return target[key as keyof typeof target];
Expand Down
97 changes: 67 additions & 30 deletions packages/core/src/plugin/js/vite-plugin-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export class VitePluginAdapter implements JsPlugin {
renderStart: JsPlugin['renderStart'];
augmentResourceHash?: JsPlugin['augmentResourceHash'];
finalizeResources: JsPlugin['finalizeResources'];
writeResources: JsPlugin['writeResources'];

// filter for js plugin to improve performance
filters: string[];
Expand All @@ -126,32 +127,41 @@ export class VitePluginAdapter implements JsPlugin {

this.filters = filters;

const hooksMap = {
buildStart: () =>
(this.buildStart = this.viteBuildStartToFarmBuildStart()),
resolve: () => (this.resolve = this.viteResolveIdToFarmResolve()),
load: () => (this.load = this.viteLoadToFarmLoad()),
transform: () => (this.transform = this.viteTransformToFarmTransform()),
buildEnd: () => (this.buildEnd = this.viteBuildEndToFarmBuildEnd()),
closeBundle: () => (this.finish = this.viteCloseBundleToFarmFinish()),
handleHotUpdate: () =>
(this.updateModules = this.viteHandleHotUpdateToFarmUpdateModules()),
renderChunk: () =>
(this.renderResourcePot =
this.viteHandleRenderChunkToFarmRenderResourcePot()),
renderStart: () =>
(this.renderStart = this.viteRenderStartToFarmRenderStart()),
augmentChunkHash: () =>
(this.augmentResourceHash =
this.viteAugmentChunkHashToFarmAugmentResourceHash()),
generateBundle: () =>
(this.finalizeResources =
this.viteGenerateBundleToFarmFinalizeResources()),
writeBundle: () =>
(this.writeResources = this.viteWriteBundleToFarmWriteResources())
};
// convert hooks
if (rawPlugin.buildStart)
this.buildStart = this.viteBuildStartToFarmBuildStart();
if (rawPlugin.buildStart) this.resolve = this.viteResolveIdToFarmResolve();
if (rawPlugin.load) this.load = this.viteLoadToFarmLoad();
if (rawPlugin.transform)
this.transform = this.viteTransformToFarmTransform();
if (rawPlugin.buildEnd) this.buildEnd = this.viteBuildEndToFarmBuildEnd();
if (rawPlugin.closeBundle) this.finish = this.viteCloseBundleToFarmFinish();
if (rawPlugin.handleHotUpdate)
this.updateModules = this.viteHandleHotUpdateToFarmUpdateModules();
if (rawPlugin.renderChunk)
this.renderResourcePot =
this.viteHandleRenderChunkToFarmRenderResourcePot();
if (rawPlugin.renderStart)
this.renderStart = this.viteRenderStartToFarmRenderStart();
if (rawPlugin.augmentChunkHash)
this.augmentResourceHash =
this.viteAugmentChunkHashToFarmAugmentResourceHash();
if (rawPlugin.generateBundle)
this.finalizeResources = this.viteGenerateBundleToFarmFinalizeResources();
for (const [hookName, fn] of Object.entries(hooksMap)) {
if (rawPlugin[hookName as keyof Plugin]) {
fn();
}
}

// if other unsupported vite plugins hooks are used, throw error
const unsupportedHooks = [
'transformIndexHtml',
'writeBundle',
// 'writeBundle',
'renderError',
'resolveDynamicImport',
'resolveFileUrl',
Expand Down Expand Up @@ -183,11 +193,12 @@ export class VitePluginAdapter implements JsPlugin {
merge(
this._viteConfig,
await configHook(
proxyViteConfig(this._viteConfig, this.name),
proxyViteConfig(this._viteConfig, this.name, this._logger),
this.getViteConfigEnv()
)
),
this.name
this.name,
this._logger
);

this._farmConfig = viteConfigToFarmConfig(
Expand All @@ -200,12 +211,9 @@ export class VitePluginAdapter implements JsPlugin {
return this._farmConfig.compilation;
}

async configResolved(config: UserConfig['compilation']) {
async configResolved(_config: UserConfig['compilation']) {
if (!this._rawPlugin.configResolved) return;

this._farmConfig.compilation = config;
this._viteConfig = farmConfigToViteConfig(this._farmConfig);

const configResolvedHook = this.wrapRawPluginHook(
'configResolved',
this._rawPlugin.configResolved
Expand Down Expand Up @@ -276,7 +284,9 @@ export class VitePluginAdapter implements JsPlugin {
hook?: ObjectHook<(...args: any[]) => any, { sequential?: boolean }>,
farmContext?: CompilationContext,
currentHandlingFile?: string
) {
): (
...args: any[]
) => any | undefined | Promise<(...args: any[]) => any | undefined> {
if (hook === undefined) {
return undefined;
}
Expand Down Expand Up @@ -608,7 +618,7 @@ export class VitePluginAdapter implements JsPlugin {
context
) as OmitThis<FunctionPluginHooks['augmentChunkHash']>;

const hash = await hook(
const hash = await hook?.(
transformResourceInfo2RollupRenderedChunk(param)
);

Expand All @@ -635,7 +645,7 @@ export class VitePluginAdapter implements JsPlugin {
{} as OutputBundle
);

hook(
await hook?.(
transformFarmConfigToRollupNormalizedOutputOptions(param.config),
bundles
);
Expand All @@ -652,6 +662,33 @@ export class VitePluginAdapter implements JsPlugin {
};
}

private viteWriteBundleToFarmWriteResources(): JsPlugin['writeResources'] {
return {
executor: this.wrapExecutor(
async (param: FinalizeResourcesHookParams, context) => {
const hook = this.wrapRawPluginHook(
'writeBundle',
this._rawPlugin.writeBundle,
context
);

const bundles = Object.entries(param.resourcesMap).reduce(
(res, [key, val]) => {
res[key] = transformResourceInfo2RollupResource(val);
return res;
},
{} as OutputBundle
);

await hook?.(
transformFarmConfigToRollupNormalizedOutputOptions(param.config),
bundles
);
}
)
};
}

// skip farm lazy compilation virtual module for vite plugin
public static isFarmInternalVirtualModule(id: string) {
return (
Expand Down
10 changes: 7 additions & 3 deletions packages/core/src/plugin/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,19 +131,19 @@ export interface JsPlugin {
configEnv?: ConfigEnv
) => Config['config'] | Promise<Config['config']>;

configResolved?: (config: Config['config']) => void;
configResolved?: (config: Config['config']) => void | Promise<void>;

/**
* runs in development mode only
* @param server
* @returns
*/
configureDevServer?: (server: DevServer) => void;
configureDevServer?: (server: DevServer) => void | Promise<void>;
/**
* @param compiler
* @returns
*/
configureCompiler?: (compiler: Compiler) => void;
configureCompiler?: (compiler: Compiler) => void | Promise<void>;

buildStart?: { executor: Callback<Record<string, never>, void> };

Expand Down Expand Up @@ -198,6 +198,10 @@ export interface JsPlugin {
>;
};

writeResources?: {
executor: Callback<FinalizeResourcesHookParams, void | Promise<void>>;
};

pluginCacheLoaded?: {
executor: Callback<number[], undefined | null | void>;
};
Expand Down

0 comments on commit f2d7330

Please sign in to comment.