Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chat with pdf ( Work in progress ) #326

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions JS/jsonnet/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,14 @@ fn regex_match(a: String, b: String) -> Vec<String> {
matches
}

fn arakoolib_uncached() -> ObjValue {
fn arakoolib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
let mut builder = ObjValueBuilder::new();
builder.method(
"native",
builtin_native {
settings: settings.clone(),
},
);
builder.method("join", join::INST);
builder.method("regexMatch", regex_match::INST);
builder.build()
Expand All @@ -62,6 +68,18 @@ fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {
Source::new_virtual(source_name.into(), code.into())
}

#[builtin(fields(
settings: Rc<RefCell<Settings>>,
))]
pub fn builtin_native(this: &builtin_native, x: IStr) -> Val {
this.settings
.borrow()
.ext_natives
.get(&x)
.cloned()
.map_or(Val::Null, Val::Func)
}

impl ArakooContextInitializer {
pub fn new(_s: State, resolver: PathResolver) -> Self {
let settings = jrsonnet_stdlib::Settings {
Expand All @@ -74,7 +92,7 @@ impl ArakooContextInitializer {
let stdlib_obj = jrsonnet_stdlib::stdlib_uncached(settings.clone());

let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));
let arakoolib_obj = arakoolib_uncached();
let arakoolib_obj = arakoolib_uncached(settings.clone());
let arakoolib_thunk = Thunk::evaluated(Val::Obj(arakoolib_obj));
Self {
context: {
Expand Down
Binary file modified JS/jsonnet/src/jsonnet_wasm_bg.wasm
Binary file not shown.
6 changes: 3 additions & 3 deletions JS/jsonnet/test/dist/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ describe("Testing javascript native function of jsonnet library", () => {
return a + b + c;
}
let result = JSON.parse(jsonnet.javascriptCallback("add", add).evaluateSnippet(`{
"result": "Output "+std.native("add")(1,2,3),
"result": "Output "+arakoo.native("add")(1,2,3),
"name":"Alice"
}`));
expect(result).to.eql({
Expand All @@ -185,7 +185,7 @@ describe("Testing javascript native function of jsonnet library", () => {
return sum;
}
let result = JSON.parse(jsonnet.javascriptCallback("arrsum", calcSum).evaluateSnippet(`{
"result": "Output "+std.native("arrsum")(${JSON.stringify(numArr)}),
"result": "Output "+arakoo.native("arrsum")(${JSON.stringify(numArr)}),
"name":"Alice"
}`));
expect(result).to.eql({
Expand All @@ -198,7 +198,7 @@ describe("Testing javascript native function of jsonnet library", () => {
return a + b;
}
let result = JSON.parse(jsonnet.javascriptCallback("concat", concat).evaluateSnippet(`{
"result": "Output "+std.native("concat")("Hello ","World"),
"result": "Output "+arakoo.native("concat")("Hello ","World"),
"name":"Alice"
}`));
expect(result).to.eql({
Expand Down
55 changes: 0 additions & 55 deletions JS/jsonnet/test/funcs.js

This file was deleted.

25 changes: 3 additions & 22 deletions JS/jsonnet/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,32 +157,13 @@ describe("Testing join function of jsonnet library", () => {
})
})

// describe("Call native function ", () => {
// it("Call native add function", function () {
// function add(a, b) {
// console.log("a = ", a, " and b = ", b)
// return a + b
// }
// // native: {
// function hello() {
// console.log("hello")
// }
// // }
// // let result = jsonnet.javascriptNative("add", [1, 2]);
// let result = jsonnet.javascriptNative("hello", this);
// // let result = eval("add(1,2)")
// let expected = 3
// expect(result).to.equal(expected)
// })
// })

describe("Testing javascript native function of jsonnet library", () => {
it("Test javascript native function using arithematic operations : add", () => {
function add(a: number, b: number, c: number) {
return a + b + c;
}
let result = JSON.parse(jsonnet.javascriptCallback("add", add).evaluateSnippet(`{
"result": "Output "+std.native("add")(1,2,3),
"result": "Output "+arakoo.native("add")(1,2,3),
"name":"Alice"
}`))
expect(result).to.eql({
Expand All @@ -200,7 +181,7 @@ describe("Testing javascript native function of jsonnet library", () => {
return sum;
}
let result = JSON.parse(jsonnet.javascriptCallback("arrsum", calcSum).evaluateSnippet(`{
"result": "Output "+std.native("arrsum")(${JSON.stringify(numArr)}),
"result": "Output "+arakoo.native("arrsum")(${JSON.stringify(numArr)}),
"name":"Alice"
}`))
expect(result).to.eql({
Expand All @@ -213,7 +194,7 @@ describe("Testing javascript native function of jsonnet library", () => {
return a + b;
}
let result = JSON.parse(jsonnet.javascriptCallback("concat", concat).evaluateSnippet(`{
"result": "Output "+std.native("concat")("Hello ","World"),
"result": "Output "+arakoo.native("concat")("Hello ","World"),
"name":"Alice"
}`))
expect(result).to.eql({
Expand Down
26 changes: 24 additions & 2 deletions JS/wasm/crates/apis/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,29 @@ fn fetch_callback(
));
}
};

todo!("fetch");
let mut headers_map: HashMap<String, JSValue> = HashMap::new();
for (key, value) in response["headers"].as_object().unwrap() {
headers_map.insert(
key.to_string(),
JSValue::String(value.as_str().unwrap().to_string()),
);
}
let mut response_map: HashMap<String, JSValue> = HashMap::new();
response_map.insert(
"status".to_string(),
JSValue::Int(response["status"].as_i64().unwrap().try_into().unwrap()),
);
response_map.insert(
"statusText".to_string(),
JSValue::String(response["statusText"].as_str().unwrap().to_string()),
);
response_map.insert(
"body".to_string(),
JSValue::String(response["body"].as_str().unwrap().to_string()),
);
response_map.insert("headers".to_string(), JSValue::Object(headers_map));
let response_obj = JSValue::Object(response_map);
// todo!("fetch");
Ok(response_obj)
}
}
29 changes: 29 additions & 0 deletions JS/wasm/crates/apis/src/http/shims/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,35 @@ const requestToHandler = (input) => {
}
};

globalThis.axios = {
get: async (url) => {
try {
let response = await fetch(url, {
method: "GET",
});
try {
let body = JSON.parse(response.body);
response.body = body;
return response;
} catch (error) {
return response;
}
} catch (error) {
console.log("error occured");
return error;
}
},
post: async (url, data) => {
return fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
});
},
};

globalThis.entrypoint = requestToHandler;
globalThis.result = {};
globalThis.error = null;
4 changes: 3 additions & 1 deletion JS/wasm/crates/apis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ extern "C" {
fn get_response(ptr: *mut u8);
}

mod pdfparse;

pub(crate) trait JSApiSet {
fn register(&self, runtime: &Runtime, config: &APIConfig) -> Result<()>;
}
Expand All @@ -100,6 +102,6 @@ pub fn add_to_runtime(runtime: &Runtime, config: APIConfig) -> Result<()> {
text_encoding::TextEncoding.register(runtime, &config)?;
http::Http.register(runtime, &config)?;
jsonnet::Jsonnet.register(runtime, &config)?;

pdfparse::PDFPARSER.register(runtime, &config)?;
Ok(())
}
40 changes: 40 additions & 0 deletions JS/wasm/crates/apis/src/pdfparse/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use crate::{APIConfig, JSApiSet};
use anyhow::Result;
use javy::{
quickjs::{from_qjs_value, to_qjs_value, JSContextRef, JSValue, JSValueRef},
Runtime,
};

pub struct PDFPARSER;

impl JSApiSet for PDFPARSER {
fn register(&self, runtime: &Runtime, _config: &APIConfig) -> Result<()> {
let context = runtime.context();
context
.global_object()?
.set_property("setImmediate", context.wrap_callback(set_immediate_api()).expect("unable to get result")).expect("unable to set property");
Ok(())
}
}

fn set_immediate_api(
) -> impl FnMut(&JSContextRef, JSValueRef, &[JSValueRef]) -> Result<JSValue> {
move |context: &JSContextRef, _this: JSValueRef, args: &[JSValueRef]| {
let callback = args.get(0).unwrap();
if callback.is_function() {
let mut argsvec: Vec<JSValueRef> = vec![];
for n in 1..args.len() {
argsvec.push(args.get(n).unwrap().to_owned())
}
let result = callback
.call(
&to_qjs_value(context.to_owned(), &JSValue::Undefined).unwrap(),
args,
)
.expect("Failed to call callback");
return Ok(from_qjs_value(result).expect("Unable to convert result into"));
}
Ok(JSValue::Undefined)
}
}

20 changes: 18 additions & 2 deletions JS/wasm/crates/serve/src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,15 +265,31 @@ pub fn add_fetch_to_linker(linker: &mut Linker<WasiCtx>) -> anyhow::Result<()> {
},
)?;
// add the fetch_output_len and fetch_output functions here
let response_clone = response.clone();
linker.func_wrap("arakoo", "get_response_len", move || -> i32 {
todo!("get_response_len")
let response_clone = response_clone.clone();
let response = response_clone.lock().unwrap().clone();
response.len() as i32
})?;

// also add the fetch_error_len and fetch_error functions here
linker.func_wrap(
"arakoo",
"get_response",
move |mut _caller: Caller<'_, WasiCtx>, _ptr: i32| todo!("get_response"),
move |mut _caller: Caller<'_, WasiCtx>, ptr: i32| {
let response_clone = response.clone();
let mem = match _caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Trap::NullReference.into()),
};
let offset = ptr as u32 as usize;
let response = response_clone.lock().unwrap().clone();
match mem.write(&mut _caller, offset, response.as_bytes()) {
Ok(_) => {}
_ => return Err(Trap::MemoryOutOfBounds.into()),
};
Ok(())
},
)?;
Ok(())
}
6 changes: 3 additions & 3 deletions JS/wasm/crates/serve/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct WasmInput<'a> {
url: String,
method: &'a str,
headers: HashMap<String, String>,
body: &'a str,
body: String,
params: HashMap<String, String>,
}

Expand All @@ -22,7 +22,7 @@ pub struct WasmOutput {
}

impl<'a> WasmInput<'a> {
pub fn new(request: &'a Parts, body: &'a str) -> Self {
pub fn new(request: &'a Parts, body: String) -> Self {
let mut params = HashMap::new();

if let Some(query) = request.uri.query() {
Expand Down Expand Up @@ -58,7 +58,7 @@ impl<'a> WasmInput<'a> {
}

pub fn body(&self) -> &str {
self.body
&self.body
}


Expand Down
4 changes: 2 additions & 2 deletions JS/wasm/crates/serve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl WorkerCtx {
info!("Handling request: {:?} {:?}", parts.method, parts.uri);
let body = hyper::body::to_bytes(body).await.unwrap();
let body_str = String::from_utf8_lossy(&body).to_string();
let result = self.run(&parts, &body_str).await;
let result = self.run(&parts, body_str).await;
match result {
Ok(output) => {
let mut response = Response::builder();
Expand Down Expand Up @@ -137,7 +137,7 @@ impl WorkerCtx {
/// This function sets up the necessary state and memory management for running the WebAssembly
/// module, including setting up the input and output buffers, and wrapping the necessary
/// functions to be called from WebAssembly.
async fn run(&self, parts: &Parts, body: &str) -> anyhow::Result<WasmOutput> {
async fn run(&self, parts: &Parts, body: String) -> anyhow::Result<WasmOutput> {
// Serialize the request parts and body into a JSON input for the WebAssembly module.
let input = serde_json::to_vec(&WasmInput::new(parts, body)).unwrap();
let mem_len = input.len() as i32;
Expand Down
2 changes: 1 addition & 1 deletion JS/wasm/examples/ec-wasmjs-hono/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "hono",
"name": "ec-hono",
"type": "module",
"main": "bin/app.js",
"scripts": {
Expand Down
Loading
Loading