JavaScriptREPL.js 2.4 KB

123456789101112
  1. export default class JavaScriptREPL{static wrapObjectLiteral(code){if(!(/^\s*\{/.test(code)&&/\}\s*$/.test(code))){return code;}
  2. const parse=(async()=>0).constructor;try{parse('return '+code+';');const wrappedCode='('+code+')';parse(wrappedCode);return wrappedCode;}catch(e){return code;}}
  3. static async preprocessExpression(text){text=JavaScriptREPL.wrapObjectLiteral(text);let preprocessed=false;if(text.indexOf('await')!==-1){const preprocessedText=await Formatter.formatterWorkerPool().preprocessTopLevelAwaitExpressions(text);preprocessed=!!preprocessedText;text=preprocessedText||text;}
  4. return{text,preprocessed};}
  5. static async evaluateAndBuildPreview(text,throwOnSideEffect,timeout,allowErrors,objectGroup){const executionContext=UI.context.flavor(SDK.ExecutionContext);const isTextLong=text.length>ObjectUI.JavaScriptREPL._MaxLengthForEvaluation;if(!text||!executionContext||(throwOnSideEffect&&isTextLong)){return{preview:createDocumentFragment(),result:null};}
  6. const wrappedResult=await JavaScriptREPL.preprocessExpression(text);const options={expression:wrappedResult.text,generatePreview:true,includeCommandLineAPI:true,throwOnSideEffect:throwOnSideEffect,timeout:timeout,objectGroup:objectGroup,disableBreaks:true};const result=await executionContext.evaluate(options,false,wrappedResult.preprocessed);const preview=JavaScriptREPL._buildEvaluationPreview(result,allowErrors);return{preview,result};}
  7. static _buildEvaluationPreview(result,allowErrors){const fragment=createDocumentFragment();if(result.error){return fragment;}
  8. if(result.exceptionDetails&&result.exceptionDetails.exception&&result.exceptionDetails.exception.description){const exception=result.exceptionDetails.exception.description;if(exception.startsWith('TypeError: ')||allowErrors){fragment.createChild('span').textContent=result.exceptionDetails.text+' '+exception;}
  9. return fragment;}
  10. const formatter=new ObjectUI.RemoteObjectPreviewFormatter();const{preview,type,subtype,description}=result.object;if(preview&&type==='object'&&subtype!=='node'){formatter.appendObjectPreview(fragment,preview,false);}else{const nonObjectPreview=formatter.renderPropertyPreview(type,subtype,description.trimEndWithMaxLength(400));fragment.appendChild(nonObjectPreview);}
  11. return fragment;}}
  12. export const _MaxLengthForEvaluation=2000;self.ObjectUI=self.ObjectUI||{};ObjectUI=ObjectUI||{};ObjectUI.JavaScriptREPL=JavaScriptREPL;ObjectUI.JavaScriptREPL._MaxLengthForEvaluation=_MaxLengthForEvaluation;