Skip to content

Commit

Permalink
chore: improve
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Dec 20, 2024
1 parent 68bdad8 commit 9356ff3
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 78 deletions.
27 changes: 15 additions & 12 deletions crates/binding/src/js_hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use napi::NapiRaw;
use napi_derive::napi;
use serde_json::Value;

use crate::js_plugin::PluginContext;
use crate::threadsafe_function::ThreadsafeFunction;

#[napi(object)]
Expand Down Expand Up @@ -81,19 +82,21 @@ pub struct JsHooks {
pub transform_include: Option<JsFunction>,
}

type ResolveIdFuncParams = (PluginContext, String, String, ResolveIdParams);

pub struct TsFnHooks {
pub build_start: Option<ThreadsafeFunction<(), ()>>,
pub build_end: Option<ThreadsafeFunction<(), ()>>,
pub write_bundle: Option<ThreadsafeFunction<(), ()>>,
pub generate_end: Option<ThreadsafeFunction<Value, ()>>,
pub load: Option<ThreadsafeFunction<String, Option<LoadResult>>>,
pub load_include: Option<ThreadsafeFunction<String, Option<bool>>>,
pub watch_changes: Option<ThreadsafeFunction<(String, WatchChangesParams), ()>>,
pub resolve_id:
Option<ThreadsafeFunction<(String, String, ResolveIdParams), Option<ResolveIdResult>>>,
pub _on_generate_file: Option<ThreadsafeFunction<WriteFile, ()>>,
pub transform: Option<ThreadsafeFunction<(String, String), Option<TransformResult>>>,
pub transform_include: Option<ThreadsafeFunction<String, Option<bool>>>,
pub build_start: Option<ThreadsafeFunction<PluginContext, ()>>,
pub build_end: Option<ThreadsafeFunction<PluginContext, ()>>,
pub write_bundle: Option<ThreadsafeFunction<PluginContext, ()>>,
pub generate_end: Option<ThreadsafeFunction<(PluginContext, Value), ()>>,
pub load: Option<ThreadsafeFunction<(PluginContext, String), Option<LoadResult>>>,
pub load_include: Option<ThreadsafeFunction<(PluginContext, String), Option<bool>>>,
pub watch_changes: Option<ThreadsafeFunction<(PluginContext, String, WatchChangesParams), ()>>,
pub resolve_id: Option<ThreadsafeFunction<ResolveIdFuncParams, Option<ResolveIdResult>>>,
pub _on_generate_file: Option<ThreadsafeFunction<(PluginContext, WriteFile), ()>>,
pub transform:
Option<ThreadsafeFunction<(PluginContext, String, String), Option<TransformResult>>>,
pub transform_include: Option<ThreadsafeFunction<(PluginContext, String), Option<bool>>>,
}

impl TsFnHooks {
Expand Down
58 changes: 37 additions & 21 deletions crates/binding/src/js_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ use mako::ast::file::{Content, JsContent};
use mako::compiler::Context;
use mako::plugin::{Plugin, PluginGenerateEndParams, PluginLoadParam, PluginResolveIdParams};
use mako::resolve::{ExternalResource, Resolution, ResolvedResource, ResolverResource};
use napi_derive::napi;

use crate::js_hook::{
LoadResult, ResolveIdParams, ResolveIdResult, TransformResult, TsFnHooks,
WatchChangesParams, WriteFile,
LoadResult, ResolveIdParams, ResolveIdResult, TransformResult, TsFnHooks, WatchChangesParams,
WriteFile,
};

fn content_from_result(result: TransformResult) -> Result<Content> {
Expand All @@ -27,6 +28,17 @@ fn content_from_result(result: TransformResult) -> Result<Content> {
}
}

#[napi]
pub struct PluginContext {}

#[napi]
impl PluginContext {
#[napi]
pub fn warn(&self, msg: String) {
println!("WARN: {}", msg)
}
}

pub struct JsPlugin {
pub hooks: TsFnHooks,
pub name: Option<String>,
Expand All @@ -44,27 +56,25 @@ impl Plugin for JsPlugin {

fn build_start(&self, _context: &Arc<Context>) -> Result<()> {
if let Some(hook) = &self.hooks.build_start {
hook.call(())?
hook.call(PluginContext {})?
}
Ok(())
}

fn load(&self, param: &PluginLoadParam, _context: &Arc<Context>) -> Result<Option<Content>> {
if let Some(hook) = &self.hooks.load {
if self.hooks.load_include.is_some()
&& self
.hooks
.load_include
.as_ref()
.unwrap()
.call(param.file.path.to_string_lossy().to_string())?
== Some(false)
&& self.hooks.load_include.as_ref().unwrap().call((
PluginContext {},
param.file.path.to_string_lossy().to_string(),
))? == Some(false)
{
return Ok(None);
}
let x: Option<LoadResult> = hook.call(
let x: Option<LoadResult> = hook.call((
PluginContext {},
param.file.path.to_string_lossy().to_string(),
)?;
))?;
if let Some(x) = x {
return content_from_result(TransformResult {
content: x.content,
Expand All @@ -85,6 +95,7 @@ impl Plugin for JsPlugin {
) -> Result<Option<ResolverResource>> {
if let Some(hook) = &self.hooks.resolve_id {
let x: Option<ResolveIdResult> = hook.call((
PluginContext {},
source.to_string(),
importer.to_string(),
ResolveIdParams {
Expand Down Expand Up @@ -116,17 +127,18 @@ impl Plugin for JsPlugin {
// keep generate_end for compatibility
// since build_end does not have none error params in unplugin's api spec
if let Some(hook) = &self.hooks.generate_end {
hook.call(serde_json::to_value(param)?)?
hook.call((PluginContext {}, serde_json::to_value(param)?))?
}
if let Some(hook) = &self.hooks.build_end {
hook.call(())?
hook.call(PluginContext {})?
}
Ok(())
}

fn watch_changes(&self, id: &str, event: &str, _context: &Arc<Context>) -> Result<()> {
if let Some(hook) = &self.hooks.watch_changes {
hook.call((
PluginContext {},
id.to_string(),
WatchChangesParams {
event: event.to_string(),
Expand All @@ -138,17 +150,20 @@ impl Plugin for JsPlugin {

fn write_bundle(&self, _context: &Arc<Context>) -> Result<()> {
if let Some(hook) = &self.hooks.write_bundle {
hook.call(())?
hook.call(PluginContext {})?
}
Ok(())
}

fn before_write_fs(&self, path: &std::path::Path, content: &[u8]) -> Result<()> {
if let Some(hook) = &self.hooks._on_generate_file {
hook.call(WriteFile {
path: path.to_string_lossy().to_string(),
content: content.to_vec(),
})?;
hook.call((
PluginContext {},
WriteFile {
path: path.to_string_lossy().to_string(),
content: content.to_vec(),
},
))?;
}
Ok(())
}
Expand All @@ -160,7 +175,7 @@ impl Plugin for JsPlugin {
_context: &Arc<Context>,
) -> Result<Option<Content>> {
if let Some(hook) = &self.hooks.transform_include {
if hook.call(path.to_string())? == Some(false) {
if hook.call((PluginContext {}, path.to_string()))? == Some(false) {
return Ok(None);
}
}
Expand All @@ -172,7 +187,8 @@ impl Plugin for JsPlugin {
_ => return Ok(None),
};

let result: Option<TransformResult> = hook.call((content_str, path.to_string()))?;
let result: Option<TransformResult> =
hook.call((PluginContext {}, content_str, path.to_string()))?;

if let Some(result) = result {
return content_from_result(result).map(Some);
Expand Down
3 changes: 3 additions & 0 deletions e2e/fixtures/plugins.context/mako.config.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"plugins": [
"./plugin"
],
"minify": false
}
13 changes: 0 additions & 13 deletions e2e/fixtures/plugins.context/node_modules/plugin/index.js

This file was deleted.

6 changes: 6 additions & 0 deletions e2e/fixtures/plugins.context/plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

module.exports = {
async load(path) {
path.endsWith('.hoo');
}
};
10 changes: 7 additions & 3 deletions e2e/fixtures/plugins.context/plugins.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
module.exports = [
{
async loadInclude(path) {
// this.warn('loadInclude: ' + path);
path.endsWith('.hoo');
return true;
},
async load(path) {
if (path.endsWith('.hoo')) {
console.log('----');
console.log('load', path, this, this.error, this.root);
console.log('----');
// console.log('load', path, this, this.warn);
this.warn('load: ' + path);
return {
content: `export default () => <Foooo>.hoo</Foooo>;`,
type: 'jsx',
Expand Down
2 changes: 0 additions & 2 deletions e2e/fixtures/plugins/node_modules/plugin/index.js

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

3 changes: 3 additions & 0 deletions packages/mako/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,6 @@ export interface BuildParams {
watch: boolean;
}
export declare function build(buildParams: BuildParams): Promise<void>;
export class PluginContext {
warn(msg: string): void;
}
3 changes: 2 additions & 1 deletion packages/mako/binding.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`);
}

const { build } = nativeBinding;
const { PluginContext, build } = nativeBinding;

module.exports.PluginContext = PluginContext;
module.exports.build = build;
39 changes: 18 additions & 21 deletions packages/mako/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,27 +135,6 @@ export async function build(params: BuildParams) {
});
}

// add context to each plugin's hook
params.config.plugins.forEach((plugin: any) => {
Object.keys(plugin).forEach((key) => {
const oldValue = plugin[key];
if (typeof oldValue === 'function') {
plugin[key] = (context: any, ...args: any[]) => {
const c = {
...(context || {}),
// error: (err: any) => {
// console.error(err);
// },
// log: (...args: any[]) => {
// console.log(...args);
// },
};
return oldValue.apply(c, [...args]);
};
}
});
});

// support dump mako config
if (process.env.DUMP_MAKO_CONFIG) {
const configFile = path.join(params.root, 'mako.config.json');
Expand Down Expand Up @@ -206,6 +185,24 @@ export async function build(params: BuildParams) {
);
}
});

// add context to each plugin's hook
plugins.forEach((plugin: any) => {
Object.keys(plugin).forEach((key) => {
const oldValue = plugin[key];
if (typeof oldValue === 'function') {
plugin[key] = (context: any, ...args: any[]) => {
return oldValue.apply(
{
warn: context.warn.bind(context),
},
[...args],
);
};
}
});
});

params.config = omit(params.config, [
'less',
'sass',
Expand Down
5 changes: 0 additions & 5 deletions scripts/mako.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@ build({

function getPlugins() {
let plugins = [];
const hooksPath = path.join(cwd, 'hooks.config.js');
if (fs.existsSync(hooksPath)) {
let hooks = require(hooksPath);
plugins.push(hooks);
}
const pluginsPath = path.join(cwd, 'plugins.config.js');
if (fs.existsSync(pluginsPath)) {
plugins.push(...require(pluginsPath));
Expand Down

0 comments on commit 9356ff3

Please sign in to comment.