minify-html/src/unit/script.rs

53 lines
1.8 KiB
Rust
Raw Normal View History

use crate::err::ProcessingResult;
2020-01-25 02:04:02 -05:00
use crate::proc::MatchAction::*;
use crate::proc::MatchMode::*;
use crate::proc::{Processor, JsMinSection};
use crate::cfg::Cfg;
2020-07-11 08:52:27 -04:00
#[cfg(feature = "js-esbuild")]
use crate::proc::checkpoint::Checkpoint;
use esbuild_rs::{TransformOptionsBuilder, TransformOptions};
use std::sync::Arc;
use lazy_static::lazy_static;
lazy_static! {
static ref TRANSFORM_OPTIONS: Arc<TransformOptions> = {
let mut builder = TransformOptionsBuilder::new();
builder.minify_identifiers = true;
builder.minify_syntax = true;
builder.minify_whitespace = true;
builder.build()
};
}
pub fn process_script(proc: &mut Processor, cfg: &Cfg) -> ProcessingResult<()> {
2020-07-11 08:20:17 -04:00
#[cfg(feature = "js-esbuild")]
2020-07-11 08:52:27 -04:00
let start = Checkpoint::new(proc);
loop {
proc.require_not_at_end()?;
// Use fast memchr. Unfortunately all characters in "</script>" are common in JS code.
proc.m(WhileNotChar(b'<'), Keep);
// `process_tag` will require closing tag.
if proc.m(IsSeq(b"</script"), MatchOnly).nonempty() {
#[cfg(feature = "js-esbuild")]
if cfg.minify_js {
let (wg, results) = proc.new_script_section();
2020-07-11 08:52:27 -04:00
let src_range = start.written_range(proc);
// TODO Optimise: Avoid copying to new Vec.
let src = Arc::new(proc[src_range].to_vec());
esbuild_rs::transform(src, TRANSFORM_OPTIONS.clone(), move |result| {
results.lock().unwrap().push(JsMinSection {
src_range,
result,
});
drop(wg);
});
return Ok(());
2020-07-11 08:52:27 -04:00
};
break;
};
2020-07-11 08:52:27 -04:00
// Consume '<'.
proc.accept_expect();
};
Ok(())
}