|
| 1 | +use js_sys::{Array, JsString}; |
| 2 | +use wasm_bindgen::prelude::*; |
| 3 | +use web_sys::{Blob, BlobPropertyBag, Url}; |
| 4 | + |
| 5 | +// This is a not-so-clean approach to get the current bindgen ES module URL |
| 6 | +// in Rust. This will fail at run time on bindgen targets not using ES modules. |
| 7 | +#[wasm_bindgen] |
| 8 | +extern "C" { |
| 9 | + #[wasm_bindgen] |
| 10 | + type ImportMeta; |
| 11 | + |
| 12 | + #[wasm_bindgen(method, getter)] |
| 13 | + fn url(this: &ImportMeta) -> JsString; |
| 14 | + |
| 15 | + #[wasm_bindgen(js_namespace = import, js_name = meta)] |
| 16 | + static IMPORT_META: ImportMeta; |
| 17 | +} |
| 18 | + |
| 19 | +pub fn on_the_fly(code: &str) -> Result<String, JsValue> { |
| 20 | + // Generate the import of the bindgen ES module, assuming `--target web`: |
| 21 | + let header = format!( |
| 22 | + "import init, * as bindgen from '{}';\n\n", |
| 23 | + IMPORT_META.url(), |
| 24 | + ); |
| 25 | + |
| 26 | + Url::create_object_url_with_blob(&Blob::new_with_str_sequence_and_options( |
| 27 | + &Array::of2(&JsValue::from(header.as_str()), &JsValue::from(code)), |
| 28 | + &BlobPropertyBag::new().type_("text/javascript"), |
| 29 | + )?) |
| 30 | +} |
| 31 | + |
| 32 | +// dependent_module! takes a local file name to a JS module as input and |
| 33 | +// returns a URL to a slightly modified module in run time. This modified module |
| 34 | +// has an additional import statement in the header that imports the current |
| 35 | +// bindgen JS module under the `bindgen` alias, and the separate init function. |
| 36 | +// How this URL is produced does not matter for the macro user. on_the_fly |
| 37 | +// creates a blob URL in run time. A better, more sophisticated solution |
| 38 | +// would add wasm_bindgen support to put such a module in pkg/ during build time |
| 39 | +// and return a URL to this file instead (described in #3019). |
| 40 | +#[macro_export] |
| 41 | +macro_rules! dependent_module { |
| 42 | + ($file_name:expr) => { |
| 43 | + crate::dependent_module::on_the_fly(include_str!($file_name)) |
| 44 | + }; |
| 45 | +} |
0 commit comments