Skip to main content

Tangled QuickJS Javascript Engine binding library

Project description

Build Status Stable Version Coverage Python License

thquickjs

Python binding for QuickJS JavaScript Engine. QuickJS is a small and embeddable JavaScript engine. Safely evaluate untrusted JavaScript code. Create and manipulate values inside the QuickJS runtime. Expose host functions to the QuickJS runtime.

Installation

pip install thquickjs

Simple Usage

from thresult import unwrap
from thquickjs.thquickjs import QuickJS


qjs = QuickJS()

with unwrap():
    # call JS function
    code = '''
        var f = (x) => {
            return [ x, x, x ];
        };
    '''

    qjs.eval(code)
    f: callable = qjs.get_function('f')
    result = f(10)
    assert result == [10, 10, 10]

Advanced Usage

from thresult import unwrap
from thquickjs.thquickjs import QuickJS


qjs = QuickJS()

with unwrap():
    # call JS function
    code = '''
        var f = (x) => {
            return [ x ];
        };
    '''

    qjs.eval(code)
    f: callable = qjs.get_function('f')
    result = f(10)
    assert result == [10]

    # register Python function inside JS runtime
    py_name = 'pylam'
    py_func = lambda x: json.dumps([x * 10])
    qjs.add_callable(py_name, py_func)

    # call Python function from JS runtime
    code = '''
        var g = (x) => {
            return [ JSON.parse(pylam(x)) ];
        };
    '''

    qjs.eval(code)
    g: callable = qjs.get_function('g')
    result = g(10)
    assert result == [[100]]
    
    # call Python function registered in JS runtime
    pylam = qjs.get(py_name)
    result = pylam(5)
    assert result == json.dumps([50])

Testing

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

Coverage

docker-compose build thquickjs-coverage ; docker-compose run --rm -v $PWD:/test thquickjs-coverage

Building

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

Licensing

thquickjs is licensed under the BSD 3 license.

Check the LICENSE for details.

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.26.tar.gz (4.2 kB view hashes)

Uploaded Source

Built Distribution

thquickjs-0.9.26-py3-none-any.whl (4.1 kB view hashes)

Uploaded Python 3

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