Skip to content

Commit

Permalink
GH-195: Change web_resolve to use new API
Browse files Browse the repository at this point in the history
  • Loading branch information
CMDJojo committed Mar 30, 2023
1 parent 97021f4 commit 4c4d1e0
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 30 deletions.
2 changes: 0 additions & 2 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,7 @@ async fn compile_file(input_file: &Path, output_format: &OutputFormat) -> Compil
}

spawn_blocking(|| {
println!("Waiting");
RECEIVER.get().unwrap().lock().unwrap().blocking_recv();
println!("Got it!");
})
.await
.unwrap();
Expand Down
6 changes: 6 additions & 0 deletions core/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,13 @@ where
pub(crate) fn configure(&mut self, config: Option<Config>) -> Result<bool, CoreError> {
let config = config.unwrap_or_default();
let mut lock = self.package_manager.lock().unwrap();

#[cfg(feature = "native")]
lock.finalize(&self.engine).unwrap();

#[cfg(feature = "web")]
lock.finalize().unwrap();

let arc_mutex = Arc::clone(&self.package_manager);
let missings = lock.get_missing_packages(arc_mutex, &config);
println!("Missings: {:?}", missings);
Expand Down
14 changes: 12 additions & 2 deletions core/src/package_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::str::FromStr;
use std::sync::{Arc, Mutex};

use thiserror::Error;
#[cfg(feature = "native")]
use wasmer::Engine;

use parser::config::{Config, Hide, Import, ImportConfig};
Expand Down Expand Up @@ -35,14 +36,23 @@ impl PackageManager {
self.external_packages = Default::default();
}

//noinspection RsUnreachableCode
// Might want to change this to Vec<CoreError>?
pub fn finalize(&mut self, engine: &Engine) -> Result<(), CoreError> {
pub fn finalize(
&mut self,
#[cfg(feature = "native")] engine: &Engine,
) -> Result<(), CoreError> {
// First, get all successful fetches and add them to external_packages, propagating any
// error when creating the package itself
let result: Vec<(PackageID, Package)> = self
.new_packages
.drain()
.map(|(k, v)| Package::new(v.as_slice(), engine).map(|p| (k, p)))
.map(|(k, v)| {
#[cfg(feature = "native")]
return Package::new(v.as_slice(), engine).map(|p| (k, p));
#[cfg(feature = "web")]
return Package::new(v.as_slice()).map(|p| (k, p));
})
.collect::<Result<Vec<_>, _>>()?;

for (package_name, package) in result {
Expand Down
2 changes: 1 addition & 1 deletion playground/web_bindings/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ wasm-bindgen = "0.2.84"
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.6" }
serde = { version = "1.0.152", features = ["derive"] }
serde = { version = "1.0.152", features = ["derive", "rc"] }
serde_json = "1.0.93"
js-sys = "0.3.61"
wasm-bindgen-futures = "0.4.34"
Expand Down
13 changes: 10 additions & 3 deletions playground/web_bindings/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::cell::RefCell;

use modmark_core::{Context, CoreError, DenyAllResolver, eval, eval_no_document, OutputFormat};
use modmark_core::{Context, CoreError, eval, eval_no_document, OutputFormat};
use parser::ParseError;
use serde::Serialize;
use thiserror::Error;
Expand All @@ -20,6 +20,8 @@ pub enum PlaygroundError {
Core(#[from] CoreError),
#[error("Failed to parse")]
Parsing(#[from] ParseError),
#[error("No result")]
NoResult,
}

impl From<PlaygroundError> for JsValue {
Expand All @@ -31,6 +33,9 @@ impl From<PlaygroundError> for JsValue {
PlaygroundError::Parsing(error) => {
JsValue::from_str(&format!("<p>{error}</p><pre>{error:#?}</pre>"))
}
PlaygroundError::NoResult => {
JsValue::from_str(&format!("<p>{error}</p><pre>No result</pre>"))
}
}
}
}
Expand Down Expand Up @@ -60,7 +65,8 @@ pub fn transpile(source: &str, format: &str) -> Result<String, PlaygroundError>
let result = CONTEXT.with(|ctx| {
let mut ctx = ctx.borrow_mut();
eval(source, &mut ctx, &OutputFormat::new(format))
})?;
})?
.ok_or(PlaygroundError::NoResult)?;

let warnings = result
.1
Expand Down Expand Up @@ -88,7 +94,8 @@ pub fn transpile_no_document(source: &str, format: &str) -> Result<String, Playg
let result = CONTEXT.with(|ctx| {
let mut ctx = ctx.borrow_mut();
eval_no_document(source, &mut ctx, &OutputFormat::new(format))
})?;
})?
.ok_or(PlaygroundError::NoResult)?;

let warnings = result
.1
Expand Down
43 changes: 21 additions & 22 deletions playground/web_bindings/src/web_resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use std::sync::{Arc, Mutex};
use std::task::Poll;

use js_sys::{ArrayBuffer, Date, Map, Object, Uint8Array};
use modmark_core::Resolve;
use modmark_core::package_manager::{PackageID, PackageSource, ResolveTask};
use modmark_core::package_manager::Resolve;
use thiserror::Error;
use wasm_bindgen::JsValue;
use wasm_bindgen::prelude::*;
Expand All @@ -19,29 +20,27 @@ pub struct WebResolve;
pub struct FetchError(String);

impl Resolve for WebResolve {
type Error = FetchError;

fn resolve(&self, path: &str) -> Result<Vec<u8>, Self::Error> {
web_sys::console::log_1(&("Making request".into()));
let x = fetch_and_send_all(&vec![path]).pop().unwrap();
web_sys::console::log_1(&("DONE!!!".into()));
x

/*if path.starts_with("https://") {
spawn_fetcher_and_loader(path)
} else {
web_sys::console::log_1(&("Can only fetch HTTPS packages atm".into()));
Ok(vec![])
}*/
fn resolve_all(&self, paths: Vec<ResolveTask>) {
paths.into_iter().for_each(resolve);
}
}

fn resolve_all(&self, paths: &[&str]) -> Vec<Result<Vec<u8>, Self::Error>> {
paths.iter().map(|url| spawn_fetcher_and_loader(url)).collect()

/*web_sys::console::log_1(&("Making request".into()));
let x = fetch_and_send_all(paths);
web_sys::console::log_1(&("DONE!!!".into()));
x*/
#[derive(Error, Debug)]
#[error("Web resolve err: {0:?}")]
pub struct WebResolveErr(String);

pub fn resolve(task: ResolveTask) {
let target = task.package.target.clone();
match target {
PackageSource::Local => { todo!() }
PackageSource::Registry => { todo!() }
PackageSource::Url => {
spawn_local(async move {
let result = fetch_bytes(&task.package.name).await
.map_err(|e| WebResolveErr(e.js_typeof().as_string().unwrap()));
task.complete(result);
});
}
}
}

Expand Down

0 comments on commit 4c4d1e0

Please sign in to comment.