diff --git a/JS/jsonnet/.gitignore b/JS/jsonnet/.gitignore index d048f9901..58f885656 100755 --- a/JS/jsonnet/.gitignore +++ b/JS/jsonnet/.gitignore @@ -3,3 +3,4 @@ node_modules/ Cargo.lock package-lock.json yarn.lock +dist/ \ No newline at end of file diff --git a/JS/jsonnet/Cargo.toml b/JS/jsonnet/Cargo.toml index 09d71046e..8afe8984c 100644 --- a/JS/jsonnet/Cargo.toml +++ b/JS/jsonnet/Cargo.toml @@ -20,6 +20,12 @@ wasm-bindgen-file-reader = "1" regex = "1.10.3" js-sys = "0.3.69" console_error_panic_hook = "0.1.7" +urlencoding = "2.1.3" [dev-dependencies] wasm-bindgen-test = "0.3.34" + +[features] +nodejs = [] +default = ["nodejs"] + diff --git a/JS/jsonnet/package.json b/JS/jsonnet/package.json index e7a9394d1..cfaae1656 100644 --- a/JS/jsonnet/package.json +++ b/JS/jsonnet/package.json @@ -3,12 +3,12 @@ "version": "0.3.1", "exports": { "import": { - "default": "./src/index.mjs", - "types": "./src/index.d.mts" + "types": "./src/index.d.mts", + "default": "./src/index.mjs" }, "require": { - "default": "./src/index.js", - "types": "./src/index.d.ts" + "types": "./src/index.d.ts", + "default": "./src/index.js" } } } diff --git a/JS/jsonnet/src/context.rs b/JS/jsonnet/src/context.rs index a9b69a0ee..5e0a8dd04 100644 --- a/JS/jsonnet/src/context.rs +++ b/JS/jsonnet/src/context.rs @@ -1,16 +1,27 @@ use jrsonnet_stdlib::{builtin_type, Settings}; -use std::{cell::{Ref, RefCell, RefMut}, collections::HashMap, rc::Rc}; +use std::{ + cell::{Ref, RefCell, RefMut}, + collections::HashMap, + rc::Rc, +}; +use jrsonnet_evaluator::function::builtin; use jrsonnet_evaluator::{ - error::ErrorKind::{self, ImportSyntaxError}, function::{builtin::{ NativeCallback, NativeCallbackHandler}, FuncVal, TlaArg}, stdlib, tb, trace::PathResolver, ContextBuilder, ContextInitializer, Error, ObjValue, ObjValueBuilder, Result, State, Thunk, Val, - function::builtin, + error::ErrorKind::{self, ImportSyntaxError}, + function::{ + builtin::{NativeCallback, NativeCallbackHandler}, + FuncVal, TlaArg, + }, + stdlib, tb, + trace::PathResolver, + typed::{ComplexValType, Typed, ValType}, + ContextBuilder, ContextInitializer, Error, ObjValue, ObjValueBuilder, ObjectLike, Result, + State, Thunk, Val, }; use jrsonnet_gcmodule::Trace; use jrsonnet_parser::{IStr, Source}; use jrsonnet_stdlib::{StdTracePrinter, TracePrinter}; - - // Implement NativeCallbackHandler for your native function #[builtin] @@ -22,8 +33,7 @@ fn join(a: String, b: String) -> String { fn includes(a: String, b: String) -> bool { if a.contains(&b) { return true; - } - else { + } else { return false; } } @@ -50,17 +60,61 @@ fn regex_match(a: String, b: String) -> Vec { matches } +// #[derive(Debug)] +// struct DateTimeFormatOptions { +// hour: String, +// minute: String, +// hour12: bool, +// } + +// #[builtin] +// fn format_date( +// hour: Option, +// minute: Option, +// hour12: bool, +// timeZone: Option, +// ) -> String { +// super::log(&format!("Debug : {:?}", hour)); +// super::log(&format!("Debug : {:?}", minute)); +// super::log(&format!("Debug : {:?}", hour12)); +// println!("Debug : {:?}", timeZone); +// String::from("Formatted date") +// } + +/// Returns current date and time in utc +// #[builtin] +// fn date( +// dateTime: Option, +// timeStamp: Option, +// year: Option, +// monthIndex: Option, +// day: Option, +// hours: Option, +// minutes: Option, +// seconds: Option, +// milliseconds: Option, +// ) -> String { +// String::from("Good datetime") +// } + +#[builtin] +fn url_encode(a: String) -> String { + urlencoding::encode(&a).into_owned() +} + fn arakoolib_uncached(settings: Rc>) -> ObjValue { let mut builder = ObjValueBuilder::new(); builder.method( - "native", - builtin_native { - settings: settings.clone(), - }, - ); + "native", + builtin_native { + settings: settings.clone(), + }, + ); builder.method("join", join::INST); builder.method("regexMatch", regex_match::INST); builder.method("includes", includes::INST); + // builder.method("formatDate", format_date::INST); + builder.method("urlEncode", url_encode::INST); builder.build() } @@ -75,20 +129,20 @@ pub struct ArakooContextInitializer { } fn extvar_source(name: &str, code: impl Into) -> Source { - let source_name = format!(""); - Source::new_virtual(source_name.into(), code.into()) + let source_name = format!(""); + Source::new_virtual(source_name.into(), code.into()) } #[builtin(fields( settings: Rc>, ))] pub fn builtin_native(this: &builtin_native, x: IStr) -> Val { - this.settings - .borrow() - .ext_natives - .get(&x) - .cloned() - .map_or(Val::Null, Val::Func) + this.settings + .borrow() + .ext_natives + .get(&x) + .cloned() + .map_or(Val::Null, Val::Func) } impl ArakooContextInitializer { @@ -101,7 +155,7 @@ impl ArakooContextInitializer { }; let settings = Rc::new(RefCell::new(settings)); let stdlib_obj = jrsonnet_stdlib::stdlib_uncached(settings.clone()); - + let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj)); let arakoolib_obj = arakoolib_uncached(settings.clone()); let arakoolib_thunk = Thunk::evaluated(Val::Obj(arakoolib_obj)); @@ -163,11 +217,11 @@ impl jrsonnet_evaluator::ContextInitializer for ArakooContextInitializer { fn reserve_vars(&self) -> usize { 1 } - + fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context { self.context.clone() } - + fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) { builder.bind("std", self.stdlib_thunk.clone()); builder.bind("arakoo", self.arakoolib_thunk.clone()); diff --git a/JS/jsonnet/src/jsonnet.js b/JS/jsonnet/src/jsonnet.js index a57be778a..ebe36ad5d 100644 --- a/JS/jsonnet/src/jsonnet.js +++ b/JS/jsonnet/src/jsonnet.js @@ -1,8 +1,8 @@ -const isArakoo = process.env.arakoo; +// const isArakoo = process.env.arakoo; let Jsonnet; -if (!isArakoo) { +if (!process.env.arakoo) { let module = require("./jsonnet_wasm.js"); let { jsonnet_evaluate_snippet, diff --git a/JS/jsonnet/src/jsonnet_wasm.d.ts b/JS/jsonnet/src/jsonnet_wasm.d.ts index d7ba546fc..160156e6c 100644 --- a/JS/jsonnet/src/jsonnet_wasm.d.ts +++ b/JS/jsonnet/src/jsonnet_wasm.d.ts @@ -1,45 +1,45 @@ /* tslint:disable */ /* eslint-disable */ /** - * @returns {number} - */ +* @returns {number} +*/ export function jsonnet_make(): number; /** - * @param {number} vm - */ +* @param {number} vm +*/ export function jsonnet_destroy(vm: number): void; /** - * @param {number} vm - * @param {string} filename - * @param {string} snippet - * @returns {string} - */ +* @param {number} vm +* @param {string} filename +* @param {string} snippet +* @returns {string} +*/ export function jsonnet_evaluate_snippet(vm: number, filename: string, snippet: string): string; /** - * @param {number} vm - * @param {string} filename - * @returns {string} - */ +* @param {number} vm +* @param {string} filename +* @returns {string} +*/ export function jsonnet_evaluate_file(vm: number, filename: string): string; /** - * @param {number} vm - * @param {string} key - * @param {string} value - */ +* @param {number} vm +* @param {string} key +* @param {string} value +*/ export function jsonnet_ext_string(vm: number, key: string, value: string): void; /** - * @param {string} name - * @returns {Function | undefined} - */ +* @param {string} name +* @returns {Function | undefined} +*/ export function get_func(name: string): Function | undefined; /** - * @param {string} name - * @param {Function} func - */ +* @param {string} name +* @param {Function} func +*/ export function set_func(name: string, func: Function): void; /** - * @param {number} vm - * @param {string} name - * @param {number} args_num - */ +* @param {number} vm +* @param {string} name +* @param {number} args_num +*/ export function register_native_callback(vm: number, name: string, args_num: number): void; diff --git a/JS/jsonnet/src/jsonnet_wasm.js b/JS/jsonnet/src/jsonnet_wasm.js index 3e7153453..7f1d7c2cf 100644 --- a/JS/jsonnet/src/jsonnet_wasm.js +++ b/JS/jsonnet/src/jsonnet_wasm.js @@ -1,5 +1,5 @@ let imports = {}; -imports["__wbindgen_placeholder__"] = module.exports; +imports['__wbindgen_placeholder__'] = module.exports; let wasm; const { read_file } = require(String.raw`./snippets/arakoo-jsonnet-17c737407ebd2d3c/read-file.js`); const { TextEncoder, TextDecoder } = require(`util`); @@ -8,9 +8,7 @@ const heap = new Array(128).fill(undefined); heap.push(undefined, null, true, false); -function getObject(idx) { - return heap[idx]; -} +function getObject(idx) { return heap[idx]; } let WASM_VECTOR_LEN = 0; @@ -23,29 +21,27 @@ function getUint8Memory0() { return cachedUint8Memory0; } -let cachedTextEncoder = new TextEncoder("utf-8"); - -const encodeString = - typeof cachedTextEncoder.encodeInto === "function" - ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); - } - : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length, - }; - }; +let cachedTextEncoder = new TextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length, 1) >>> 0; - getUint8Memory0() - .subarray(ptr, ptr + buf.length) - .set(buf); + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); WASM_VECTOR_LEN = buf.length; return ptr; } @@ -59,7 +55,7 @@ function passStringToWasm0(arg, malloc, realloc) { for (; offset < len; offset++) { const code = arg.charCodeAt(offset); - if (code > 0x7f) break; + if (code > 0x7F) break; mem[ptr + offset] = code; } @@ -67,7 +63,7 @@ function passStringToWasm0(arg, malloc, realloc) { if (offset !== 0) { arg = arg.slice(offset); } - ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; const view = getUint8Memory0().subarray(ptr + offset, ptr + len); const ret = encodeString(arg, view); @@ -106,7 +102,7 @@ function takeObject(idx) { return ret; } -let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }); +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); cachedTextDecoder.decode(); @@ -127,39 +123,39 @@ function addHeapObject(obj) { function debugString(val) { // primitive types const type = typeof val; - if (type == "number" || type == "boolean" || val == null) { - return `${val}`; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; } - if (type == "string") { + if (type == 'string') { return `"${val}"`; } - if (type == "symbol") { + if (type == 'symbol') { const description = val.description; if (description == null) { - return "Symbol"; + return 'Symbol'; } else { return `Symbol(${description})`; } } - if (type == "function") { + if (type == 'function') { const name = val.name; - if (typeof name == "string" && name.length > 0) { + if (typeof name == 'string' && name.length > 0) { return `Function(${name})`; } else { - return "Function"; + return 'Function'; } } // objects if (Array.isArray(val)) { const length = val.length; - let debug = "["; + let debug = '['; if (length > 0) { debug += debugString(val[0]); } - for (let i = 1; i < length; i++) { - debug += ", " + debugString(val[i]); + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); } - debug += "]"; + debug += ']'; return debug; } // Test for built-in @@ -171,14 +167,14 @@ function debugString(val) { // Failed to match the standard '[object ClassName]' return toString.call(val); } - if (className == "Object") { + if (className == 'Object') { // we're a user defined class or Object // JSON.stringify avoids problems with cycles, and is generally much // easier than looping through ownProperties of `val`. try { - return "Object(" + JSON.stringify(val) + ")"; + return 'Object(' + JSON.stringify(val) + ')'; } catch (_) { - return "Object"; + return 'Object'; } } // errors @@ -197,27 +193,27 @@ function handleError(f, args) { } } /** - * @returns {number} - */ -module.exports.jsonnet_make = function () { +* @returns {number} +*/ +module.exports.jsonnet_make = function() { const ret = wasm.jsonnet_make(); return ret >>> 0; }; /** - * @param {number} vm - */ -module.exports.jsonnet_destroy = function (vm) { +* @param {number} vm +*/ +module.exports.jsonnet_destroy = function(vm) { wasm.jsonnet_destroy(vm); }; /** - * @param {number} vm - * @param {string} filename - * @param {string} snippet - * @returns {string} - */ -module.exports.jsonnet_evaluate_snippet = function (vm, filename, snippet) { +* @param {number} vm +* @param {string} filename +* @param {string} snippet +* @returns {string} +*/ +module.exports.jsonnet_evaluate_snippet = function(vm, filename, snippet) { let deferred3_0; let deferred3_1; try { @@ -239,11 +235,11 @@ module.exports.jsonnet_evaluate_snippet = function (vm, filename, snippet) { }; /** - * @param {number} vm - * @param {string} filename - * @returns {string} - */ -module.exports.jsonnet_evaluate_file = function (vm, filename) { +* @param {number} vm +* @param {string} filename +* @returns {string} +*/ +module.exports.jsonnet_evaluate_file = function(vm, filename) { let deferred2_0; let deferred2_1; try { @@ -263,11 +259,11 @@ module.exports.jsonnet_evaluate_file = function (vm, filename) { }; /** - * @param {number} vm - * @param {string} key - * @param {string} value - */ -module.exports.jsonnet_ext_string = function (vm, key, value) { +* @param {number} vm +* @param {string} key +* @param {string} value +*/ +module.exports.jsonnet_ext_string = function(vm, key, value) { const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; const ptr1 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); @@ -276,10 +272,10 @@ module.exports.jsonnet_ext_string = function (vm, key, value) { }; /** - * @param {string} name - * @returns {Function | undefined} - */ -module.exports.get_func = function (name) { +* @param {string} name +* @returns {Function | undefined} +*/ +module.exports.get_func = function(name) { const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; const ret = wasm.get_func(ptr0, len0); @@ -287,81 +283,73 @@ module.exports.get_func = function (name) { }; /** - * @param {string} name - * @param {Function} func - */ -module.exports.set_func = function (name, func) { +* @param {string} name +* @param {Function} func +*/ +module.exports.set_func = function(name, func) { const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; wasm.set_func(ptr0, len0, addHeapObject(func)); }; /** - * @param {number} vm - * @param {string} name - * @param {number} args_num - */ -module.exports.register_native_callback = function (vm, name, args_num) { +* @param {number} vm +* @param {string} name +* @param {number} args_num +*/ +module.exports.register_native_callback = function(vm, name, args_num) { const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; wasm.register_native_callback(vm, ptr0, len0, args_num); }; -module.exports.__wbindgen_string_get = function (arg0, arg1) { +module.exports.__wbindgen_string_get = function(arg0, arg1) { const obj = getObject(arg1); - const ret = typeof obj === "string" ? obj : undefined; - var ptr1 = isLikeNone(ret) - ? 0 - : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const ret = typeof(obj) === 'string' ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); var len1 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len1; getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbindgen_object_drop_ref = function (arg0) { +module.exports.__wbindgen_object_drop_ref = function(arg0) { takeObject(arg0); }; -module.exports.__wbindgen_string_new = function (arg0, arg1) { +module.exports.__wbindgen_string_new = function(arg0, arg1) { const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }; -module.exports.__wbg_readfile_5b48d0f7e3518df2 = function () { - return handleError(function (arg0, arg1, arg2) { - const ret = read_file(getStringFromWasm0(arg1, arg2)); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getInt32Memory0()[arg0 / 4 + 1] = len1; - getInt32Memory0()[arg0 / 4 + 0] = ptr1; - }, arguments); -}; +module.exports.__wbg_readfile_5b48d0f7e3518df2 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = read_file(getStringFromWasm0(arg1, arg2)); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; +}, arguments) }; -module.exports.__wbindgen_object_clone_ref = function (arg0) { +module.exports.__wbindgen_object_clone_ref = function(arg0) { const ret = getObject(arg0); return addHeapObject(ret); }; -module.exports.__wbg_call_27c0f87801dedf93 = function () { - return handleError(function (arg0, arg1) { - const ret = getObject(arg0).call(getObject(arg1)); - return addHeapObject(ret); - }, arguments); -}; +module.exports.__wbg_call_27c0f87801dedf93 = function() { return handleError(function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); +}, arguments) }; -module.exports.__wbg_call_b3ca7c6051f9bec1 = function () { - return handleError(function (arg0, arg1, arg2) { - const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); - return addHeapObject(ret); - }, arguments); -}; +module.exports.__wbg_call_b3ca7c6051f9bec1 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); +}, arguments) }; -module.exports.__wbg_new_abda76e883ba8a5f = function () { +module.exports.__wbg_new_abda76e883ba8a5f = function() { const ret = new Error(); return addHeapObject(ret); }; -module.exports.__wbg_stack_658279fe44541cf6 = function (arg0, arg1) { +module.exports.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) { const ret = getObject(arg1).stack; const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len1 = WASM_VECTOR_LEN; @@ -369,7 +357,7 @@ module.exports.__wbg_stack_658279fe44541cf6 = function (arg0, arg1) { getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbg_error_f851667af71bcfc6 = function (arg0, arg1) { +module.exports.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) { let deferred0_0; let deferred0_1; try { @@ -381,7 +369,7 @@ module.exports.__wbg_error_f851667af71bcfc6 = function (arg0, arg1) { } }; -module.exports.__wbindgen_debug_string = function (arg0, arg1) { +module.exports.__wbindgen_debug_string = function(arg0, arg1) { const ret = debugString(getObject(arg1)); const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len1 = WASM_VECTOR_LEN; @@ -389,14 +377,15 @@ module.exports.__wbindgen_debug_string = function (arg0, arg1) { getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbindgen_throw = function (arg0, arg1) { +module.exports.__wbindgen_throw = function(arg0, arg1) { throw new Error(getStringFromWasm0(arg0, arg1)); }; -const path = require("path").join(__dirname, "jsonnet_wasm_bg.wasm"); -const bytes = require("fs").readFileSync(path); +const path = require('path').join(__dirname, 'jsonnet_wasm_bg.wasm'); +const bytes = require('fs').readFileSync(path); const wasmModule = new WebAssembly.Module(bytes); const wasmInstance = new WebAssembly.Instance(wasmModule, imports); wasm = wasmInstance.exports; module.exports.__wasm = wasm; + diff --git a/JS/jsonnet/src/jsonnet_wasm_bg.wasm b/JS/jsonnet/src/jsonnet_wasm_bg.wasm index 320978dac..da9f86534 100644 Binary files a/JS/jsonnet/src/jsonnet_wasm_bg.wasm and b/JS/jsonnet/src/jsonnet_wasm_bg.wasm differ diff --git a/JS/jsonnet/src/jsonnet_wasm_bg.wasm.d.ts b/JS/jsonnet/src/jsonnet_wasm_bg.wasm.d.ts index addf76d72..82d72aa0d 100644 --- a/JS/jsonnet/src/jsonnet_wasm_bg.wasm.d.ts +++ b/JS/jsonnet/src/jsonnet_wasm_bg.wasm.d.ts @@ -3,14 +3,7 @@ export const memory: WebAssembly.Memory; export function jsonnet_make(): number; export function jsonnet_destroy(a: number): void; -export function jsonnet_evaluate_snippet( - a: number, - b: number, - c: number, - d: number, - e: number, - f: number -): void; +export function jsonnet_evaluate_snippet(a: number, b: number, c: number, d: number, e: number, f: number): void; export function jsonnet_evaluate_file(a: number, b: number, c: number, d: number): void; export function jsonnet_ext_string(a: number, b: number, c: number, d: number, e: number): void; export function get_func(a: number, b: number): number; diff --git a/JS/jsonnet/src/lib.rs b/JS/jsonnet/src/lib.rs index af68f2ffb..b0fa2b2c6 100755 --- a/JS/jsonnet/src/lib.rs +++ b/JS/jsonnet/src/lib.rs @@ -1,5 +1,6 @@ use std::{cell::RefCell, collections::HashMap, path::Path}; +use console_error_panic_hook; use jrsonnet_evaluator::{ apply_tla, error::ErrorKind, @@ -17,7 +18,6 @@ use jrsonnet_gcmodule::Trace; use jrsonnet_parser::IStr; use std::alloc; use wasm_bindgen::prelude::*; -use console_error_panic_hook; pub mod context; @@ -60,6 +60,7 @@ pub fn jsonnet_make() -> *mut VM { }); } let state = State::default(); + #[cfg(feature = "nodejs")] console_error_panic_hook::set_once(); state.settings_mut().import_resolver = tb!(FileImportResolver::default()); state.set_context_initializer(context::ArakooContextInitializer::new( diff --git a/JS/jsonnet/test/dist/test.js b/JS/jsonnet/test/dist/test.js deleted file mode 100644 index d9da59521..000000000 --- a/JS/jsonnet/test/dist/test.js +++ /dev/null @@ -1,215 +0,0 @@ -import Jsonnet from "@arakoodev/jsonnet"; -// import Jsonnet from "../src/index.js" -// import Jsonnet from "../src/index.mjs" -import { expect } from "chai"; -import { describe, it } from "mocha"; -let jsonnet = new Jsonnet(); -describe("Testing evaluateSnippet function of jsonnet library", () => { - it("self reference", () => { - let result = JSON.parse( - jsonnet.evaluateSnippet(`{ - Martini: { - local drink = self, - ingredients: [ - { kind: "Farmer's Gin", qty: 1 }, - { - kind: 'Dry White Vermouth', - qty: drink.ingredients[0].qty, - }, - ], - garnish: 'Olive', - served: 'Straight Up', - }, - }`) - ); - let expected = { - Martini: { - garnish: "Olive", - ingredients: [ - { - kind: "Farmer's Gin", - qty: 1, - }, - { - kind: "Dry White Vermouth", - qty: 1, - }, - ], - served: "Straight Up", - }, - }; - // expect(JSON.stringify(result)).to.equal(JSON.stringify(expected)); - expect(result).to.eql(expected); - }); - it("math operations", () => { - let result = JSON.parse( - jsonnet.evaluateSnippet(`{ - a: 1 + 2, - b: 3 * 4, - c: 5 / 6, - d: 7 % 8, - e: 9 - 10, - }`) - ); - let expected = { - a: 3, - b: 12, - c: 0.8333333333333334, - d: 7, - e: -1, - }; - // expect(JSON.stringify(result)).to.equal(JSON.stringify(expected)); - expect(result).to.eql(expected); - }); -}); -describe("Testing evaluateFile function of jsonnet library", () => { - it("Read File and evaluate", () => { - // let result = jsonnet.extString("name", "Alice"); - let result = JSON.parse(jsonnet.evaluateFile("./test.jsonnet")); - let expected = { - concat_array: [1, 2, 3, 4], - concat_string: "1234", - equality1: false, - equality2: true, - ex1: 1.6666666666666665, - ex2: 3, - ex3: 1.6666666666666665, - ex4: true, - obj: { - a: 1, - b: 3, - c: 4, - }, - obj_member: true, - str1: "The value of self.ex2 is 3.", - str2: "The value of self.ex2 is 3.", - str3: "ex1=1.67, ex2=3.00", - str4: "ex1=1.67, ex2=3.00", - str5: "ex1=1.67\nex2=3.00\n", - }; - expect(result).to.eql(expected); - }); -}); -describe("Testing extString function of jsonnet library", () => { - it("Test extString function", () => { - let result = JSON.parse( - jsonnet.extString("name", "Alice").evaluateSnippet(`local username = std.extVar('name'); - local Person(name='Alice') = { - name: name, - welcome: 'Hello ' + name + '!', - }; - { - person1: Person(username), - person2: Person('Bob'), - }`) - ); - let expected = { - person1: { - name: "Alice", - welcome: "Hello Alice!", - }, - person2: { - name: "Bob", - welcome: "Hello Bob!", - }, - }; - expect(result).to.eql(expected); - }); -}); -describe("Testing regex function of jsonnet library", () => { - it("Test regex function", () => { - let result = JSON.parse(jsonnet.evaluateFile("./test_regex.jsonnet")); - let expected = { - person1: { - name: "Alice Arthur's Magazine", - welcome: "Hello Alice Arthur's Magazine!", - }, - person2: { - name: "Arthur's Magazine", - welcome: "Hello Arthur's Magazine!", - }, - }; - // console.log("result : ", result); - expect(result).to.eql(expected); - }); -}); -describe("Testing join function of jsonnet library", () => { - it("Test join function", () => { - let result = JSON.parse( - jsonnet.evaluateSnippet(`local a = "open"; - local b = "source"; - { - "joined string":arakoo.join(a,b) - }`) - ); - let expected = { - "joined string": "opensource", - }; - expect(result).to.eql(expected); - }); -}); -describe("Testing javascript native function of jsonnet library", () => { - it("Test javascript native function using arithematic operations : add", () => { - function add(a, b, c) { - return a + b + c; - } - let result = JSON.parse( - jsonnet.javascriptCallback("add", add).evaluateSnippet(`{ - "result": "Output "+arakoo.native("add")(1,2,3), - "name":"Alice" - }`) - ); - expect(result).to.eql({ - result: "Output 6", - name: "Alice", - }); - }); - it("Test javascript native function using arithematic operations : array sum", () => { - let numArr = [1, 2, 3, 4, 5]; - function calcSum(arr) { - let sum = 0; - for (let i = 0; i < arr.length; i++) { - sum += arr[i]; - } - return sum; - } - let result = JSON.parse( - jsonnet.javascriptCallback("arrsum", calcSum).evaluateSnippet(`{ - "result": "Output "+arakoo.native("arrsum")(${JSON.stringify(numArr)}), - "name":"Alice" - }`) - ); - expect(result).to.eql({ - result: "Output 15", - name: "Alice", - }); - }); - it("Test javascript native function using string operations : concat", () => { - function concat(a, b) { - return a + b; - } - let result = JSON.parse( - jsonnet.javascriptCallback("concat", concat).evaluateSnippet(`{ - "result": "Output "+arakoo.native("concat")("Hello ","World"), - "name":"Alice" - }`) - ); - expect(result).to.eql({ - result: "Output Hello World", - name: "Alice", - }); - }); -}); -describe("Testing includes function of jsonnet library", () => { - it("Test includes function", () => { - let result = JSON.parse( - jsonnet.evaluateSnippet(`{ - "result":arakoo.includes("open source is awesome","source") - }`) - ); - let expected = { - result: true, - }; - expect(result).to.eql(expected); - }); -}); diff --git a/JS/jsonnet/test/test.ts b/JS/jsonnet/test/test.ts index 8c66d3dec..c7d5941b2 100644 --- a/JS/jsonnet/test/test.ts +++ b/JS/jsonnet/test/test.ts @@ -22,8 +22,7 @@ describe("Testing evaluateSnippet function of jsonnet library", () => { garnish: 'Olive', served: 'Straight Up', }, - }`) - ); + }`)); let expected = { Martini: { garnish: "Olive", @@ -40,7 +39,6 @@ describe("Testing evaluateSnippet function of jsonnet library", () => { served: "Straight Up", }, }; - // expect(JSON.stringify(result)).to.equal(JSON.stringify(expected)); expect(result).to.eql(expected); }); @@ -61,7 +59,6 @@ describe("Testing evaluateSnippet function of jsonnet library", () => { d: 7, e: -1, }; - // expect(JSON.stringify(result)).to.equal(JSON.stringify(expected)); expect(result).to.eql(expected); }); }); @@ -222,3 +219,17 @@ describe("Testing includes function of jsonnet library", () => { expect(result).to.eql(expected); }); }); + +describe("Testing urlencoding function of jsonnet library", () => { + it("Test urlencoding function", () => { + let result = JSON.parse( + jsonnet.evaluateSnippet(`{ + "result":arakoo.urlEncode("open source is awesome") + }`) + ); + let expected = { + result: "open%20source%20is%20awesome", + }; + expect(result).to.eql(expected); + }) +}); \ No newline at end of file diff --git a/JS/wasm/crates/arakoo-core/Cargo.toml b/JS/wasm/crates/arakoo-core/Cargo.toml index 9e8b34c58..16997c078 100644 --- a/JS/wasm/crates/arakoo-core/Cargo.toml +++ b/JS/wasm/crates/arakoo-core/Cargo.toml @@ -24,6 +24,6 @@ bytes = { version = "1.6.0", features = ["serde"] } fastrand = "2.1.0" log = {version = "*"} env_logger = {version = "*"} -arakoo-jsonnet ={ path = "../../../jsonnet"} +arakoo-jsonnet ={ path = "../../../jsonnet", default-features = false} jrsonnet-gcmodule = { version = "0.3.6" } jrsonnet-evaluator = { version = "0.5.0-pre95" }