Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add context parameters to updateModules hook #2026

Merged
merged 8 commits into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/vue3/farm.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineConfig } from "@farmfe/core";
// import Vue from "unplugin-vue/farm";
import Vue from "unplugin-vue/vite";
// import Vue from "unplugin-vue/vite";
import Vue from "@vitejs/plugin-vue";
import fs from 'fs'

export default defineConfig({
Expand Down
1 change: 0 additions & 1 deletion examples/vue3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"@module-federation/vite": "^1.1.1",
"unplugin-auto-import": "^0.16.7",
"unplugin-vue-router": "^0.7.0",
"unplugin-vue": "/Users/adny/typescript/unplugin-vue",
"vue": "^3.4.0",
"vue-router": "^4.4.3"
},
Expand Down
2 changes: 1 addition & 1 deletion examples/vue3/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import HelloWorld from "./components/HelloWorld.vue";
<img src="./assets/logo.png" class="logo" alt="Farm logo" /> </a>
<a href="https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>2222
</a>
</div>
<HelloWorld msg="Farm + Vue" />
</template>
Expand Down
47 changes: 45 additions & 2 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -45,6 +46,7 @@ import { normalizePersistentCache } from './normalize-config/normalize-persisten
import { parseUserConfig } from './schema.js';

import { externalAdapter } from '../plugin/js/external-adapter.js';
import { ViteModuleGraphAdapter } from '../plugin/js/vite-server-adapter.js';
import { convertErrorMessage } from '../utils/error.js';
import { resolveHostname } from '../utils/http.js';
import merge from '../utils/merge.js';
Expand All @@ -69,6 +71,8 @@ import type {
FarmCliOptions,
Format,
HmrOptions,
ModuleContext,
ModuleNode,
NormalizedServerConfig,
ResolvedCompilation,
ResolvedUserConfig,
Expand Down Expand Up @@ -909,8 +913,9 @@ export async function resolvePlugins(
) {
const { jsPlugins: rawJsPlugins, rustPlugins } =
await resolveFarmPlugins(userConfig);
const jsPlugins = await resolveAndFilterAsyncPlugins(rawJsPlugins);

const jsPlugins = (await resolveAndFilterAsyncPlugins(rawJsPlugins)).map(
wrapPluginUpdateModules
);
const vitePlugins = (userConfig?.vitePlugins ?? []).filter(Boolean);

const vitePluginAdapters = vitePlugins.length
Expand Down Expand Up @@ -1109,3 +1114,41 @@ function getNamespaceName(rootPath: string) {
}
return FARM_DEFAULT_NAMESPACE;
}

function wrapPluginUpdateModules(plugin: JsPlugin): JsPlugin {
if (!plugin.updateModules?.executor) {
return plugin;
}
const originalExecutor = plugin.updateModules.executor;
const moduleGraph = new ViteModuleGraphAdapter(plugin.name);

plugin.updateModules.executor = async ({ paths }, ctx) => {
moduleGraph.context = ctx;
for (const [file, type] of paths) {
const mods = moduleGraph.getModulesByFile(
file
) as unknown as ModuleNode[];

const filename = normalizePath(file);
const moduleContext: ModuleContext = {
file: filename,
timestamp: Date.now(),
type,
paths,
modules: (mods ?? []).map(
(m) =>
({
...m,
id: normalizePath(m.id),
file: normalizePath(m.file)
}) as ModuleNode
),
read: function (): string | Promise<string> {
return readFile(file, 'utf-8');
}
};
return originalExecutor.call(plugin, moduleContext);
}
};
return plugin;
}
19 changes: 19 additions & 0 deletions packages/core/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,22 @@ export type EnvResult = Record<
`$__farm_regex:(global(This)?\\.)?process\\.env\\.${string}`,
string
>;

export interface ModuleNode {
url: string;
/**
* Resolved file system path + query
*/
id: string | null;
file: string | null;
type: 'js' | 'css';
}

export interface ModuleContext {
file: string;
timestamp: number;
type: string;
modules: ModuleNode[];
paths: string[];
read: (file: string) => string | Promise<string>;
}
14 changes: 13 additions & 1 deletion packages/core/src/plugin/js/js-plugin-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ const CallbackSchemaNotArgs = z
.function()
.returns(z.union([z.void(), z.promise(z.void())]));

const updateModulesCallbackSchema = z
.function()
.returns(
z.union([
z.array(z.any()),
z.promise(z.array(z.any())),
z.void(),
z.promise(z.void())
])
)
.optional();

// name schema
export const nameSchema = z.string().min(1);

Expand Down Expand Up @@ -469,7 +481,7 @@ export const createUpdateFinishedSchema = (name: string) => {
export const createUpdateModulesSchema = (name: string) => {
return z
.object({
executor: CallbackSchemaNotArgs
executor: updateModulesCallbackSchema
})
.refine(
(data) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/plugin/js/vite-plugin-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,7 @@ export class VitePluginAdapter implements JsPlugin {
const mods = moduleGraph.getModulesByFile(
file
) as unknown as ModuleNode[];

const filename = normalizePath(file);
const ctx: HmrContext = {
file: filename,
Expand All @@ -641,7 +642,6 @@ export class VitePluginAdapter implements JsPlugin {
},
server: this._viteDevServer as unknown as ViteDevServer
};
console.log(ctx.modules);

const updateMods: ModuleNode[] = await hook?.(ctx);

Expand Down
13 changes: 8 additions & 5 deletions packages/core/src/plugin/type.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Compiler, ResolvedUserConfig, Server, UserConfig } from '../index.js';
import {
Compiler,
ModuleContext,
ResolvedUserConfig,
Server,
UserConfig
} from '../index.js';

import {
Config,
Expand Down Expand Up @@ -249,10 +255,7 @@ export interface JsPlugin {
updateFinished?: { executor: Callback<Record<string, never>, void> };

updateModules?: {
executor: Callback<
{ paths: [string, string][] },
string[] | undefined | null | void
>;
executor: Callback<ModuleContext, string[] | undefined | null | void>;
};
}

Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/server/hmr-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class HmrEngine {
if (this._updateQueue.length > 0) {
await this.recompileAndSendResult();
}
if (this.app.resolvedUserConfig?.server.writeToDisk) {
if (this.app.config?.server.writeToDisk) {
this.app.compiler.writeResourcesToDisk();
}
});
Expand Down Expand Up @@ -180,9 +180,7 @@ export class HmrEngine {
{
type: 'error',
err: ${errorStr},
overlay: ${
(this.app.resolvedUserConfig.server.hmr as HmrOptions).overlay
}
overlay: ${(this.app.config.server.hmr as HmrOptions).overlay}
}
`);
});
Expand Down
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading