diff --git a/packages/engine/package.json b/packages/engine/package.json index 50768a335..f0fce903c 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -11,6 +11,9 @@ "url": "https://github.com/didi/LogicFlow", "directory": "packages/engine" }, + "browser": { + "vm": "./es/expression/browserVm.js" + }, "license": "Apache-2.0", "scripts": { "dev": "cross-env NODE_ENV=development webpack-dev-server --client-log-level warning --config scripts/webpack.config.dev.js", diff --git a/packages/engine/src/expression/browserVm.ts b/packages/engine/src/expression/browserVm.ts index 12d609b51..1559b7b7d 100644 --- a/packages/engine/src/expression/browserVm.ts +++ b/packages/engine/src/expression/browserVm.ts @@ -5,30 +5,35 @@ import { getWarningMsg, } from '../constant/LogCode'; -const runInBrowserContext = async (code: string, globalData: any = {}) => { +const createContext = (globalData) => { const iframe = document.createElement('iframe'); iframe.style.display = 'none'; if (!document || !document.body) { console.error(getErrorMsg(ErrorCode.NO_DOCUMENT_BODY)); } - let res = null; + const iframeWindow = iframe.contentWindow as any; + iframeWindow.parent = null; + Object.keys(globalData).forEach((key) => { + iframeWindow[key] = globalData[key]; + }); + return iframeWindow; +}; +const runInContext = (code, context) => { try { - document.body.appendChild(iframe); - const iframeWindow = iframe.contentWindow as any; - iframeWindow.parent = null; - const iframeEval = iframeWindow.eval; - Object.keys(globalData).forEach((key) => { - iframeWindow[key] = globalData[key]; - }); - iframeEval.call(iframeWindow, code); - res = iframeWindow; + const iframeEval = context.eval; + iframeEval.call(context, code); } catch (e) { - console.warn(getWarningMsg(WarningCode.EXPRESSION_EXEC_ERROR), { code, globalData, e }); + console.warn(getWarningMsg(WarningCode.EXPRESSION_EXEC_ERROR), { code, context, e }); } - document.body.removeChild(iframe); - return res; + return context; +}; +const runInBrowserContext = async (code: string, globalData: any = {}) => { + const context = createContext(globalData); + runInContext(code, context); + return context; }; - export { runInBrowserContext, + createContext, + runInContext, }; diff --git a/packages/engine/src/expression/nodeVm.ts b/packages/engine/src/expression/nodeVm.ts index 7d46a1e36..7d5b2e328 100644 --- a/packages/engine/src/expression/nodeVm.ts +++ b/packages/engine/src/expression/nodeVm.ts @@ -1,6 +1,7 @@ /* eslint-disable global-require */ +const vm = require('vm'); + const runInNewContext = async (code: string, globalData: any = {}) => { - const vm = require('vm'); const context = vm.createContext(globalData); vm.runInContext(code, context); return context;