Skip to main content

TangledHub QuickJs wrapper library

Project description

License Build Coverage

thquickjs

Overview

TangledHub library for creating context for JavaScript and Python code. QuickJS is a small and embeddable Javascript engine. Safely evaluate untrusted Javascript. Create and manipulate values inside the QuickJS runtime. Expose host functions to the QuickJS runtime

Licencing

thquickjs is licensed under the BSD license. Check the LICENSE file for details

Installation

pip install thquickjs

Testing

Run in console:

docker-compose build thquickjs-test ; docker-compose run --rm thquickjs-test

Building

Run in console:

docker-compose build thquickjs-build ; docker-compose run --rm thquickjs-build

Publish

Run in console:

docker-compose build thquickjs-publish ; docker-compose run --rm thquickjs-publish

Usage

Evaluate JavaScript code

Create instance of QuickJS. Use that instance to evaluate JavaScript code. JavaScript code can be in string or file. JavaScript code (variables, functions) can be accessed from quickjs context.

'''
    setup and create instance of QuickJS object
    - eval code function evaluate JS code
    - get function obtain a function from quickjs context
    - js function call in python code

    params:
        eval:
            code: string(js code)
        
        get:
            function_name: str

    returns:
        get:
            function: js function
'''
from thquickjs.thquickjs import QuickJS

# create QuckJS object
qjs: QuickJS = QuickJS()

# example js code
code = '''
    f = function(x) {
        return 40 + x;
    }
    
    f1 = function(x, y) {
        return x + y;
    }
'''

# evaluate JS code
qjs.eval(code).unwrap()

# obtain a function from quickjs context
func = qjs.get('f1').unwrap()  # js function in python

# invoke function from JS code in Python code
result = func(2, 3)  # returns 5

JavaScript code can be in separate file. Note that file extension doesn't have to be .js.

'''
    setup and create instance of QuickJS object
    - eval code function evaluate JS code from file
    - get function obtain a function from quickjs context
    - js function call in python code

    params:
        eval:
            code: string(js code)
        
        get:
            function_name: str

    returns:
        get:
            function: js function
'''
from thquickjs.thquickjs import QuickJS

# create QuckJS object
qjs = QuickJS()

# value of code is content of file 
code = '''
    f = function(x) {
        return 40 + x;
    }
    
    f1 = function(x, y) {
        return x + y;
    }
'''

file_name: str = file_name = 'abc.txt'

with open(file_name, 'r') as reader:
    content = reader.read()

# evaluate JS code
qjs.eval(content).unwrap()

# obtain a function from quickjs context
func = qjs.get('f1').unwrap()  # js function in python

# invoke function from JS code in Python code
result = func(2, 3)  # returns 5

Try to get non-existing variable from context will return None.

from thquickjs.thquickjs import QuickJS

# create QuckJS object
qjs = QuickJS()

# example js code
code = '''
    f = function(x) {
        return 40 + x;
    }
    
    f1 = function(x, y) {
        return x + y;
    }
'''

# evaluate JS code
qjs.eval(code).unwrap()

# try to get non-existing variable from context will return None
func = qjs.get('a').unwrap()  # None

Parsing js modules

# create QuckJS object
qjs = QuickJS()

# import lodash
path = os.path.join('/deps' 'vendor', 'lodash.js')

# import module by specified path
qjs.import_js_module(path).unwrap()

# use lodash
code = '''
    var a = _.range(10);
    a;
'''

# evaluate JS code
res = qjs.eval(code, as_json=True).unwrap()
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Add values to thquickjs context

Variables can be added in thquickjs context.

from thquickjs.thquickjs import QuickJS

# create QucikJS object
qjs: QuickJS = QuickJS()

# set variable and value to context
qjs.set('x', 8, ).unwrap()

# get value by given variable name
v = qjs.get('x').unwrap()  # v is 8

# change value of variable x in context
qjs.set('x', 12, ).unwrap()

# get value by given variable name
v = qjs.get('x').unwrap()  # v is 12

Add Python callable in thquickjs context

from thquickjs.thquickjs import QuickJS

# create QucikJS object
qjs = QuickJS()

py_name = 'pylam'
py_func = lambda x: x * 10

# adding Python callable in context
qjs.add_callable(py_name, py_func).unwrap()

# get function by given variable name
f = qjs.get(py_name).unwrap()  # v is 8

# result
result = f(5)  # returns value of 50

Handling errors

In previous examples, using unwrap() will return appropriate value or rise Exception. Using unwrap_or(v: Any) or unwrap_value() will prevent rising exceptions and terminating program.

Handling errors when parsing JavaScript code

from _quickjs import JSException
from thquickjs.thquickjs import QuickJS

# create QuckJS object
qjs = QuickJS()

# example of unparsable js code
code = '''unparsable js code'''

# standard way to handle exception using try and except blocks
try:
    # evaluate unparsable JS code
    qjs_func: _quickjs.Object = qjs.eval(code).unwrap()
except JSException as e:
    pass

# evaluation of js code and unwraps_value - returns exception as string
qjs_func = qjs.eval(code).unwrap_value()

# unwrap_or method sets default value in case of exception
# qjs_func in case of exception will have default value
qjs_func = qjs.eval(code).unwrap_or('default value in case of exception') 

Handling errors when adding Python callable

from thquickjs.thquickjs import QuickJS

## handling errors

# create QucikJS object
qjs: QuickJS = QuickJS()


# handling error with try/except
def add_ten(n: int) -> int:
    return n + 10


py_name = 'pylam'

try:
    # add callable to context
    f = qjs.add_callable(py_name, 'unparsable').unwrap()
except TypeError as e:
    f = add_ten


# handling error with unwrap_value
def add_two(n: int) -> int:
    return n + 2


py_name = 'pylam'

# in case of Err, variable f will contain error message
f = qjs.add_callable(py_name, 'unparsable').unwrap_value()

# in case of Err, add_two function will be assigned to variable f
f = qjs.add_callable(py_name, 'unparsable').unwrap_or(add_two)
f(3)  # result 5

Using unwrap_value() and unwrap_or(v: Any) when there is no exceptions, will have no effects on return value.

from thquickjs.thquickjs import QuickJS

# create QucikJS object
qjs = QuickJS()

# set variable and value to context
qjs.set('x', 8, ).unwrap()

# get value by given variable name
v = qjs.get('x').unwrap()  # v is 8

# change value of variable x in context
qjs.set('x', 12, ).unwrap()

# get value by given variable name
v = qjs.get('x').unwrap()  # v is 12

# if unwrap doesn't rise Exception, unwrap_value will return expected value
v1 = qjs.get('x').unwrap_value()  # v1 is 12

# if unwrap doesn't rise Exception, unwrap_or will have no effects on return value
v2 = qjs.get('x').unwrap_or(11)  # v2 is 12

Set memory limit

Use set_memory_limit method to set available memory for thquickjs. To get informations about memory use memory method.

qjs: QuickJS = QuickJS()

qjs.set_memory_limit(memory_limit=1024000)

# get informations about memory - used, available etc.
res: dict = qjs.memory()

Set time limit

To set time limit in context, use set_time_limit method.

qjs = QuickJS()

qjs.set_time_limit(time_limit=600)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

thquickjs-0.9.0.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

thquickjs-0.9.0-py3-none-any.whl (4.3 kB view details)

Uploaded Python 3

File details

Details for the file thquickjs-0.9.0.tar.gz.

File metadata

  • Download URL: thquickjs-0.9.0.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.12 CPython/3.10.1 Linux/5.4.109+

File hashes

Hashes for thquickjs-0.9.0.tar.gz
Algorithm Hash digest
SHA256 a3a98372773bec0c36d95e2bd9c1eba5d6918f9708b1f03cd38488419ec5dc34
MD5 04105428c2e5e4f64fa2f4f67d232156
BLAKE2b-256 7354c1a43d53265dfe798cf9d99e7b09c40ed7d78a7643afd326b7778282df88

See more details on using hashes here.

File details

Details for the file thquickjs-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: thquickjs-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 4.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.12 CPython/3.10.1 Linux/5.4.109+

File hashes

Hashes for thquickjs-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2e84ffb0aa035dfe3eaf7941a049de0ec56dfa66670f70ab672c286b6090f78b
MD5 752814c46477375109d51bfdb6d32759
BLAKE2b-256 52a797cdbc046cc78bde7c1a205987bd5306034a64eba8dc08df927d3104a69e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page