Skip to content

Commit

Permalink
fix(engine): support es module umd and commonJs
Browse files Browse the repository at this point in the history
  • Loading branch information
towersxu authored and boyongjiong committed Aug 18, 2023
1 parent f8e51cc commit bb17159
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 16 deletions.
3 changes: 3 additions & 0 deletions packages/engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
35 changes: 20 additions & 15 deletions packages/engine/src/expression/browserVm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
3 changes: 2 additions & 1 deletion packages/engine/src/expression/nodeVm.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down

0 comments on commit bb17159

Please sign in to comment.