Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@pipcook/boa

Package Overview
Dependencies
Maintainers
5
Versions
104
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pipcook/boa - npm Package Compare versions

Comparing version 1.3.0 to 2.0.0-alpha.0

20

lib/worker.js
'use strict';
const { isMainThread, workerData } = require('worker_threads');
let isMainThread = false;
let workerData = null;
let supportWorkerThreads = false;
const { PythonObject, NODE_PYTHON_HANDLE_NAME } = require('bindings')('boa');

@@ -8,3 +11,13 @@ const { wrap } = require('./proxy');

const TYPE_ID = 'SHARED_PYTHON_OBJECT_TYPE';
try {
require.resolve('worker_threads');
supportWorkerThreads = true;
} catch (err) {
supportWorkerThreads = false;
}
if (supportWorkerThreads === true) {
({ isMainThread, workerData } = require('worker_threads'));
}
/**

@@ -16,4 +29,7 @@ * This is a wrapper for shared Python object, just like

constructor(o) {
if (!supportWorkerThreads) {
throw new TypeError('worker_threads is not supported, please upgrade your Node.js');
}
if (!isMainThread) {
throw TypeError('SharedPythonObject must be used in main thread.');
throw new TypeError('SharedPythonObject must be used in main thread.');
}

@@ -20,0 +36,0 @@ this.ownershipId = o[NODE_PYTHON_HANDLE_NAME].requestOwnership();

32

package.json
{
"name": "@pipcook/boa",
"version": "1.3.0",
"version": "2.0.0-alpha.0",
"description": "Use Python modules seamlessly in Node.js",

@@ -8,12 +8,14 @@ "main": "lib/index.js",

"clean": "sh tools/clean-python.sh && make -C ./pybind11/ clean",
"preinstall": "node tools/check-dependence.js && make -C ./pybind11/ && node tools/install-python.js && node tools/install-requirements.js",
"predeps": "tools/check-dependence.js",
"deps": "make -C ./pybind11/ && tools/install-python.js",
"preinstall": "npm run deps",
"postinstall": "npm run build",
"test": "npm run test:js && npm run test:ts",
"test:js": "tape ./tests/**/*.js",
"test:ts": "ts-node ./node_modules/.bin/tape ./tests/**/*.ts",
"pretest": "npm run lint && bip install numpy==1.17.4",
"test": "ava",
"cov": "nyc --reporter=text-summary npm run test",
"cov:report": "nyc report -r=lcov",
"lint": "eslint . -c .eslintrc.js --no-eslintrc && ./clang-format.py",
"lint": "npm run lint:js && npm run lint:clang",
"lint:js": "eslint . -c .eslintrc.js --no-eslintrc",
"lint:clang": "./clang-format.py",
"build": "npm run compile",
"pretest": "npm run lint",
"codecov": "nyc report --reporter=lcovonly && codecov",

@@ -41,2 +43,11 @@ "htmlcov": "nyc report --reporter=html",

"homepage": "https://github.com/alibaba/pipcook#readme",
"ava": {
"extensions": [
"js",
"ts"
],
"require": [
"ts-node/register"
]
},
"dependencies": {

@@ -48,7 +59,6 @@ "bindings": "^1.5.0",

"devDependencies": {
"@types/tape": "^4.13.0",
"ava": "^3.13.0",
"codecov": "^3.6.5",
"eslint": "^6.7.2",
"eslint": "^7.15.0",
"nyc": "^15.1.0",
"tape": "^5.0.1",
"ts-node": "^8.6.2"

@@ -59,3 +69,3 @@ },

},
"gitHead": "93832fc6d2a4a0c300572060c4fb0272a9a26612"
"gitHead": "669a342abc54e7615cb34d1be1ad3e65c808f042"
}

@@ -1,2 +0,9 @@

const test = require('tape');
// check if worker_threads is enabled.
try {
require.resolve('worker_threads');
} catch (e) {
console.log('just skip the module because worker_threads not found');
return;
}
const { Worker, isMainThread, workerData, parentPort } = require('worker_threads');

@@ -14,11 +21,10 @@ const boa = require('../../');

if (isMainThread) {
test('run functions with worker_threads', t => {
t.plan(6);
const test = require('ava');
test.cb('run functions with worker_threads', t => {
const foo = new Foobar();
const descriptor = foo.toString();
const owned = foo[symbols.GetOwnershipSymbol]();
t.equal(owned, true, 'the main thread owns the object before creating shared objects');
t.is(owned, true, 'the main thread owns the object before creating shared objects');
console.log(`create a foo object with ownership(${owned})`);
const worker = new Worker(__filename, {

@@ -30,4 +36,4 @@ workerData: {

console.log('main: worker is started and send an object', descriptor);
t.throws(() => foo.toString(), 'Object is owned by another thread.');
t.throws(() => new SharedPythonObject(foo), 'Object is owned by another thread.');
t.throws(() => foo.toString(), { message: 'Object is owned by another thread.' });
t.throws(() => new SharedPythonObject(foo), { message: 'Object is owned by another thread.' });

@@ -37,5 +43,5 @@ let expectedOwnership = false;

const ownership = foo[symbols.GetOwnershipSymbol]();
t.equal(ownership, expectedOwnership, `ownership should be ${expectedOwnership}.`);
t.is(ownership, expectedOwnership, `ownership should be ${expectedOwnership}.`);
}, 1000);
worker.on('message', state => {

@@ -42,0 +48,0 @@ if (state === 'done') {

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -7,15 +7,14 @@ const builtins = boa.builtins();

test('keyword arguments throws', t => {
t.throws(() => boa.kwargs(false), TypeError);
t.throws(() => boa.kwargs(true), TypeError);
t.throws(() => boa.kwargs('foobar'), TypeError);
t.throws(() => boa.kwargs(123), TypeError);
t.end();
t.throws(() => boa.kwargs(false), { instanceOf: TypeError });
t.throws(() => boa.kwargs(true), { instanceOf: TypeError });
t.throws(() => boa.kwargs('foobar'), { instanceOf: TypeError });
t.throws(() => boa.kwargs(123), { instanceOf: TypeError });
});
test('hash function', t => {
t.ok(builtins.__hash__());
t.equal(builtins['__notexists__'], undefined);
t.is(Boolean(builtins.__hash__()), true);
t.is(builtins['__notexists__'], undefined);
const mlist = builtins.list([1, 3, 5]);
t.strictEqual(JSON.stringify({ foobar: mlist }),
t.is(JSON.stringify({ foobar: mlist }),
'{"foobar":[1,3,5]}');

@@ -25,7 +24,6 @@

mlist[1] = 4;
t.strictEqual(mlist[0], 2);
t.strictEqual(mlist[1], 4);
t.strictEqual(JSON.stringify({ foofoo: mlist }),
t.is(mlist[0], 2);
t.is(mlist[1], 4);
t.is(JSON.stringify({ foofoo: mlist }),
'{"foofoo":[2,4,5]}');
t.end();
});

@@ -37,6 +35,5 @@

const f = new pybasic.Foobar();
t.strictEqual(f[PyGetAttrSymbol]('test'), 'pythonworld', 'getattr is ok');
t.is(f[PyGetAttrSymbol]('test'), 'pythonworld', 'getattr is ok');
f[PySetAttrSymbol]('test', 'updated');
t.strictEqual(f[PyGetAttrSymbol]('test'), 'updated', 'setattr is ok');
t.end();
t.is(f[PyGetAttrSymbol]('test'), 'updated', 'setattr is ok');
});

@@ -47,8 +44,7 @@

// test for getitemm and setitem
t.strictEqual(mlist[PyGetItemSymbol](0), 1, 'mlist[0] = 1');
t.strictEqual(mlist[PyGetItemSymbol](1), 3, 'mlist[1] = 3');
t.is(mlist[PyGetItemSymbol](0), 1, 'mlist[0] = 1');
t.is(mlist[PyGetItemSymbol](1), 3, 'mlist[1] = 3');
mlist[PySetItemSymbol](0, 100);
t.strictEqual(mlist[PyGetItemSymbol](0), 100, 'setitem is ok');
t.strictEqual(mlist[PyGetAttrSymbol]('__len__')(), 2, 'use getattr to check mlist length');
t.end();
t.is(mlist[PyGetItemSymbol](0), 100, 'setitem is ok');
t.is(mlist[PyGetAttrSymbol]('__len__')(), 2, 'use getattr to check mlist length');
});

@@ -64,6 +60,5 @@

const d = new EmptyDict();
t.equal(JSON.stringify(d), '{"foobar":10}');
t.equal(builtins.type(d).__name__, 'EmptyDict');
t.equal(d.foobar, 10);
t.end();
t.is(JSON.stringify(d), '{"foobar":10}');
t.is(builtins.type(d).__name__, 'EmptyDict');
t.is(d.foobar, 10);
});

@@ -79,5 +74,5 @@

const f = new Foobar();
t.equal(f.test, 'pythonworld');
t.equal(f.ping('yorkie'), 'hello <yorkie> on pythonworld');
t.equal(f.callfunc(x => x * 2), 233 * 2);
t.is(f.test, 'pythonworld');
t.is(f.ping('yorkie'), 'hello <yorkie> on pythonworld');
t.is(f.callfunc(x => x * 2), 233 * 2);

@@ -92,4 +87,3 @@ const v = f.testObjPass({

// fn2(fn1(input));
t.equal(v, 400);
t.end();
t.is(v, 400);
});

@@ -114,10 +108,9 @@

const f = new FoobarList();
t.equal(f[0], 1);
t.equal(f[1], 3);
t.equal(f[2], 7);
t.equal(len(f), 3);
t.end();
t.is(f[0], 1);
t.is(f[1], 3);
t.is(f[2], 7);
t.is(len(f), 3);
});
test('with-statement normal flow', t => {
test.cb('with-statement normal flow', t => {
const { open } = builtins;

@@ -135,16 +128,15 @@ boa.with(open(__filename, 'r'), f => {

const { open } = builtins;
t.throws(() => boa.with({}), TypeError);
t.throws(() => boa.with(open(__filename, 'r')), TypeError);
t.end();
t.throws(() => boa.with({}), { instanceOf: TypeError });
t.throws(() => boa.with(open(__filename, 'r')), { instanceOf: TypeError });
});
test('with-statement python exceptions', t => {
test.cb('with-statement python exceptions', t => {
const { Foobar } = boa.import('tests.base.basic');
const mfoobar = new Foobar();
boa.with(mfoobar, () => {
t.equal(mfoobar.entered, true, 'foobar entered');
t.is(mfoobar.entered, true, 'foobar entered');
// throw error
mfoobar.hellomsg(233);
});
t.equal(mfoobar.exited, true, 'foobar exited');
t.is(mfoobar.exited, true, 'foobar exited');

@@ -161,12 +153,12 @@ mfoobar.__exitcode__ = 1;

const [r0, r1,, r3] = range(0, 10);
t.equal(r0[0], r0[1]);
t.equal(r1[0], r1[1]);
t.equal(r3[0], r3[1]);
t.is(r0[0], r0[1]);
t.is(r1[0], r1[1]);
t.is(r3[0], r3[1]);
const [...iter] = range(0, 10);
t.equal(iter.length, 10);
t.is(iter.length, 10);
const [i0, ...iter2] = range(0, 10);
t.equal(i0[0], i0[1]);
t.equal(iter2.length, 9);
t.is(i0[0], i0[1]);
t.is(iter2.length, 9);
t.throws(() => {

@@ -176,4 +168,3 @@ // eslint-disable-next-line no-unused-vars

// Should throw the error
}, TypeError);
t.end();
}, { instanceOf: TypeError });
});

@@ -183,3 +174,2 @@

t.throws(() => boa.import('noneexistent-module'));
t.end();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -6,8 +6,6 @@ const { range, enumerate } = boa.builtins();

test('builtins.enumerate', t => {
t.plan(11);
const r = enumerate(range(0, 10)).forEach((v, i) => {
t.equal(v, i);
t.is(v, i);
});
t.equal(r, undefined);
t.end();
t.is(r, undefined);
});

@@ -17,13 +15,12 @@

const [r0, r1,, r3] = enumerate(range(0, 10));
t.equal(r0[0], r0[1]);
t.equal(r1[0], r1[1]);
t.equal(r3[0], r3[1]);
t.is(r0[0], r0[1]);
t.is(r1[0], r1[1]);
t.is(r3[0], r3[1]);
const [...iter] = enumerate(range(0, 10));
t.equal(iter.length, 10);
t.is(iter.length, 10);
const [i0, ...iter2] = enumerate(range(0, 10));
t.equal(i0[0], i0[1]);
t.equal(iter2.length, 9);
t.end();
t.is(i0[0], i0[1]);
t.is(iter2.length, 9);
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -11,6 +11,5 @@ const pybasic = boa.import('tests.base.basic');

for (const ele of generator) {
t.equal(ele, count);
t.is(ele, count);
count -= 1;
}
t.end();
});

@@ -26,9 +25,8 @@

t.equal(val.value, count);
t.equal(val.done, false);
t.is(val.value, count);
t.is(val.done, false);
val = generator.next();
t.equal(val.value, undefined);
t.equal(val.done, true);
t.end();
t.is(val.value, undefined);
t.is(val.done, true);
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const callee = require('../../lib/delegators/callee');

@@ -6,5 +6,4 @@

const fn = callee();
t.strictEqual(typeof fn, 'function');
t.throws(fn, TypeError);
t.end();
t.is(typeof fn, 'function');
t.throws(fn, { instanceOf: TypeError });
});

@@ -1,9 +0,8 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');
test('simple eval', t => {
t.equal(boa.eval`10`, 10);
t.equal(boa.eval`10 + 20`, 30);
t.equal(boa.eval('10 + 20'), 30);
t.end();
t.is(boa.eval`10`, 10);
t.is(boa.eval`10 + 20`, 30);
t.is(boa.eval('10 + 20'), 30);
});

@@ -15,10 +14,9 @@

const y = 100;
t.equal(boa.eval`${y} + 10`, 110);
t.equal(boa.eval`len(${x})`, 2);
t.is(boa.eval`${y} + 10`, 110);
t.is(boa.eval`len(${x})`, 2);
{
const res = boa.eval`${y} + ${x}`;
t.equal(res.shape[0], x.shape[0]);
t.equal(res.shape[1], x.shape[1]);
t.is(res.shape[0], x.shape[0]);
t.is(res.shape[1], x.shape[1]);
}
t.end();
});

@@ -1,10 +0,9 @@

const test = require('tape');
const test = require('ava');
const utils = require('../../lib/utils');
test('utils.getIndent', t => {
t.equal(utils.getIndent(['']), 0);
t.equal(utils.getIndent([' ']), 0);
t.equal(utils.getIndent([' s']), 1);
t.equal(utils.getIndent([' s s']), 1);
t.end();
t.is(utils.getIndent(['']), 0);
t.is(utils.getIndent([' ']), 0);
t.is(utils.getIndent([' s']), 1);
t.is(utils.getIndent([' s s']), 1);
});

@@ -6,3 +6,3 @@ /* eslint-disable no-process-exit */

const path = require('path');
const test = require('tape');
const test = require('ava');
const { spawnSync } = require('child_process');

@@ -39,17 +39,17 @@

const result = spawnSync(process.execPath, args, options);
t.strictEqual(result.signal, null);
t.strictEqual(result.status, 0);
t.is(result.signal, null);
t.is(result.status, 0);
t.end();
}
test('python stdlib', t => check(t, './py/test-esm-loader-stdlib.mjs'));
test.cb('python stdlib', t => check(t, './py/test-esm-loader-stdlib.mjs'));
test('python thirdparty', t => check(t, './py/test-esm-loader-thirdparty.mjs'));
test.cb('python thirdparty', t => check(t, './py/test-esm-loader-thirdparty.mjs'));
test('python custom', t => check(t, './py/test-esm-loader-custom.mjs'));
test.cb('python custom', t => check(t, './py/test-esm-loader-custom.mjs'));
test('javascript thirdparty', t => check(t, './js/test-esm-loader-thirdparty.mjs'));
test.cb('javascript thirdparty', t => check(t, './js/test-esm-loader-thirdparty.mjs'));
test('javascript custom', t => check(t, './js/test-esm-loader-custom.mjs'));
test.cb('javascript custom', t => check(t, './js/test-esm-loader-custom.mjs'));
test('dynamic imports', t => check(t, './py/test-esm-loader-dynamic-imports.mjs'));
test.cb('dynamic imports', t => check(t, './py/test-esm-loader-dynamic-imports.mjs'));

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -6,5 +6,5 @@ const np = boa.import('numpy');

test('the numpy constants', t => {
t.equal(np.Inf, Infinity);
t.equal(np.NINF, -Infinity);
t.ok(isNaN(np.NAN, NaN));
t.is(np.Inf, Infinity);
t.is(np.NINF, -Infinity);
t.assert(isNaN(np.NAN, NaN));

@@ -16,3 +16,2 @@ // TODOs

console.log(np.pi);
t.end();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -8,7 +8,7 @@ const np = boa.import('numpy');

return (s, expect) => {
t.equal(type(s).__name__, 'tuple', 'shape should be a tuple');
t.equal(len(s), expect.length,
t.is(type(s).__name__, 'tuple', 'shape should be a tuple');
t.is(len(s), expect.length,
`the shape length for array should be in ${expect.length}`);
expect.forEach((n, i) => {
t.equal(s[i], n, `shape[${i}] should be ${n}`);
t.is(s[i], n, `shape[${i}] should be ${n}`);
});

@@ -20,12 +20,11 @@ };

const x = np.array([[1, 2, 3], [4, 5, 6]], np.int32);
t.equal(JSON.stringify(x), '[[1,2,3],[4,5,6]]');
t.is(JSON.stringify(x), '[[1,2,3],[4,5,6]]');
const testshape = _testshape(t);
t.equal(type(x).__name__, 'ndarray');
t.equal(x.dtype.name, 'int32', 'the dtype should be int32');
t.equal(x.ndim, 2);
t.equal(x.size, 6);
t.is(type(x).__name__, 'ndarray');
t.is(x.dtype.name, 'int32', 'the dtype should be int32');
t.is(x.ndim, 2);
t.is(x.size, 6);
testshape(x.shape, [2, 3]);
t.end();
});

@@ -36,7 +35,6 @@

const testshape = _testshape(t);
t.equal(type(x).__name__, 'ndarray');
t.equal(x.ndim, 2);
t.equal(x.size, 15);
t.is(type(x).__name__, 'ndarray');
t.is(x.ndim, 2);
t.is(x.size, 15);
testshape(x.shape, [3, 5]);
t.end();
});

@@ -47,6 +45,5 @@

const testshape = _testshape(t);
t.equal(x.ndim, 2);
t.equal(x.size, 12);
t.is(x.ndim, 2);
t.is(x.size, 12);
testshape(x.shape, [3, 4]);
t.end();
});

@@ -57,7 +54,6 @@

const testshape = _testshape(t);
t.equal(x.dtype.name, 'int16');
t.equal(x.ndim, 3);
t.equal(x.size, 2 * 3 * 4);
t.is(x.dtype.name, 'int16');
t.is(x.ndim, 3);
t.is(x.size, 2 * 3 * 4);
testshape(x.shape, [2, 3, 4]);
t.end();
});

@@ -68,6 +64,5 @@

const testshape = _testshape(t);
t.equal(x.ndim, 2);
t.equal(x.size, 12);
t.is(x.ndim, 2);
t.is(x.size, 12);
testshape(x.shape, [3, 4]);
t.end();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -14,3 +14,3 @@ const np = boa.import('numpy');

}
t.end();
t.pass();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -7,4 +7,3 @@ const np = boa.import('numpy');

const r = np.fv(0.05 / 12, 10 * 12, -100, -100);
t.equal(r, 15692.928894335748);
t.end();
t.is(r, 15692.928894335748);
});

@@ -14,4 +13,3 @@

const r = np.pv(0.05 / 12, 10 * 12, -100, 15692.93)
t.equal(r, -100.00067131625819);
t.end();
t.is(r, -100.00067131625819);
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -8,3 +8,3 @@ const np = boa.import('numpy');

// BigInt is required.
t.end();
t.pass();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -12,5 +12,4 @@ const np = boa.import('numpy');

const m = np.asmatrix(x);
t.equal(JSON.stringify(m.tolist()), '[[1,2],[3,4]]');
t.equal(type(m).__name__, 'matrix');
t.end();
t.is(JSON.stringify(m.tolist()), '[[1,2],[3,4]]');
t.is(type(m).__name__, 'matrix');
});

@@ -20,4 +19,3 @@

const m = np.matlib.empty(tuple([2, 2]));
t.equal(type(m).__name__, 'matrix');
t.end();
t.is(type(m).__name__, 'matrix');
});

@@ -27,6 +25,5 @@

const m1 = np.matlib.zeros(tuple([2, 3]));
t.equal(type(m1).__name__, 'matrix');
t.is(type(m1).__name__, 'matrix');
const m2 = np.matlib.zeros(2);
t.equal(type(m2).__name__, 'matrix');
t.end();
t.is(type(m2).__name__, 'matrix');
});

@@ -36,6 +33,5 @@

const m1 = np.matlib.ones(tuple([2, 3]));
t.equal(type(m1).__name__, 'matrix');
t.is(type(m1).__name__, 'matrix');
const m2 = np.matlib.ones(2);
t.equal(type(m2).__name__, 'matrix');
t.end();
t.is(type(m2).__name__, 'matrix');
});

@@ -48,4 +44,3 @@

}));
t.equal(type(m).__name__, 'matrix');
t.end();
t.is(type(m).__name__, 'matrix');
});

@@ -57,4 +52,3 @@

}));
t.equal(type(m).__name__, 'matrix');
t.end();
t.is(type(m).__name__, 'matrix');
});

@@ -78,3 +72,3 @@

}
t.end();
t.pass();
});

@@ -91,3 +85,3 @@

}
t.end();
t.pass();
});

@@ -105,3 +99,3 @@

// TODO: matrix doesn't support operators like +/-/*.
t.end();
t.pass();
});

@@ -113,3 +107,3 @@

const m1 = mb.add(20);
t.equal(`${m1.A1}`, '[21 22 23 24]');
t.is(`${m1.A1}`, '[21 22 23 24]');
// simple test

@@ -122,5 +116,5 @@ console.log(m1.sub(10));

console.log(m1.ipow(3));
t.end();
t.pass();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -7,3 +7,4 @@ const np = boa.import('numpy');

console.log(`${np.typecodes['All']}`);
t.end();
});
t.pass();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -6,9 +6,8 @@ const builtins = boa.builtins();

test('builtins constants', t => {
t.strictEqual(builtins.True, true);
t.strictEqual(builtins.False, false);
t.strictEqual(builtins.None, null);
t.ok(builtins.NotImplemented);
t.ok(builtins.Ellipsis);
t.ok(builtins.__debug__);
t.end();
t.is(builtins.True, true);
t.is(builtins.False, false);
t.is(builtins.None, null);
t.is(Boolean(builtins.NotImplemented), true);
t.is(Boolean(builtins.Ellipsis), true);
t.is(Boolean(builtins.__debug__), true);
});

@@ -18,7 +17,6 @@

const { abs } = builtins;
t.equal(abs(100), 100);
t.equal(abs(-100), 100);
t.equal(abs(10.06), 10.06);
t.equal(abs(-10.06), 10.06);
t.end();
t.is(abs(100), 100);
t.is(abs(-100), 100);
t.is(abs(10.06), 10.06);
t.is(abs(-10.06), 10.06);
});

@@ -28,5 +26,4 @@

const { bin } = builtins;
t.equal(bin(3), '0b11');
t.equal(bin(-10), '-0b1010');
t.end();
t.is(bin(3), '0b11');
t.is(bin(-10), '-0b1010');
});

@@ -37,5 +34,4 @@

const bval = bytes.fromhex('2Ef0 F1f2');
t.equal(type(bval).__name__, 'bytes');
t.equal(bval.hex(), '2ef0f1f2');
t.end();
t.is(type(bval).__name__, 'bytes');
t.is(bval.hex(), '2ef0f1f2');
});

@@ -45,9 +41,7 @@

const { hash } = builtins;
t.equal(typeof hash(hash), 'number');
t.end();
t.is(typeof hash(hash), 'number');
});
test('`builtins.help()` function', t => {
builtins.help(builtins.abs);
t.end();
t.is(typeof builtins.help(builtins.abs), 'object');
});

@@ -57,11 +51,9 @@

const { hex } = builtins;
t.equal(hex(255), '0xff');
t.equal(hex(-42), '-0x2a');
t.end();
t.is(hex(255), '0xff');
t.is(hex(-42), '-0x2a');
});
test('`builtins.int` class', t => {
t.equal(builtins.int(16), 16);
t.equal(builtins.int(255), 255);
t.end();
t.is(builtins.int(16), 16);
t.is(builtins.int(255), 255);
});

@@ -73,6 +65,5 @@

const bar = list(foo);
t.equal(len(bar), foo.length);
t.equal(len(foo), len(bar));
foo.forEach((v, i) => t.equal(bar[i], v));
t.end();
t.is(len(bar), foo.length);
t.is(len(foo), len(bar));
foo.forEach((v, i) => t.is(bar[i], v));
});

@@ -88,5 +79,4 @@

const arr = [30, 31, 32, 100];
t.equal(len(dict(boa.kwargs(obj))), Object.keys(obj).length);
t.equal(len(arr), arr.length);
t.end();
t.is(len(dict(boa.kwargs(obj))), Object.keys(obj).length);
t.is(len(arr), arr.length);
});

@@ -96,7 +86,6 @@

const { min, max } = builtins;
t.equal(min([1, 2, 3]), 1);
t.equal(max([1, 2, 3]), 3);
t.equal(min(1, 2, 3), 1);
t.equal(max(1, 2, 3), 3);
t.end();
t.is(min([1, 2, 3]), 1);
t.is(max([1, 2, 3]), 3);
t.is(min(1, 2, 3), 1);
t.is(max(1, 2, 3), 3);
});

@@ -109,5 +98,4 @@

chars.forEach(c => {
t.equal(ord(c), c.charCodeAt(0), `ord(${c}) is right`);
t.is(ord(c), c.charCodeAt(0), `ord(${c}) is right`);
});
t.end();
});

@@ -117,5 +105,4 @@

const { pow } = builtins;
t.equal(pow(10, 2), 100);
t.equal(pow(38, 10, 97), 66);
t.end();
t.is(pow(10, 2), 100);
t.is(pow(38, 10, 97), 66);
});

@@ -127,20 +114,20 @@

const r = range(10);
t.equal(len(r), 10, 'the len(range(10)) should be 10');
t.equal(r[0], 0, 'the first should be 0');
t.equal(r[9], 9, 'the last should be 9');
t.is(len(r), 10, 'the len(range(10)) should be 10');
t.is(r[0], 0, 'the first should be 0');
t.is(r[9], 9, 'the last should be 9');
}
{
const r = range(0, 20);
t.equal(len(r), 20);
t.equal(r[0], 0);
t.equal(r[19], 19);
t.is(len(r), 20);
t.is(r[0], 0);
t.is(r[19], 19);
}
{
const r = range(0, 21, 5);
t.equal(len(r), 5);
t.equal(r[0], 0);
t.equal(r[1], 5);
t.equal(r[2], 10);
t.equal(r[3], 15);
t.equal(r[4], 20);
t.is(len(r), 5);
t.is(r[0], 0);
t.is(r[1], 5);
t.is(r[2], 10);
t.is(r[3], 15);
t.is(r[4], 20);
}

@@ -150,6 +137,5 @@ {

const s = r.slice(1, 5, 1);
t.equal(len(s), len(r) - 1);
t.equal(s[0], r[1]);
t.is(len(s), len(r) - 1);
t.is(s[0], r[1]);
}
t.end();
});

@@ -160,7 +146,6 @@

const n = 10.123;
t.equal(round(n), 10);
t.equal(round(n, 1), 10.1);
t.equal(round(n, 2), 10.12);
t.equal(round(n, 3), 10.123);
t.end();
t.is(round(n), 10);
t.is(round(n, 1), 10.1);
t.is(round(n, 2), 10.12);
t.is(round(n, 3), 10.123);
});

@@ -171,6 +156,5 @@

const aEmptyTuple = tuple();
t.equal(len(aEmptyTuple), 0);
t.is(len(aEmptyTuple), 0);
const aTupleFromRange = tuple(range(0, 20));
t.equal(len(aTupleFromRange), 20);
t.end();
t.is(len(aTupleFromRange), 20);
});

@@ -181,5 +165,4 @@

const aTuple = tuple();
t.equal(type(aTuple).__name__, 'tuple');
t.equal(type(tuple).__name__, 'type');
t.end();
t.is(type(aTuple).__name__, 'tuple');
t.is(type(tuple).__name__, 'type');
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -10,7 +10,6 @@

console.log(v);
t.ok(len(v) === 3);
t.ok(min(v) === 0.3888888888888889);
t.ok(max(v) === 0.8);
t.is(len(v), 3);
t.is(min(v), 0.3888888888888889);
t.is(max(v), 0.8);
}
t.end();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -9,4 +9,3 @@

m.update(s);
console.log(`${m.digest()}`);
t.end();
t.is(typeof m.digest(), 'object');
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const path = require('path');

@@ -10,16 +10,15 @@ const boa = require('../../');

const currl = list(Path('.').iterdir());
t.strictEqual(len(currl) > 0, true);
t.is(len(currl) > 0, true);
}
{
const q = Path('./node_modules');
t.strictEqual(q.exists(), true);
t.strictEqual(q.is_dir(), true);
t.is(q.exists(), true);
t.is(q.is_dir(), true);
}
{
const q = PurePath('foo', 'some/path', 'bar');
t.strictEqual(q.toString(), 'foo/some/path/bar');
t.strictEqual(q.name, 'bar');
t.strictEqual(q.is_absolute(), false);
t.is(q.toString(), 'foo/some/path/bar');
t.is(q.name, 'bar');
t.is(q.is_absolute(), false);
}
t.end();
});

@@ -32,5 +31,4 @@

fp.seek(0);
t.strictEqual(fp.read().toString(), 'b\'Hello world!\'');
t.is(fp.read().toString(), 'b\'Hello world!\'');
fp.close();
t.end();
});

@@ -42,4 +40,3 @@

const files = glob.glob(match);
console.log(`${files[0]}`);
t.end();
t.is(typeof files[0], 'string');
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -25,7 +25,6 @@

t.ok(uuid1());
t.ok(uuid3(NAMESPACE_DNS, 'nodejs.org'));
t.ok(uuid4());
t.ok(uuid5(NAMESPACE_DNS, 'nodejs.org'));
t.end();
t.is(typeof uuid1(), 'object');
t.is(typeof uuid3(NAMESPACE_DNS, 'nodejs.org'), 'object');
t.is(typeof uuid4(), 'object');
t.is(typeof uuid5(NAMESPACE_DNS, 'nodejs.org'), 'object');
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -10,46 +10,44 @@ const { version_info } = boa.import('sys');

// Number-theoretic and representation functions
t.strictEqual(math.ceil(10), 10);
t.strictEqual(math.copysign(1.0, -1.0), -1);
t.strictEqual(math.fabs(-100), 100);
t.strictEqual(math.factorial(8), 40320);
t.strictEqual(math.floor(100.99), 100);
t.strictEqual(math.fmod(50, 100), 50);
t.strictEqual(math.fsum(np.ones(100)), 100);
// t.strictEqual(math.isfinite(Number.POSITIVE_INFINITY));
t.is(math.ceil(10), 10);
t.is(math.copysign(1.0, -1.0), -1);
t.is(math.fabs(-100), 100);
t.is(math.factorial(8), 40320);
t.is(math.floor(100.99), 100);
t.is(math.fmod(50, 100), 50);
t.is(math.fsum(np.ones(100)), 100);
// t.is(math.isfinite(Number.POSITIVE_INFINITY));
// Power and logarithmic functions
t.ok(math.exp(10));
t.ok(math.log(100));
t.assert(math.exp(10));
t.assert(math.log(100));
// Trigonometric functions
t.ok(math.acos(0.1));
t.ok(math.asin(0.2));
t.ok(math.atan(0.3));
t.ok(math.atan2(0.5, 0.5));
t.ok(math.cos(0.1));
t.assert(math.acos(0.1));
t.assert(math.asin(0.2));
t.assert(math.atan(0.3));
t.assert(math.atan2(0.5, 0.5));
t.assert(math.cos(0.1));
if (version_info.major === 3 && version_info.minor >= 8) {
t.ok(math.dist(10, 30));
t.assert(math.dist(10, 30));
}
t.ok(math.sin(0.1));
t.ok(math.tan(0.1));
t.assert(math.sin(0.1));
t.assert(math.tan(0.1));
// Angular conversion
t.ok(math.degrees(0.9));
t.ok(math.radians(30));
t.assert(math.degrees(0.9));
t.assert(math.radians(30));
// Special functions
t.ok(math.erf(0.1));
t.strictEqual(math.gamma(1), 1);
t.strictEqual(math.gamma(2), 1);
t.strictEqual(math.gamma(3), 2);
t.ok(math.lgamma(5));
t.assert(math.erf(0.1));
t.is(math.gamma(1), 1);
t.is(math.gamma(2), 1);
t.is(math.gamma(3), 2);
t.assert(math.lgamma(5));
// Constants
t.strictEqual(math.pi, 3.141592653589793);
t.strictEqual(math.e, 2.718281828459045);
t.strictEqual(math.tau, 6.283185307179586);
t.ok(!isFinite(math.inf));
t.ok(isNaN(math.nan));
t.end();
t.is(math.pi, 3.141592653589793);
t.is(math.e, 2.718281828459045);
t.is(math.tau, 6.283185307179586);
t.assert(!isFinite(math.inf));
t.assert(isNaN(math.nan));
});

@@ -60,18 +58,17 @@

getcontext().prec = 6;
t.strictEqual(`${Decimal(1).truediv(Decimal(7))}`, '0.142857');
t.is(`${Decimal(1).truediv(Decimal(7))}`, '0.142857');
getcontext().prec = 12;
t.strictEqual(`${Decimal(1).truediv(Decimal(7))}`, '0.142857142857');
t.strictEqual(`${Decimal(1).add(2)}`, '3');
t.strictEqual(`${Decimal(10).sub(Decimal(2.3))}`, '7.70000000000');
t.strictEqual(`${Decimal(1.6).mul(Decimal(2.3))}`, '3.68000000000');
t.ok(Decimal(1.6).divmod(Decimal(2.3)));
t.ok(Decimal(1.6).mod(Decimal(2.3)));
t.is(`${Decimal(1).truediv(Decimal(7))}`, '0.142857142857');
t.is(`${Decimal(1).add(2)}`, '3');
t.is(`${Decimal(10).sub(Decimal(2.3))}`, '7.70000000000');
t.is(`${Decimal(1.6).mul(Decimal(2.3))}`, '3.68000000000');
t.assert(Decimal(1.6).divmod(Decimal(2.3)));
t.assert(Decimal(1.6).mod(Decimal(2.3)));
t.strictEqual(Decimal(3.14) == 3.14, true);
t.strictEqual(Decimal(1).exp() == 2.71828182846, true);
t.strictEqual(Decimal(2).fma(3, 5) == 11, true);
t.strictEqual(Decimal('1.41421356').quantize(Decimal('1.000')) == 1.414, true);
t.strictEqual(Decimal(18).remainder_near(Decimal(10)) == -2, true);
t.strictEqual(Decimal(25).remainder_near(Decimal(10)) == 5, true);
t.end();
t.is(Decimal(3.14) == 3.14, true);
t.is(Decimal(1).exp() == 2.71828182846, true);
t.is(Decimal(2).fma(3, 5) == 11, true);
t.is(Decimal('1.41421356').quantize(Decimal('1.000')) == 1.414, true);
t.is(Decimal(18).remainder_near(Decimal(10)) == -2, true);
t.is(Decimal(25).remainder_near(Decimal(10)) == 5, true);
});

@@ -82,8 +79,7 @@

const { Decimal } = boa.import('decimal');
t.strictEqual(Fraction(16, -10) == '-8/5', true);
t.strictEqual(Fraction(123) == '123', true);
t.strictEqual(Fraction('1.414213 \t\n') == '1414213/1000000', true);
t.strictEqual(Fraction('7e-6') == '7/1000000', true);
t.strictEqual(Fraction(Decimal('1.1')) == '11/10', true);
t.end();
t.is(Fraction(16, -10) == '-8/5', true);
t.is(Fraction(123) == '123', true);
t.is(Fraction('1.414213 \t\n') == '1414213/1000000', true);
t.is(Fraction('7e-6') == '7/1000000', true);
t.is(Fraction(Decimal('1.1')) == '11/10', true);
});

@@ -94,7 +90,7 @@

const { len } = boa.builtins();
t.strictEqual(random.randrange(10) <= 10, true);
t.strictEqual(random.randrange(5, 10) >= 5, true);
t.is(random.randrange(10) <= 10, true);
t.is(random.randrange(5, 10) >= 5, true);
{
const choices = ['red', 'black', 'green'];
t.strictEqual(choices.includes(random.choice(choices)), true);
t.is(choices.includes(random.choice(choices)), true);
}

@@ -105,9 +101,8 @@ {

}));
t.strictEqual(len(choices), 3);
t.is(len(choices), 3);
const sample = random.sample([1, 3, 4, 4, 10, 100, 3], 2);
t.strictEqual(len(sample), 2);
t.is(len(sample), 2);
}
t.strictEqual(random.uniform(1, 5) >= 0, true);
t.strictEqual(random.uniform(1, 5) <= 5, true);
t.end();
t.is(random.uniform(1, 5) >= 0, true);
t.is(random.uniform(1, 5) <= 5, true);
});

@@ -127,13 +122,12 @@

t.equal(mean([1, 2, 3, 4, 4]), 2.8);
t.equal(mean([-1.0, 2.5, 3.25, 5.75]), 2.625);
t.equal(median([1, 3, 5]), 3);
t.equal(median([1, 3, 5, 7]), 4.0);
t.equal(median_low([1, 3, 5, 7]), 3);
t.equal(median_high([1, 3, 5, 7]), 5);
t.equal(median_grouped([52, 52, 53, 54]), 52.5);
t.equal(mode(['red', 'blue', 'blue', 'red', 'green', 'red', 'red']), 'red');
t.equal(pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]), 0.986893273527251);
t.equal(variance([2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]), 1.3720238095238095);
t.end();
t.is(mean([1, 2, 3, 4, 4]), 2.8);
t.is(mean([-1.0, 2.5, 3.25, 5.75]), 2.625);
t.is(median([1, 3, 5]), 3);
t.is(median([1, 3, 5, 7]), 4.0);
t.is(median_low([1, 3, 5, 7]), 3);
t.is(median_high([1, 3, 5, 7]), 5);
t.is(median_grouped([52, 52, 53, 54]), 52.5);
t.is(mode(['red', 'blue', 'blue', 'red', 'green', 'red', 'red']), 'red');
t.is(pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]), 0.986893273527251);
t.is(variance([2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]), 1.3720238095238095);
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const path = require('path');

@@ -17,3 +17,3 @@ const boa = require('../../');

console.log(`os.getpid() is ${os.getpid()}`);
t.end();
t.pass();
});

@@ -34,3 +34,3 @@

}
t.end();
t.pass();
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -6,26 +6,25 @@ const sys = boa.import('sys');

test('the `sys` constants', t => {
t.ok(sys.abiflags);
t.ok(sys.argv);
t.ok(sys.base_exec_prefix);
t.ok(sys.base_prefix);
t.ok(sys.byteorder);
t.ok(sys.builtin_module_names);
t.ok(sys.copyright);
t.ok(typeof sys.dont_write_bytecode === 'boolean');
t.ok(sys.getdefaultencoding() === 'utf-8');
t.ok(sys.getdlopenflags());
t.ok(sys.hash_info.width);
t.ok(sys.hash_info.inf);
t.ok(sys.hash_info.nan === 0);
t.ok(sys.hexversion);
t.ok(sys.maxsize);
t.ok(sys.maxunicode);
t.ok(sys.path);
t.ok(sys.platform === process.platform);
t.ok(sys.prefix);
t.ok(sys.thread_info.name);
t.ok(sys.version);
t.ok(sys.version_info.major === 3);
t.ok(sys.version_info.minor >= 0);
t.end();
t.assert(sys.abiflags);
t.assert(sys.argv);
t.assert(sys.base_exec_prefix);
t.assert(sys.base_prefix);
t.assert(sys.byteorder);
t.assert(sys.builtin_module_names);
t.assert(sys.copyright);
t.assert(typeof sys.dont_write_bytecode === 'boolean');
t.assert(sys.getdefaultencoding() === 'utf-8');
t.assert(sys.getdlopenflags());
t.assert(sys.hash_info.width);
t.assert(sys.hash_info.inf);
t.assert(sys.hash_info.nan === 0);
t.assert(sys.hexversion);
t.assert(sys.maxsize);
t.assert(sys.maxunicode);
t.assert(sys.path);
t.assert(sys.platform === process.platform);
t.assert(sys.prefix);
t.assert(sys.thread_info.name);
t.assert(sys.version);
t.assert(sys.version_info.major === 3);
t.assert(sys.version_info.minor >= 0);
});

@@ -1,2 +0,2 @@

const test = require('tape');
const test = require('ava');
const boa = require('../../');

@@ -6,13 +6,10 @@ const string = boa.import('string');

test('String constants', t => {
t.strictEqual(string.ascii_letters,
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
t.strictEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz');
t.strictEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
t.strictEqual(string.digits, '0123456789');
t.strictEqual(string.hexdigits, '0123456789abcdefABCDEF');
t.strictEqual(string.octdigits, '01234567');
t.strictEqual(string.punctuation,
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~');
t.ok(string.whitespace);
t.end();
t.is(string.ascii_letters, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
t.is(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz');
t.is(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
t.is(string.digits, '0123456789');
t.is(string.hexdigits, '0123456789abcdefABCDEF');
t.is(string.octdigits, '01234567');
t.is(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~');
t.assert(string.whitespace);
});

@@ -22,6 +19,5 @@

const fmt = string.Formatter();
t.strictEqual(fmt.format('foobar {0} {1}', 'a', 'b'), 'foobar a b');
t.strictEqual(fmt.format('foobar {name}', boa.kwargs({ name: 'test' })),
'foobar test');
t.end();
t.is(fmt.format('foobar {0} {1}', 'a', 'b'), 'foobar a b');
t.is(fmt.format('foobar {name}', boa.kwargs({ name: 'test' })),
'foobar test');
});

@@ -35,4 +31,3 @@

}));
t.strictEqual(actual, 'tim likes kung pao');
t.end();
t.is(actual, 'tim likes kung pao');
});

@@ -43,4 +38,3 @@

const m = re.search('(?<=abc)def', 'abcdef');
t.equal(m.group(0), 'def');
t.end();
t.is(m.group(0), 'def');
});

@@ -53,13 +47,12 @@

} = boa.import('difflib');
t.ok(get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']));
t.assert(get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']));
{
const s = SequenceMatcher(null, ' abcd', 'abcd abcd');
const m = s.find_longest_match(0, 5, 0, 9);
t.strictEqual(m.a, 0);
t.strictEqual(m.b, 4);
t.strictEqual(m.size, 5);
t.is(m.a, 0);
t.is(m.b, 4);
t.is(m.size, 5);
}
t.strictEqual(SequenceMatcher(null, 'tide', 'diet').ratio(), 0.25);
t.strictEqual(SequenceMatcher(null, 'diet', 'tide').ratio(), 0.5);
t.end();
t.is(SequenceMatcher(null, 'tide', 'diet').ratio(), 0.25);
t.is(SequenceMatcher(null, 'diet', 'tide').ratio(), 0.5);
});

@@ -69,16 +62,15 @@

const { shorten, indent } = boa.import('textwrap');
t.strictEqual(
t.is(
shorten('Hello world!', boa.kwargs({ width: 12 })),
'Hello world!'
);
t.strictEqual(
t.is(
shorten('Hello world!', boa.kwargs({ width: 11 })),
'Hello [...]'
);
t.strictEqual(
t.is(
shorten('Hello world!', boa.kwargs({ width: 10, placeholder: '...' })),
'Hello...'
);
t.strictEqual(indent('hello', '\t'), '\thello');
t.end();
t.is(indent('hello', '\t'), '\thello');
});

@@ -88,8 +80,7 @@

const unicodedata = boa.import('unicodedata');
t.strictEqual(unicodedata.lookup('LEFT CURLY BRACKET'), '{');
t.strictEqual(unicodedata.name('/'), 'SOLIDUS');
t.strictEqual(unicodedata.decimal('9'), 9);
t.strictEqual(unicodedata.category('A'), 'Lu');
t.strictEqual(unicodedata.bidirectional('\u0660'), 'AN');
t.end();
t.is(unicodedata.lookup('LEFT CURLY BRACKET'), '{');
t.is(unicodedata.name('/'), 'SOLIDUS');
t.is(unicodedata.decimal('9'), 9);
t.is(unicodedata.category('A'), 'Lu');
t.is(unicodedata.bidirectional('\u0660'), 'AN');
});

@@ -0,14 +1,13 @@

import test from 'ava';
import * as boa from '../..';
import test from 'tape';
test('test typescript import builtins', (t: test.Test) => {
test('test typescript import builtins', (t) => {
const builtins = boa.builtins();
t.strictEqual(typeof builtins.toString(), 'string');
t.is(typeof builtins.toString(), 'string');
const mlist = builtins.list([1, 3, 5]);
t.strictEqual(JSON.stringify({ foobar: mlist }),
'{"foobar":[1,3,5]}');
t.end();
t.is(JSON.stringify({ foobar: mlist }),
'{"foobar":[1,3,5]}');
});
test('test typescript import official module', (t: test.Test) => {
test('test typescript import official module', (t) => {
const colorsys = boa.import('colorsys');

@@ -18,14 +17,11 @@ const { len, min, max } = boa.builtins();

const v = colorsys.rgb_to_hsv(0.2, 0.8, 0.4);
console.log(v);
t.ok(len(v) === 3);
t.ok(min(v) === 0.3888888888888889);
t.ok(max(v) === 0.8);
t.is(len(v), 3);
t.is(min(v), 0.3888888888888889);
t.is(max(v), 0.8);
}
t.end();
});
test('test typescript symbols', (t: test.Test) => {
test('test typescript symbols', (t) => {
const colorsys = boa.import('colorsys');
t.strictEqual(colorsys[boa.symbols.GetOwnershipSymbol](), true);
t.end();
t.is(colorsys[boa.symbols.GetOwnershipSymbol](), true);
});

@@ -0,23 +1,21 @@

import test from 'ava';
import * as boa from '../../';
import test from 'tape';
test('test typescript eval(simple)', (t: test.Test) => {
t.equal(boa.eval`10`, 10);
t.equal(boa.eval`10 + 20`, 30);
t.equal(boa.eval('10 + 20'), 30);
t.end();
test('test typescript eval(simple)', (t) => {
t.is(boa.eval`10` as any, 10);
t.is(boa.eval`10 + 20` as any, 30);
t.is(boa.eval('10 + 20') as any, 30);
});
test('test typescript eval(context)', (t: test.Test) => {
test('test typescript eval(context)', (t) => {
const np = boa.import('numpy');
const x = np.array([[1, 2, 3], [4, 5, 6]], np.int32);
const y = 100;
t.equal(boa.eval`${y} + 10`, 110);
t.equal(boa.eval`len(${x})`, 2);
t.is(boa.eval`${y} + 10` as any, 110);
t.is(boa.eval`len(${x})` as any, 2);
{
const res = boa.eval`${y} + ${x}`;
t.equal(res.shape[0], x.shape[0]);
t.equal(res.shape[1], x.shape[1]);
t.is(res.shape[0], x.shape[0]);
t.is(res.shape[1], x.shape[1]);
}
t.end();
});
import * as boa from '../../';
import test from 'tape';
import test from 'ava';
test('test typescript kwargs', (t: test.Test) => {
test('test typescript kwargs', (t) => {
const string = boa.import('string');
const fmt = string.Formatter();
t.strictEqual(fmt.format('foobar {0} {1}', 'a', 'b'), 'foobar a b');
t.strictEqual(fmt.format('foobar {name}', boa.kwargs({ name: 'test' })),
'foobar test');
t.end();
t.is(fmt.format('foobar {0} {1}', 'a', 'b'), 'foobar a b');
t.is(fmt.format('foobar {name}', boa.kwargs({ name: 'test' })),
'foobar test');
});
import * as boa from '../../';
import test from 'tape';
import test from 'ava';
test('test typescript with-statement', (t: test.Test) => {
test.cb('test typescript with-statement', (t) => {
t.plan(1);

@@ -6,0 +6,0 @@ const { open } = boa.builtins();

@@ -0,9 +1,5 @@

#!/usr/bin/env node
'use strict';
const { run, PLATFORM } = require('./utils');
const majorVersion = process.version.split('.')[0];
if (parseInt(majorVersion.substr(1)) < 12) {
throw new TypeError(`require Node.js >= v12.0.0, but ${process.version} found`);
}
const cmds = [ 'rm', 'make', 'tar' ];

@@ -16,3 +12,3 @@

} else {
throw new TypeError(`No support for your platform ${PLATFORM}`);
throw new TypeError(`no support for your platform ${PLATFORM}`);
}

@@ -19,0 +15,0 @@

@@ -0,1 +1,3 @@

#!/usr/bin/env node
'use strict';

@@ -2,0 +4,0 @@

@@ -0,1 +1,3 @@

#!/usr/bin/env node
'use strict';

@@ -2,0 +4,0 @@

@@ -0,55 +1,47 @@

#!/usr/bin/env node
'use strict';
const { run, py, initAndGetCondaPath, PLATFORM, ARCH } = require('./utils');
const utils = require('./utils');
const fs = require('fs');
const path = require('path');
let CONDA_DOWNLOAD_PREFIX = 'https://repo.anaconda.com/miniconda';
if (process.env.BOA_TUNA) {
CONDA_DOWNLOAD_PREFIX = 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda';
}
if (process.env.BOA_CONDA_MIRROR) {
CONDA_DOWNLOAD_PREFIX = process.env.BOA_CONDA_MIRROR;
}
const run = utils.run.bind(utils);
const py = utils.py.bind(utils);
const CONDA_LOCAL_PATH = initAndGetCondaPath();
let condaDownloadName = process.env.CONDA_PACKAGE_NAME || 'Miniconda3-4.7.12.1';
if (PLATFORM === 'linux') {
condaDownloadName += '-Linux';
} else if (PLATFORM === 'darwin') {
condaDownloadName += '-MacOSX';
} else {
throw new TypeError(`No support for your platform ${PLATFORM}`);
if (!utils.shouldInstallConda()) {
console.info('skip installing the python from conda.');
return process.exit(0);
}
if (ARCH === 'x64') {
condaDownloadName += '-x86_64';
} else if (ARCH === 'ppc64') {
condaDownloadName += '-ppc64le';
} else if (PLATFORM !== 'darwin') {
condaDownloadName += '-x86';
}
condaDownloadName = `${condaDownloadName}.sh`;
// download and install conda
const remoteURL = utils.getCondaRemote();
const installDir = utils.resolveAndUpdateCondaPath();
const downloader = utils.getCondaDownloaderName();
// download it if not exists.
if (!fs.existsSync(condaDownloadName)) {
run(`curl ${CONDA_DOWNLOAD_PREFIX}/${condaDownloadName} > ${condaDownloadName}`);
// fetch the downloader file if that doesn't exist.
if (!fs.existsSync(downloader)) {
run('curl', `${remoteURL}/${downloader}`, '>', downloader);
}
// check if ./bin/python exists, if not then install it.
if (!fs.existsSync(path.join(CONDA_LOCAL_PATH, 'bin', 'python'))) {
run('rm', `-rf ${CONDA_LOCAL_PATH}`);
run('sh', `./${condaDownloadName}`, `-f -b -p ${CONDA_LOCAL_PATH}`);
// check if the python is installed correctly, we will skip the installation
// when it's installed before.
if (!utils.shouldPythonInstalledOn(installDir)) {
// clean the install dir.
run('rm', '-rf', installDir);
// install
run('sh', downloader, `-f -b -p ${installDir}`);
}
// cleanup the standard libs.
if (PLATFORM === 'darwin') {
run('rm', `-rf ${CONDA_LOCAL_PATH}/lib/libc++*`);
} else if (PLATFORM === 'linux') {
run('rm', `-rf ${CONDA_LOCAL_PATH}/lib/libstdc++.so*`);
run('rm', `-rf ${CONDA_LOCAL_PATH}/lib/libgcc_s.so*`);
if (utils.PLATFORM === 'darwin') {
run('rm', '-rf', `${installDir}/lib/libc++*`);
} else if (utils.PLATFORM === 'linux') {
run('rm', '-rf', `${installDir}/lib/libstdc++.so*`);
run('rm', '-rf', `${installDir}/lib/libgcc_s.so*`);
}
// dump info
py(`${CONDA_LOCAL_PATH}/bin/conda`, 'info -a');
py(`${installDir}/bin/conda`, 'info -a');
// install python packages
utils.installPythonPackages();

@@ -7,77 +7,265 @@ 'use strict';

const { execSync } = require('child_process');
const { BOA_CONDA_PREFIX, BOA_TUNA } = process.env;
// Constants
const CONDA_INSTALL_DIR = path.join(__dirname, '../.CONDA_INSTALL_DIR');
let { BOA_CONDA_INDEX, BOA_PYTHON_VERSION } = process.env;
const CONDA_INSTALL_NAME = '.miniconda';
// Environment variables
let {
/**
* The prefix path for choosing the conda directory, possible values are:
* - {\@package} represents a relative path to the boa installed package.
* - {\@cwd} represents a relative path to the current working directory it depends on shell.
* - {string} represents a absolute path to your installed conda path.
*
* Note that, if the variable is specified with relative path, we will throw an error.
*/
BOA_CONDA_PREFIX = '@package',
/**
* The boolean if installing from tuna mirror.
* @boolean
*/
BOA_TUNA,
/**
* The boolean if installing the conda.
*/
BOA_FORCE_INSTALL,
/**
* The conda remote URL, default is https://repo.anaconda.com/miniconda.
* @string
*/
BOA_CONDA_REMOTE = 'https://repo.anaconda.com/miniconda',
BOA_CONDA_MIRROR,
/**
* The conda version to download from remote URL.
* @string
*/
BOA_CONDA_VERSION = 'Miniconda3-4.7.12.1',
/**
* The conda index URI, if `BOA_TUNA` is specified, it will be set.
* @string
*/
BOA_CONDA_INDEX,
/**
* The python library version, for example 3.7m
* @string
*/
BOA_PYTHON_VERSION = '3.7m',
/**
* Install the base packages: numpy/scikit/...
*/
BOA_PACKAGE_BASE,
/**
* Install the cv packages: opencv
*/
BOA_PACKAGE_CV,
} = process.env;
// Check for BOA_CONDA_PREFIX, throw an TypeError when it's not a relative path.
if (!/\@(package|cwd)/.test(BOA_CONDA_PREFIX) && !path.isAbsolute(BOA_CONDA_PREFIX)) {
throw new TypeError('BOA_CONDA_PREFIX is required to be an absolute path');
}
// aliases
if (typeof BOA_CONDA_MIRROR === 'string' && BOA_CONDA_MIRROR.length > 0) {
BOA_CONDA_REMOTE = BOA_CONDA_MIRROR;
}
// Specify BOA_TUNA for simplifying the env setup.
if (BOA_TUNA && !BOA_CONDA_INDEX) {
if (BOA_TUNA) {
BOA_CONDA_REMOTE = 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda';
BOA_CONDA_INDEX = 'https://pypi.tuna.tsinghua.edu.cn/simple';
}
// run a command
exports.run = (...args) => {
const cmd = args.join(' ');
console.log(`sh "${cmd}"`);
return execSync.call(null, cmd, { stdio: 'inherit' })
};
module.exports = {
/**
* Call to `os.platform()`.
*/
PLATFORM: os.platform(),
/**
* Call to `os.arch()`
*/
ARCH: os.arch(),
// get the platform
exports.PLATFORM = os.platform();
/**
* Compute the state if the build status should install conda.
*/
shouldInstallConda() {
if ('@package' === BOA_CONDA_PREFIX) {
return true;
}
let expectedPath = BOA_CONDA_PREFIX;
if (/^\@cwd/.test(expectedPath)) {
expectedPath = expectedPath.replace('@cwd', process.cwd());
}
if (!fs.existsSync(expectedPath)) {
console.warn(`found the path(${expectedPath}) not exists, conda installation has been switched on.`);
return true;
}
return false;
},
// get the os arch
exports.ARCH = os.arch();
/**
* Resolves the conda path by configs, then update it to the CONDA_INSTALL_DIR dot file, it returns
* the resolved value.
*/
resolveAndUpdateCondaPath() {
let resolvedPrefix;
if (BOA_CONDA_PREFIX === '@package') {
resolvedPrefix = path.join(__dirname, '..');
} else if (/^\@cwd/.test(BOA_CONDA_PREFIX)) {
resolvedPrefix = (BOA_CONDA_PREFIX + '').replace('@cwd', process.cwd());
} else {
resolvedPrefix = BOA_CONDA_PREFIX;
}
const str = path.join(resolvedPrefix, CONDA_INSTALL_NAME);
fs.writeFileSync(CONDA_INSTALL_DIR, str, 'utf8');
return str;
},
// get the conda path
exports.getCondaPath = function getCondaPath() {
const condaDir = fs.readFileSync(CONDA_INSTALL_DIR, 'utf8');
return path.resolve(__dirname, '..', condaDir);
};
/**
* Return the conda remote URL.
*/
getCondaRemote() {
return BOA_CONDA_REMOTE;
},
// get the python version, it reads BOA_PYTHON_VERSION from env firstly.
exports.getPythonVersion = function getPythonVersion() {
// TODO(Yorkie): fetch the default python version from conda or other sources.
return BOA_PYTHON_VERSION || '3.7m';
};
/**
* Get the conda directory absolute path.
*/
getCondaPath() {
if (!fs.existsSync(CONDA_INSTALL_DIR)) {
throw new TypeError(`${CONDA_INSTALL_DIR} not found, please reinstall "@pipcook/boa".`);
}
const condaPath = fs.readFileSync(CONDA_INSTALL_DIR, 'utf8');
if (!condaPath || !fs.existsSync(condaPath)) {
this.run('rm', '-rf', CONDA_INSTALL_DIR);
throw new TypeError(`invalid CONDA_INSTALL_DIR file, please reinstall "@pipcook/boa".`);
}
return condaPath;
},
// get the path of the python headers.
exports.getPythonHeaderPath = function getPythonHeaderPath() {
return `${this.getCondaPath()}/include/python${this.getPythonVersion()}`;
};
/**
* Return the complete conda URL to be downloaded the specific version.
*/
getCondaDownloaderName() {
let downloaderName = (BOA_CONDA_VERSION + '');
// matches for platforms: linux/macos
if (this.PLATFORM === 'linux') {
downloaderName += '-Linux';
} else if (this.PLATFORM === 'darwin') {
downloaderName += '-MacOSX';
} else {
throw new TypeError(`no support for platform ${PLATFORM}`);
}
// matches for archs: x64/x86/ppc64/?
if (this.ARCH === 'x64') {
downloaderName += '-x86_64';
} else if (this.ARCH === 'ppc64') {
downloaderName += '-ppc64le';
} else {
if (this.PLATFORM !== 'darwin') {
downloaderName += '-x86';
}
}
return `${downloaderName}.sh`;
},
// prints the conda path.
exports.printCondaPath = () => console.log(this.getCondaPath());
/**
* Get the absolute path of the python library, this is used to compile with.
*/
getPythonLibraryAbsPath() {
return path.join(this.getCondaPath(), 'lib');
},
// initializes the conda and returns the path of conda.
exports.initAndGetCondaPath = () => {
let condaPath;
if (BOA_CONDA_PREFIX === '@cwd' || !BOA_CONDA_PREFIX) {
condaPath = path.join(process.cwd(), '.miniconda');
} else if (BOA_CONDA_PREFIX === '@package') {
condaPath = path.join(__dirname, '../.miniconda');
} else {
condaPath = path.join(BOA_CONDA_PREFIX, '.miniconda');
}
fs.writeFileSync(CONDA_INSTALL_DIR, condaPath, 'utf8');
return condaPath;
};
/**
* Get the runpath/rpath of the python library, this is used to load dynamically.
*/
getPythonLibraryRunPath() {
if (BOA_CONDA_PREFIX === '@packages') {
const prefix = PLATFORM === 'darwin' ? '@loader_path' : '$$ORIGIN';
return `${prefix}/../../${CONDA_INSTALL_NAME}/lib`;
} else {
return this.getPythonLibraryAbsPath();
}
},
// executes a python script from nodejs.
exports.py = (...args) => {
const { run, getCondaPath } = exports;
const CONDA_LOCAL_PATH = getCondaPath();
const Python = path.join(CONDA_LOCAL_PATH, 'bin/python');
const cmds = [Python].concat(args);
return run(...cmds);
};
/**
* Returns if the python should be installed on the current prefix. To install the Python always,
* set the `BOA_FORCE_INSTALL=1` to return false forcily.
* @param {string} prefix
*/
shouldPythonInstalledOn(prefix) {
if (BOA_FORCE_INSTALL) {
return false;
}
return fs.existsSync(path.join(prefix, 'bin/python'));
},
// executes a pip command from nodejs.
exports.pip = (...args) => {
const { py, getCondaPath } = exports;
const CONDA_LOCAL_PATH = getCondaPath();
const PIP = path.join(CONDA_LOCAL_PATH, 'bin/pip');
const cmds = [PIP].concat(args);
if (BOA_CONDA_INDEX) {
cmds.push(`-i ${BOA_CONDA_INDEX}`);
}
return py(...cmds);
/**
* Get the Python version to be used by Boa.
*/
getPythonVersion() {
// TODO(Yorkie): fetch the default python version from conda or other sources.
return BOA_PYTHON_VERSION;
},
/**
* Get the path of Python headers.
*/
getPythonHeaderPath() {
return `${this.getCondaPath()}/include/python${this.getPythonVersion()}`;
},
/**
* Install the Python packages by the BOA_PACKAGE_* variables.
*/
installPythonPackages() {
const packagesToInstall = [];
if (BOA_PACKAGE_BASE) {
packagesToInstall.push('numpy');
packagesToInstall.push('scikit-learn');
}
if (BOA_PACKAGE_CV) {
packagesToInstall.push('opencv-python');
}
for (let pkg of packagesToInstall) {
this.pip('install', pkg, '--default-timeout=1000');
}
},
/**
* Execute a shell command.
* @param {...any} args
*/
run(...args) {
const cmd = args.join(' ');
console.info(`sh "${cmd}"`);
return execSync.call(null, cmd, { stdio: 'inherit' });
},
/**
* Execute a python command.
* @param {...any} args
*/
py(...args) {
const python = path.join(this.getCondaPath(), 'bin/python');
const cmds = [ python ].concat(args);
return this.run(...cmds);
},
/**
* Execute a pip command.
* @param {...any} args
*/
pip(...args) {
const pip = path.join(this.getCondaPath(), 'bin/pip');
const cmds = [ pip ].concat(args);
if (BOA_CONDA_INDEX) {
cmds.push(`-i ${BOA_CONDA_INDEX}`);
}
cmds.push('--timeout=5');
return this.py(...cmds);
},
};
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"lib": [ "es6" ],
"target": "es6",
"noImplicitAny": true,

@@ -11,3 +10,3 @@ "noImplicitThis": true,

"strictFunctionTypes": true,
"types": [],
"types": [ "node" ],
"noEmit": true,

@@ -14,0 +13,0 @@ "forceConsistentCasingInFileNames": true,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc