How to load a npm package to wasm_bindgen - rust

I tried searching internet, couldn't find details how can I load a npm package to yew.
I am trying to load #polkadot/extension-dapp ( code docs)
#[wasm_bindgen(module = "/node_modules/#polkadot/extension-dapp/index.js")]
extern "C" {
#[wasm_bindgen]
pub fn web3Enable(originName: String) -> JsValue;
}
It gives error:
Uncaught TypeError: Failed to resolve module specifier "#polkadot/util". Relative references must start with either "/", "./", or "../".

Related

oxipng throwing RuntimeError: unreachable when called

I'm trying to create a small WASM project for image compression.
After some search in github, I noticed that oxipng 2.2.2 has a target for wasm32-unknown-unknown, hence why I'm using that.
I'm using wasm-pack for creating the wasm file + JS bindings with target -t web
This is the code:
extern crate oxipng;
mod utils;
use std::error::Error;
use wasm_bindgen::prelude::*;
use oxipng::*;
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
// Next let's define a macro that's like `println!`, only it works for
// `console.log`. Note that `println!` doesn't actually work on the wasm target
// because the standard library currently just eats all output. To get
// `println!`-like behavior in your app you'll likely want a macro like this.
#[macro_export]
macro_rules! console_log {
// Note that this is using the `log` function imported above during
// `bare_bones`
($($t:tt)*) => (crate::log(&format_args!($($t)*).to_string()))
}
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn compress(data: &[u8]) -> Vec<u8> {
console_log!("{}", data.len());
let opts = Options::from_preset(6);
console_log!("after options");
let res = match optimize_from_memory(data, &&opts) {
Ok(res) => Ok(res),
Err(err) => Err(err),
};
match &res {
Ok(_) => console_log!("Optimized"),
Err(err) => console_log!("Error: {}", err),
}
return res.unwrap();
}
I don't ever get an error message, the last log I have is "after options".
In a nutshell, I'm using a Flutter web application that gets a PNG file, converts it into a Uint8List, and I send it as an integer List to the JS bindings.
When called, the following error happens:
RuntimeError: unreachable
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[1019]:0x5c6be
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[414]:0x4cd37
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[619]:0x54c96
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[915]:0x5b4ba
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[986]:0x5c139
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[645]:0x55885
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[569]:0x5324b
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[594]:0x53ff1
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[2]:0x554f
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[84]:0x2cbf2
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[73]:0x2a501
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[563]:0x52eaa
at compress (http://localhost:3000/pkg/rust_png_module.js:49:14)
at compressImage (http://localhost:3000/packages/rust_wasm/ui/screens/home/home_page.dart.lib.js:568:72)
at compressImage.next (<anonymous>)
at http://localhost:3000/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:3000/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:3000/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:3000/dart_sdk.js:34265:49)
at Function._propagateToListeners (http://localhost:3000/dart_sdk.js:34303:17)
at _Future.new.[_completeWithValue] (http://localhost:3000/dart_sdk.js:34151:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:3000/dart_sdk.js:34172:35)
at Object._microtaskLoop (http://localhost:3000/dart_sdk.js:38778:13)
at _startMicrotaskLoop (http://localhost:3000/dart_sdk.js:38784:13)
at http://localhost:3000/dart_sdk.js:34519:9
Since this version is old, I don't know if I should revert back to an older version of Rust
$ rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.55.0 (c8dfcfe04 2021-09-06)`
Thank you in advance
The problem is you're using a very old version of oxipng (v2.2.2) that didn't support wasm yet. I believe wasm support was added in v2.3.0 (link to issue that was fixed). Anyways, you should be able to use the latest version just fine with wasm, just make sure you disable the default features when adding the crate to your Cargo.toml:
[dependencies]
oxipng = { version = "5", default-features = false }

How to fix v8 deprecated GetFunction?

I'm trying to repair node-osmium so that it works with Node 12 as I've got some old code I'd like to run.
v8 has now fully deprecated a lot of APIs that do not signal failure properly. These were previously only warnings of deprecation soon, they're now errors so it will no longer build. I (think I've) fixed most of these by following this CPP STYLE GUIDE.md's use maybe version of v8 APIs section.
But, i'm stuck with this error for GetFunction:
../src/utils.hpp:39:67: error: no matching function for call to ‘v8::FunctionTemplate::GetFunction()’
Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::New(T::constructor)->GetFunction(), 1, &ext);
I assume it's a similar fix as the other functions, but where do I get the context from in this constructor?
extract from node-osmium/src/utils.hpp:
namespace node_osmium {
template<class T>
auto unwrap(const v8::Local<v8::Object>& object) -> decltype(Nan::ObjectWrap::Unwrap<T>(object)->get()) {
return Nan::ObjectWrap::Unwrap<T>(object)->get();
}
template<class T, class... Args>
v8::Local<v8::Object> new_external(Args&&... args) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Value> ext = Nan::New<v8::External>(new T(std::forward<Args>(args)...));
Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::New(T::constructor)->GetFunction(context), 1, &ext);
if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Buffer instance");
return scope.Escape(maybe_local.ToLocalChecked());
}
v8::Local<v8::Value> create_js_box(const osmium::Box& box);
osmium::osm_entity_bits::type object_to_entity_bits(v8::Local<v8::Object> options);
} // namespace node_osmium

Python/C++ extension. On import, I get an undefined symbol error

My setup.py and UserMethods.cpp file are below.
My issue is this: I am trying to create and install a python package using distutils and I am running into some issues.
When I run python3 setup.py install --user there is no issue. It compiles and creates a build/ directory with a file named lib.linux-x86_64-3.6. When I check my .local/lib/python3.6/site-pacages directory, there is a file named UserMethods.cpython-36m-x86_64-linux-gnu.so.
The issue comes when I try to import the package:
$ python3
>>> import UserMethods
which returns the following error:
ImportError: ~/.local/lib/python3.6/site-packages/UserMethods.cpython-36m-x86_64-linux-gnu.so: undefined symbol: _ZN12NA62Analysis4Core18AnalyzerIdentifierD1Ev
I do not know how or where such a symbol would be defined or why it would be created. Does anyone have insight as to where this error is coming from? Thanks in advance.
EDIT:
here is the setup.py file:
from distutils.core import setup, Extension
UM_module = Extension('UserMethods', sources=['UserMethodsModule.cpp'], language='C++',
include_dirs=[ ...many... ],
extra_compile_args=['-std=c++11'],
libraries=['stdc++'],)
setup(name='UserMethods',
version='1.0',
ext_modules=[UM_module],
)
and here is my UserMethods.cpp file:
#include <Python.h>
#define PY_SSIZE_T_CLEAN
#include "UserMethods.hh"
/* OUR FUNCTIONS GO HERE */
static PyObject* UM_test(PyObject *self, PyObject *args){
const char *command;
int sts;
if ( !PyArg_ParseTuple(args, "s", &command) ){
return NULL;
}
sts = system(command);
return PyLong_FromLong(sts);
}
static PyMethodDef UserMethods[] = {
{"system", UM_test, METH_VARARGS, "execute shell command."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef UserMethodsModule = {
PyModuleDef_HEAD_INIT,
"UserMethods",
NULL,
-1,
UserMethods
};
PyMODINIT_FUNC PyInit_UserMethods(void){
return PyModule_Create(&UserMethodsModule);
}
as per #Holt above, this error was caused by not importing the library that contains the type definition in the error.
I had to add the path to the library in my linking step, which I added to the 'extra_link_args' argument in the Extension function call in Setup.py.

"could not rename crate" when compiling a basic example of rustless on Windows

I'm trying to build rustless on Windows:
This is my Cargo.toml:
[dependencies.rustless]
git = "https://github.com/rustless/rustless"
[package]
name = "ccampo_substancias_srv"
version = "0.0.1"
authors = [ "------------------------------" ]
[[bin]]
name = "Rest_test"
This is main.rs:
#![feature(plugin)]
#[plugin]
extern crate rustless;
extern crate hyper;
extern crate iron;
extern crate "rustc-serialize" as rustc_serialize;
extern crate valico;
use hyper::status::StatusCode;
use iron::Iron;
use rustless::{
Application, Api, Nesting, Versioning
};
use rustc_serialize::json::ToJson;
fn main() {
let api = Api::build(dsl!(|api| {
// Specify API version
version("v1", Versioning::AcceptHeader("chat"));
prefix("api");
// Create API for chats
mount(Api::build(dsl!(|chats_api| {
after(|client, _params| {
client.set_status(StatusCode::NotFound);
Ok(())
});
// Add namespace
namespace("chats/:id", dsl!(|chat_ns| {
// Valico settings for this namespace
params(|params| {
params.req_typed("id", valico::u64())
});
// Create endpoint for POST /chats/:id/users/:user_id
post("users/:user_id", dsl!(|endpoint| {
// Add description
desc("Update user");
// Valico settings for endpoint params
params(|params| {
params.req_typed("user_id", valico::u64());
params.req_typed("name", valico::string())
});
handle(|client, params| {
client.json(&params.to_json())
})
}));
}));
})));
}));
let app = Application::new(api);
Iron::new(app).listen("localhost:4000").unwrap();
println!("On 4000");
println!("Rustless server started!");
}
Building with "cargo build --verbose" and rust 1.5 (64bit) on Windows 10.
This is the error I'm getting, looks like it's related to some file path:
Fresh jsonway v0.3.5
Fresh conduit-mime-types v0.7.3
Fresh winapi v0.2.5
Build failed, waiting for other jobs to finish...
could not rename crate "C:\\Users\\Pedro\\workspace\\ccampo-substancias-srv\\target\\debug\\build\\advapi32-sys-cfef7a1f30f1e5f6\\build_script_build.exe"
Caused by: Acesso negado. (os error 5)
Do you have antivirus/anti-malware software on your computer? It might be trying to analyze your program, locking the file. Try disabling it temporarily or adding an exception on your project directory, then try building again.

Can I import libsyntax in my code?

I want to import the rust lexer in my code
use syntax;
fn main() { () }
but above code fails to compile
error: failed to resolve imports
testparse.rs:1:4: 1:11 error: unresolved import
testparse.rs:1 use syntax;
^~~~~~~
error: aborting due to 2 previous errors
Can I use libsyntax from user code? If I can, how can I import it?
You need to add the library:
extern mod syntax;

Resources