Skip to main content

TangledHub QuickJs wrapper library

Project description

Build Status Stable Version Coverage Python License

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.

Licensing

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

Installation

pip install thquickjs

Testing

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

Building

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

Publish

docker-compose build thquickjs-publish ; docker-compose run --rm -e PYPI_USERNAME=__token__ -e PYPI_PASSWORD=__SECRET__ 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 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 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 = '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 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', 'thquickjs', '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 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 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 Object, JSException
from 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: 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 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 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)

Testing

Run in console:

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

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.22.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

thquickjs-0.9.22-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for thquickjs-0.9.22.tar.gz
Algorithm Hash digest
SHA256 3efbf74818ca172d3c317f3e5ad8377a37d37058c486a87eddae6d5031cd6072
MD5 6b1384407b9f7b3ed31ccbb0bb0dfa6a
BLAKE2b-256 1145a1a66d27738d0b657031d745578f727cfbdb978f8f66701ce60774fe2f37

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for thquickjs-0.9.22-py3-none-any.whl
Algorithm Hash digest
SHA256 388add92035293302ca272fd9d9dd82ca8f48934aad3c8945092a66367a166d7
MD5 18158c2704e7593738cd6cf9cd07ee41
BLAKE2b-256 cfdae44fe3ad7e666173063dab129d8b5428df4ad8dcbf4171d04e247953cb03

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