|
| 1 | +#[macro_use] |
| 2 | +extern crate tracing; |
| 3 | + |
| 4 | +use anyhow::{anyhow, Result}; |
| 5 | +use bytes::Bytes; |
| 6 | +use deno_emit::{ |
| 7 | + bundle, BundleOptions, BundleType, EmitOptions, LoadFuture, LoadOptions, Loader, |
| 8 | + ModuleSpecifier, SourceMapOption, TranspileOptions, |
| 9 | +}; |
| 10 | +use deno_graph::source::LoadResponse; |
| 11 | +use url::Url; |
| 12 | + |
| 13 | +pub struct JavaScriptLoader { |
| 14 | + root: Option<Bytes>, |
| 15 | +} |
| 16 | + |
| 17 | +impl JavaScriptLoader { |
| 18 | + pub fn new(root: Option<Bytes>) -> Self { |
| 19 | + Self { root } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl Loader for JavaScriptLoader { |
| 24 | + fn load(&self, specifier: &ModuleSpecifier, _options: LoadOptions) -> LoadFuture { |
| 25 | + let root = self.root.clone(); |
| 26 | + let specifier = specifier.clone(); |
| 27 | + |
| 28 | + debug!("Attempting to load '{}'", specifier); |
| 29 | + |
| 30 | + Box::pin(async move { |
| 31 | + match specifier.scheme() { |
| 32 | + "usuba" => { |
| 33 | + debug!("Usuba!"); |
| 34 | + Ok(Some(LoadResponse::Module { |
| 35 | + content: root |
| 36 | + .ok_or_else(|| { |
| 37 | + anyhow!("Attempted to load root module, but no root was specified!") |
| 38 | + })? |
| 39 | + .to_vec() |
| 40 | + .into(), |
| 41 | + specifier, |
| 42 | + maybe_headers: None, |
| 43 | + })) |
| 44 | + } |
| 45 | + "common" => { |
| 46 | + debug!("Common!"); |
| 47 | + Ok(Some(LoadResponse::External { |
| 48 | + specifier: specifier.clone(), |
| 49 | + })) |
| 50 | + } |
| 51 | + "https" => { |
| 52 | + debug!("Https!"); |
| 53 | + let response = reqwest::get(specifier.clone()).await?; |
| 54 | + let headers = response.headers().to_owned(); |
| 55 | + let bytes = response.bytes().await?; |
| 56 | + let content = bytes.to_vec().into(); |
| 57 | + |
| 58 | + trace!("Loaded remote module: {}", String::from_utf8_lossy(&bytes)); |
| 59 | + Ok(Some(LoadResponse::Module { |
| 60 | + content, |
| 61 | + specifier, |
| 62 | + maybe_headers: Some( |
| 63 | + headers |
| 64 | + .into_iter() |
| 65 | + .filter_map(|(h, v)| { |
| 66 | + h.map(|header| { |
| 67 | + ( |
| 68 | + header.to_string(), |
| 69 | + v.to_str().unwrap_or_default().to_string(), |
| 70 | + ) |
| 71 | + }) |
| 72 | + }) |
| 73 | + .collect(), |
| 74 | + ), |
| 75 | + })) |
| 76 | + } |
| 77 | + "node" | "npm" => Err(anyhow!( |
| 78 | + "Could not import '{specifier}'. Node.js and NPM modules are not supported." |
| 79 | + )), |
| 80 | + _ => Err(anyhow!( |
| 81 | + "Could not import '{specifier}'. Unrecognize specifier format.'" |
| 82 | + )), |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +pub struct JavaScriptBundler {} |
| 89 | + |
| 90 | +impl JavaScriptBundler { |
| 91 | + fn bundle_options() -> BundleOptions { |
| 92 | + BundleOptions { |
| 93 | + bundle_type: BundleType::Module, |
| 94 | + transpile_options: TranspileOptions::default(), |
| 95 | + emit_options: EmitOptions { |
| 96 | + source_map: SourceMapOption::None, |
| 97 | + source_map_file: None, |
| 98 | + inline_sources: false, |
| 99 | + remove_comments: true, |
| 100 | + }, |
| 101 | + emit_ignore_directives: false, |
| 102 | + minify: false, |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + pub async fn bundle_url(url: Url) -> Result<String> { |
| 107 | + let mut loader = JavaScriptLoader::new(None); |
| 108 | + let emit = bundle(url, &mut loader, None, Self::bundle_options()).await?; |
| 109 | + Ok(emit.code) |
| 110 | + } |
| 111 | + |
| 112 | + pub async fn bundle_module(module: Bytes) -> Result<String> { |
| 113 | + let mut loader = JavaScriptLoader::new(Some(module)); |
| 114 | + let emit = bundle( |
| 115 | + Url::parse("usuba:root")?, |
| 116 | + &mut loader, |
| 117 | + None, |
| 118 | + Self::bundle_options(), |
| 119 | + ) |
| 120 | + .await?; |
| 121 | + Ok(emit.code) |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +#[cfg(test)] |
| 126 | +pub mod tests { |
| 127 | + use anyhow::Result; |
| 128 | + use url::Url; |
| 129 | + |
| 130 | + use crate::JavaScriptBundler; |
| 131 | + |
| 132 | + #[tokio::test] |
| 133 | + async fn it_loads_a_module_from_esm_sh() -> Result<()> { |
| 134 | + let candidate = Url::parse("https://esm.sh/canvas-confetti@1.6.0")?; |
| 135 | + let bundle = JavaScriptBundler::bundle_url(candidate).await?; |
| 136 | + |
| 137 | + assert!(bundle.len() > 0); |
| 138 | + |
| 139 | + Ok(()) |
| 140 | + } |
| 141 | + |
| 142 | + #[tokio::test] |
| 143 | + async fn it_loads_a_module_from_deno_land() -> Result<()> { |
| 144 | + let candidate = Url::parse("https://deno.land/x/zod@v3.16.1/mod.ts")?; |
| 145 | + let bundle = JavaScriptBundler::bundle_url(candidate).await?; |
| 146 | + |
| 147 | + assert!(bundle.len() > 0); |
| 148 | + |
| 149 | + Ok(()) |
| 150 | + } |
| 151 | + |
| 152 | + #[tokio::test] |
| 153 | + async fn it_can_bundle_a_module_file() -> Result<()> { |
| 154 | + let candidate = format!( |
| 155 | + r#"export * from "https://esm.sh/canvas-confetti@1.6.0"; |
| 156 | +"# |
| 157 | + ); |
| 158 | + let bundle = JavaScriptBundler::bundle_module(candidate.into()).await?; |
| 159 | + |
| 160 | + assert!(bundle.len() > 0); |
| 161 | + |
| 162 | + Ok(()) |
| 163 | + } |
| 164 | + |
| 165 | + #[tokio::test] |
| 166 | + async fn it_skips_common_modules_when_bundling() -> Result<()> { |
| 167 | + let candidate = format!( |
| 168 | + r#" |
| 169 | +import {{ read, write }} from "common:io/state@0.0.1"; |
| 170 | +
|
| 171 | +// Note: must use imports else they are tree-shaken |
| 172 | +// Caveat: cannot re-export built-ins as it provokes bundling |
| 173 | +console.log(read, write); |
| 174 | +"# |
| 175 | + ); |
| 176 | + |
| 177 | + let bundle = JavaScriptBundler::bundle_module(candidate.into()) |
| 178 | + .await |
| 179 | + .map_err(|error| { |
| 180 | + error!("{}", error); |
| 181 | + error |
| 182 | + }) |
| 183 | + .unwrap(); |
| 184 | + |
| 185 | + debug!("{bundle}"); |
| 186 | + |
| 187 | + assert!(bundle.contains("import { read, write } from \"common:io/state@0.0.1\"")); |
| 188 | + |
| 189 | + Ok(()) |
| 190 | + } |
| 191 | +} |
0 commit comments