Skip to content

Commit

Permalink
fix: A warning will now be emitted when the @wasmer/sdk package is …
Browse files Browse the repository at this point in the history
…loaded outside of a Cross-Origin Isolated context
  • Loading branch information
Michael-F-Bryan committed Dec 13, 2023
1 parent 687c46f commit 4dc5799
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub(crate) static CUSTOM_WORKER_URL: Lazy<Mutex<Option<String>>> = Lazy::new(Mut
pub(crate) const DEFAULT_REGISTRY: &str =
wasmer_wasix::runtime::resolver::WapmSource::WASMER_PROD_ENDPOINT;

const CROSS_ORIGIN_WARNING: &str = r#"This package can only be used from "Cross-Origin Isolated" websites. For more details, check out https://docs.wasmer.io/javascript-sdk/explainers/troubleshooting#sharedarraybuffer-and-cross-origin-isolation"#;

#[wasm_bindgen]
pub fn wat2wasm(wat: String) -> Result<js_sys::Uint8Array, utils::Error> {
let wasm = ::wasmer::wat2wasm(wat.as_bytes())?;
Expand All @@ -49,6 +51,17 @@ pub fn wat2wasm(wat: String) -> Result<js_sys::Uint8Array, utils::Error> {
#[wasm_bindgen(start, skip_typescript)]
fn on_start() {
console_error_panic_hook::set_once();

if let Some(cross_origin_isolated) =
crate::utils::GlobalScope::current().cross_origin_isolated()
{
// Note: This will need to be tweaked when we add support for Deno and
// NodeJS.
web_sys::console::assert_with_condition_and_data_1(
cross_origin_isolated,
&wasm_bindgen::JsValue::from_str(CROSS_ORIGIN_WARNING),
);
}
}

#[wasm_bindgen(js_name = setWorkerUrl)]
Expand Down
15 changes: 15 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,21 @@ impl GlobalScope {
None => false,
}
}

pub fn cross_origin_isolated(&self) -> Option<bool> {
let obj = self.as_object();
js_sys::Reflect::get(obj, &JsValue::from_str("crossOriginIsolated"))
.ok()
.and_then(|obj| obj.as_bool())
}

fn as_object(&self) -> &js_sys::Object {
match self {
GlobalScope::Window(w) => w,
GlobalScope::Worker(w) => w,
GlobalScope::Other(obj) => obj,
}
}
}

/// A wrapper around [`anyhow::Error`] that can be returned to JS to raise
Expand Down

0 comments on commit 4dc5799

Please sign in to comment.