Skip to content

Commit

Permalink
feat: improve rs plugin and js hooks (#855)
Browse files Browse the repository at this point in the history
* feat: more js hooks

* docs: update docs/config.md

* chore: code style

* chore: code style

* docs: update

* chore: on_generate_file > _on_generate_file

* chore: code style
  • Loading branch information
sorrycc authored Jan 11, 2024
1 parent 1e9dcdf commit c1dbfbf
Show file tree
Hide file tree
Showing 17 changed files with 508 additions and 335 deletions.
1 change: 1 addition & 0 deletions crates/mako/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ impl Compiler {
pub fn build(&self) -> Result<()> {
debug!("build");
let t_build = Instant::now();
self.context.plugin_driver.build_start(&self.context)?;
let entries: Vec<&PathBuf> = self.context.config.entry.values().collect();
let tasks = entries
.iter()
Expand Down
22 changes: 18 additions & 4 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
use std::time::{Instant, UNIX_EPOCH};

use mako_core::anyhow::{anyhow, Error, Result};
use mako_core::colored::Colorize;
Expand All @@ -16,7 +16,7 @@ use crate::comments::Comments;
use crate::config::{hash_config, Config, OutputMode};
use crate::module_graph::ModuleGraph;
use crate::optimize_chunk::OptimizeChunksInfo;
use crate::plugin::{Plugin, PluginDriver};
use crate::plugin::{Plugin, PluginDriver, PluginGenerateEndParams, PluginGenerateStats};
use crate::plugins;
use crate::plugins::minifish::Inject;
use crate::resolve::{get_resolvers, Resolvers};
Expand Down Expand Up @@ -361,6 +361,7 @@ impl Compiler {
}

let t_compiler = Instant::now();
let start_time = std::time::SystemTime::now();
let is_prod = self.context.config.mode == crate::config::Mode::Production;
let building_with_message = format!(
"Building with {} for {}...",
Expand All @@ -377,19 +378,32 @@ impl Compiler {
mako_core::mako_profile_scope!("Generate Stage");
self.generate()
};
let t_compiler = t_compiler.elapsed();
let t_compiler_duration = t_compiler.elapsed();
if result.is_ok() {
println!(
"{}",
format!(
"✓ Built in {}",
format!("{}ms", t_compiler.as_millis()).bold()
format!("{}ms", t_compiler_duration.as_millis()).bold()
)
.green()
);
if !self.context.args.watch {
println!("{}", "Complete!".bold());
}
let end_time = std::time::SystemTime::now();
let params = PluginGenerateEndParams {
is_first_compile: true,
time: t_compiler.elapsed().as_millis() as u64,
stats: PluginGenerateStats {
start_time: start_time.duration_since(UNIX_EPOCH).unwrap().as_millis() as u64,
end_time: end_time.duration_since(UNIX_EPOCH).unwrap().as_millis() as u64,
},
};
self.context
.plugin_driver
.generate_end(&params, &self.context)
.unwrap();
Ok(())
} else {
result
Expand Down
15 changes: 15 additions & 0 deletions crates/mako/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use mako_core::tungstenite::Message;
use mako_core::{hyper, hyper_staticfile, hyper_tungstenite, tokio};

use crate::compiler::{Compiler, Context};
use crate::plugin::{PluginGenerateEndParams, PluginGenerateStats};
use crate::watch::Watch;

pub struct DevServer {
Expand Down Expand Up @@ -281,6 +282,20 @@ impl DevServer {
);

let end_time = std::time::SystemTime::now();
let params = PluginGenerateEndParams {
is_first_compile: false,
time: t_compiler.elapsed().as_millis() as u64,
stats: PluginGenerateStats {
start_time: start_time.duration_since(UNIX_EPOCH).unwrap().as_millis() as u64,
end_time: end_time.duration_since(UNIX_EPOCH).unwrap().as_millis() as u64,
},
};
compiler
.context
.plugin_driver
.generate_end(&params, &compiler.context)
.unwrap();
// TODO: remove this?
callback(OnDevCompleteParams {
is_first_compile: false,
time: t_compiler.elapsed().as_millis() as u64,
Expand Down
43 changes: 43 additions & 0 deletions crates/mako/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ pub struct PluginDepAnalyzeParam<'a> {
pub ast: &'a ModuleAst,
}

#[derive(Clone)]
pub struct PluginGenerateEndParams {
pub is_first_compile: bool,
pub time: u64,
pub stats: PluginGenerateStats,
}

#[derive(Clone)]
pub struct PluginGenerateStats {
pub start_time: u64,
pub end_time: u64,
}

pub trait Plugin: Any + Send + Sync {
fn name(&self) -> &str;

Expand Down Expand Up @@ -101,6 +114,18 @@ pub trait Plugin: Any + Send + Sync {
Ok(None)
}

fn build_start(&self, _context: &Arc<Context>) -> Result<Option<()>> {
Ok(None)
}

fn generate_end(
&self,
_params: &PluginGenerateEndParams,
_context: &Arc<Context>,
) -> Result<Option<()>> {
Ok(None)
}

fn runtime_plugins(&self, _context: &Arc<Context>) -> Result<Vec<String>> {
Ok(Vec::new())
}
Expand Down Expand Up @@ -224,6 +249,24 @@ impl PluginDriver {
Err(anyhow!("None of the plugins generate content"))
}

pub fn build_start(&self, context: &Arc<Context>) -> Result<Option<()>> {
for plugin in &self.plugins {
plugin.build_start(context)?;
}
Ok(None)
}

pub fn generate_end(
&self,
param: &PluginGenerateEndParams,
context: &Arc<Context>,
) -> Result<Option<()>> {
for plugin in &self.plugins {
plugin.generate_end(param, context)?;
}
Ok(None)
}

pub fn build_success(
&self,
stats: &StatsJsonMap,
Expand Down
92 changes: 92 additions & 0 deletions crates/node/src/js_plugin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use std::sync::{mpsc, Arc};

use crate::threadsafe_function;
use crate::tsfn::{LoadResult, ReadMessage, TsFnHooks, WriteRequest};

pub struct JsPlugin {
pub hooks: TsFnHooks,
}
use mako::compiler::Context;
use mako::load::Content;
use mako::plugin::{Plugin, PluginGenerateEndParams, PluginLoadParam};
use mako_core::anyhow::{anyhow, Result};

impl Plugin for JsPlugin {
fn name(&self) -> &str {
"js_plugin"
}

fn build_start(&self, _context: &Arc<Context>) -> Result<Option<()>> {
if let Some(hook) = &self.hooks.build_start {
let (tx, rx) = mpsc::channel::<napi::Result<()>>();
hook.call(
ReadMessage { message: (), tx },
threadsafe_function::ThreadsafeFunctionCallMode::Blocking,
);
rx.recv()
.unwrap_or_else(|e| panic!("recv error: {:?}", e.to_string()))?;
}
Ok(None)
}

fn load(&self, param: &PluginLoadParam, _context: &Arc<Context>) -> Result<Option<Content>> {
if let Some(hook) = &self.hooks.load {
let (tx, rx) = mpsc::channel::<napi::Result<Option<LoadResult>>>();
hook.call(
ReadMessage {
message: param.task.request.path.clone(),
tx,
},
threadsafe_function::ThreadsafeFunctionCallMode::Blocking,
);
let x = rx
.recv()
.unwrap_or_else(|e| panic!("recv error: {:?}", e.to_string()))?;
if let Some(x) = x {
match x.content_type.as_str() {
"js" => return Ok(Some(Content::Js(x.content))),
"css" => return Ok(Some(Content::Css(x.content))),
_ => return Err(anyhow!("Unsupported content type: {}", x.content_type)),
}
}
}
Ok(None)
}

fn generate_end(
&self,
param: &PluginGenerateEndParams,
_context: &Arc<Context>,
) -> Result<Option<()>> {
if let Some(hook) = &self.hooks.generate_end {
let (tx, rx) = mpsc::channel::<napi::Result<()>>();
hook.call(
ReadMessage {
message: param.clone(),
tx,
},
threadsafe_function::ThreadsafeFunctionCallMode::Blocking,
);
rx.recv()
.unwrap_or_else(|e| panic!("recv error: {:?}", e.to_string()))?;
}
Ok(None)
}

fn before_write_fs(&self, path: &std::path::Path, content: &[u8]) -> Result<()> {
if let Some(hook) = &self.hooks._on_generate_file {
let (tx, rx) = mpsc::channel::<napi::Result<()>>();
hook.call(
WriteRequest {
path: path.to_path_buf(),
content: content.to_vec(),
tx,
},
threadsafe_function::ThreadsafeFunctionCallMode::Blocking,
);
rx.recv()
.unwrap_or_else(|e| panic!("recv error: {:?}", e.to_string()))?;
}
Ok(())
}
}
Loading

0 comments on commit c1dbfbf

Please sign in to comment.