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

Feature/hook config #1108

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
124 changes: 124 additions & 0 deletions packages/cli/src/__tests__/plugins.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { describe, test, expect } from 'vitest';
import { MitosisConfig } from '@builder.io/mitosis';
import { formatHook, runHook } from '../build/build';

const beforeBuild = (c) => {
console.log(`beforeBuild ${c}`);
};
const afterbuild = (c, f) => {
console.log(`afterbuild ${c} ${f}`);
};
const beforeBuildSecond = (c) => {
console.log(`beforeBuildSecond ${c}`);
};
const afterbuildSecond = (c, f) => {
console.log(f);
console.log(`afterbuildSecond ${c} ${f}`);
};

const objPluginConfig = {
plugins: {
order: 1,
beforeBuild,
afterbuild,
},
};
const fnPluginConfig = {
plugins: () => ({
order: 1,
beforeBuild,
afterbuild,
}),
};
const mixPluginConfig = {
plugins: [
() => ({
name: 'second',
order: 2,
beforeBuild: beforeBuildSecond,
afterbuild: afterbuildSecond,
}),
{
name: 'first',
order: 1,
beforeBuild,
afterbuild,
},
],
};

describe('mitosis plugin test', () => {
test('formatHook test objPlugin', () => {
const plugins = formatHook(objPluginConfig as MitosisConfig);
expect(plugins).toEqual([
{
order: 1,
beforeBuild,
afterbuild,
},
]);
});
test('formatHook test fnPlugin', () => {
const plugins = formatHook(fnPluginConfig as MitosisConfig);
expect(plugins).toEqual([
{
order: 1,
beforeBuild,
afterbuild,
},
]);
});
test('formatHook test mixPlugin', () => {
const plugins = formatHook(mixPluginConfig as MitosisConfig);
expect(plugins).toEqual([
{
name: 'first',
order: 1,
beforeBuild,
afterbuild,
},
{
name: 'second',
order: 2,
beforeBuild: beforeBuildSecond,
afterbuild: afterbuildSecond,
},
]);
expect(plugins).not.toEqual([
{
name: 'second',
order: 2,
beforeBuild: beforeBuildSecond,
afterbuild: afterbuildSecond,
},
{
name: 'first',
order: 1,
beforeBuild,
afterbuild,
},
]);
});
test('runHook test', async () => {
const _log = console.log;
const logs = [];
console.log = (str) => {
logs.push(str);
};
const c = { test: 1 };
const f = { test: 2 };
const plugins = formatHook(mixPluginConfig as MitosisConfig);
await runHook('beforeBuild', { plugins } as MitosisConfig)(c);
expect(logs).toEqual([`beforeBuild ${c}`, `beforeBuildSecond ${c}`]);
await runHook('afterbuild', { plugins } as MitosisConfig)(c, f);

expect(logs).toEqual([
`beforeBuild ${c}`,
`beforeBuildSecond ${c}`,
`afterbuild ${c} ${f}`,
f,
`afterbuildSecond ${c} ${f}`,
]);
console.log = _log;
});
});
67 changes: 53 additions & 14 deletions packages/cli/src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ import {
MitosisConfig,
parseJsx,
Target,
TranspilerGenerator,
parseSvelte,
TargetContext,
OutputFiles,
MitosisPlugin,
MitosisPluginFn,
HookType,
} from '@builder.io/mitosis';
import debug from 'debug';
import { flow, pipe } from 'fp-ts/lib/function';
Expand Down Expand Up @@ -69,13 +73,33 @@ const DEFAULT_CONFIG: Partial<MitosisConfig> = {
getTargetPath,
};

export const formatHook = (config?: MitosisConfig): Partial<MitosisPlugin>[] => {
const plugins = config?.plugins;
if (!plugins) return [];

let pluginList = plugins;
if (!Array.isArray(plugins)) {
pluginList = [plugins];
}

return (pluginList as Array<MitosisPluginFn | Partial<MitosisPlugin>>)
.map((plugin) => {
if (typeof plugin === 'function') {
return plugin();
}
return plugin;
})
.sort((a, b) => (a.order || 0) - (b.order || 0));
};

const getOptions = (config?: MitosisConfig): MitosisConfig => ({
...DEFAULT_CONFIG,
...config,
options: {
...DEFAULT_CONFIG.options,
...config?.options,
},
plugins: formatHook(config),
});

async function clean(options: MitosisConfig) {
Expand Down Expand Up @@ -192,12 +216,6 @@ const getMitosisComponentJSONs = async (options: MitosisConfig): Promise<ParsedM
);
};

interface TargetContext {
target: Target;
generator: TranspilerGenerator<MitosisConfig['options'][Target]>;
outputPath: string;
}

interface TargetContextWithConfig extends TargetContext {
options: MitosisConfig;
}
Expand All @@ -216,6 +234,20 @@ const buildAndOutputNonComponentFiles = async (targetContext: TargetContextWithC
return await outputNonComponentFiles({ ...targetContext, files });
};

export function runHook(hook: string, config: MitosisConfig) {
const plugins = config.plugins as Partial<MitosisPlugin>[];
const debugTarget = debug(`mitosis:${hook}`);

return async (...params) => {
for (let plugin of plugins) {
if (!plugin[hook]) continue;
debugTarget(`before run ${plugin.name} ${hook} hook...`);
await plugin[hook](...params);
debugTarget(`run $${plugin.name} ${hook} hook done`);
}
};
}

export async function build(config?: MitosisConfig) {
// merge default options
const options = getOptions(config);
Expand All @@ -227,6 +259,7 @@ export async function build(config?: MitosisConfig) {
const mitosisComponents = await getMitosisComponentJSONs(options);

const targetContexts = getTargetContexts(options);
await runHook(HookType.BeforeBuild, options)(targetContexts);

await Promise.all(
targetContexts.map(async (targetContext) => {
Expand All @@ -238,7 +271,10 @@ export async function build(config?: MitosisConfig) {
buildAndOutputNonComponentFiles({ ...targetContext, options }),
buildAndOutputComponentFiles({ ...targetContext, options, files }),
]);

await runHook(HookType.Afterbuild, options)(targetContext, {
componentFiles: x[1],
nonComponentFiles: x[0],
});
console.info(
`Mitosis: ${targetContext.target}: generated ${x[1].length} components, ${x[0].length} regular files.`,
);
Expand Down Expand Up @@ -326,7 +362,7 @@ async function buildAndOutputComponentFiles({
options,
generator,
outputPath,
}: TargetContextWithConfig & { files: ParsedMitosisJson[] }) {
}: TargetContextWithConfig & { files: ParsedMitosisJson[] }): Promise<OutputFiles[]> {
const debugTarget = debug(`mitosis:${target}`);
const shouldOutputTypescript = checkShouldOutputTypeScript({ options, target });

Expand Down Expand Up @@ -368,6 +404,7 @@ async function buildAndOutputComponentFiles({
const outputDir = `${options.dest}/${outputPath}`;

await outputFile(`${outputDir}/${outputFilePath}`, transpiled);
return { outputDir, outputFilePath };
});
return await Promise.all(output);
}
Expand All @@ -387,13 +424,15 @@ const outputNonComponentFiles = async ({
}: TargetContext & {
files: { path: string; output: string }[];
options: MitosisConfig;
}) => {
}): Promise<OutputFiles[]> => {
const extension = getNonComponentFileExtension({ target, options });
const folderPath = `${options.dest}/${outputPath}`;
const outputDir = `${options.dest}/${outputPath}`;
return await Promise.all(
files.map(({ path, output }) =>
outputFile(`${folderPath}/${path.replace(/\.tsx?$/, extension)}`, output),
),
files.map(async ({ path, output }) => {
const outputFilePath = path.replace(/\.tsx?$/, extension);
await outputFile(`${outputDir}/${outputFilePath}`, output);
return { outputDir, outputFilePath };
}),
);
};

Expand Down
40 changes: 40 additions & 0 deletions packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { MitosisComponent } from './mitosis-component';
import { TranspilerGenerator } from './transpiler';

export type Format = 'esm' | 'cjs';
export type Language = 'js' | 'ts';
Expand All @@ -14,6 +15,37 @@ export type GeneratorOptions = {
};
};

export interface TargetContext {
target: Target;
generator: TranspilerGenerator<NonNullable<MitosisConfig['options'][Target]>>;
outputPath: string;
}

export interface OutputFiles {
outputDir: string;
outputFilePath: string;
}

export interface MitosisPlugin {
name: string;
order: number;
[HookType.BeforeBuild]: (TargetContexts: TargetContext[]) => void | Promise<void>;
[HookType.Afterbuild]: (
TargetContext: TargetContext,
files: {
componentFiles: OutputFiles[];
nonComponentFiles: OutputFiles[];
},
) => void | Promise<void>;
}

export type MitosisPluginFn = () => Partial<MitosisPlugin>;

export enum HookType {
BeforeBuild = 'beforeBuild',
Afterbuild = 'afterbuild',
}

export type MitosisConfig = {
/**
* List of targets to compile to.
Expand Down Expand Up @@ -58,6 +90,14 @@ export type MitosisConfig = {
* ```
*/
options: Partial<GeneratorOptions>;

/**
* hooks
*/
plugins?:
| Partial<MitosisPlugin>
| (() => Partial<MitosisPlugin>)
| Array<Partial<MitosisPlugin> | MitosisPluginFn>;
/**
* Configure a custom parser function which takes a string and returns MitosisJSON
* Defaults to the JSXParser of this project (src/parsers/jsx)
Expand Down