2019-11-28 03:56:44 +00:00
|
|
|
import { JSExecutorGlobal, JSExecutor } from "./JSExecutionManagerSingleton";
|
|
|
|
|
declare let Realm: any;
|
|
|
|
|
|
|
|
|
|
export default class RealmExecutor implements JSExecutor {
|
|
|
|
|
rootRealm: any;
|
2020-01-01 07:53:03 +00:00
|
|
|
createSafeObject: any;
|
2019-11-28 03:56:44 +00:00
|
|
|
extrinsics: any[] = [];
|
|
|
|
|
createSafeFunction: (unsafeFn: Function) => Function;
|
|
|
|
|
|
|
|
|
|
libraries: Record<string, any> = {};
|
|
|
|
|
constructor() {
|
|
|
|
|
this.rootRealm = Realm.makeRootRealm();
|
|
|
|
|
this.createSafeFunction = this.rootRealm.evaluate(`
|
2020-01-17 09:28:26 +00:00
|
|
|
(function createSafeFunction(unsafeFn) {
|
2019-11-28 03:56:44 +00:00
|
|
|
return function safeFn(...args) {
|
|
|
|
|
unsafeFn(...args);
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
`);
|
2020-01-01 07:53:03 +00:00
|
|
|
this.createSafeObject = this.rootRealm.evaluate(`
|
2020-01-17 09:28:26 +00:00
|
|
|
(function creaetSafeObject(unsafeObject) {
|
2019-11-28 03:56:44 +00:00
|
|
|
return JSON.parse(JSON.stringify(unsafeObject));
|
|
|
|
|
})
|
|
|
|
|
`);
|
|
|
|
|
}
|
|
|
|
|
registerLibrary(accessor: string, lib: any) {
|
|
|
|
|
this.rootRealm.global[accessor] = lib;
|
|
|
|
|
}
|
|
|
|
|
unRegisterLibrary(accessor: string) {
|
|
|
|
|
this.rootRealm.global[accessor] = null;
|
|
|
|
|
}
|
2020-01-01 07:53:03 +00:00
|
|
|
private convertToMainScope(result: any) {
|
|
|
|
|
if (typeof result === "object") {
|
|
|
|
|
if (Array.isArray(result)) {
|
|
|
|
|
return Object.assign([], result);
|
|
|
|
|
}
|
|
|
|
|
return Object.assign({}, result);
|
|
|
|
|
}
|
|
|
|
|
return result;
|
|
|
|
|
}
|
2019-11-28 03:56:44 +00:00
|
|
|
execute(sourceText: string, data: JSExecutorGlobal) {
|
2020-01-01 07:53:03 +00:00
|
|
|
const safeData = this.createSafeObject(data);
|
2019-11-28 03:56:44 +00:00
|
|
|
let result;
|
|
|
|
|
try {
|
|
|
|
|
result = this.rootRealm.evaluate(sourceText, safeData);
|
|
|
|
|
} catch (e) {
|
2020-01-17 09:28:26 +00:00
|
|
|
console.error(`Error: "${e.message}" when evaluating {{${sourceText}}}`);
|
2019-11-28 03:56:44 +00:00
|
|
|
}
|
2020-01-01 07:53:03 +00:00
|
|
|
return this.convertToMainScope(result);
|
2019-11-28 03:56:44 +00:00
|
|
|
}
|
|
|
|
|
}
|