import*as Platform from"../platform/platform.js";import*as SDK from"../sdk/sdk.js";import*as UI from"../ui/ui.js";import{RemoteObjectPreviewFormatter}from"./RemoteObjectPreviewFormatter.js";export class JavaScriptREPL{static wrapObjectLiteral(e){if(!/^\s*\{/.test(e)||!/\}\s*$/.test(e))return e;const t=(async()=>0).constructor;try{t("return "+e+";");const r="("+e+")";return t(r),r}catch(r){return e}}static preprocessExpression(e){return JavaScriptREPL.wrapObjectLiteral(e)}static async evaluateAndBuildPreview(e,t,r,i,o){const n=window.ObjectUI.JavaScriptREPL,a=UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext),s="undefined"!==typeof n._MaxLengthForEvaluation?n._MaxLengthForEvaluation:MaxLengthForEvaluation,c=e.length>s;if(!e||!a||t&&c)return{preview:document.createDocumentFragment(),result:null};const p={expression:JavaScriptREPL.preprocessExpression(e),generatePreview:!0,includeCommandLineAPI:!0,throwOnSideEffect:t,timeout:r,objectGroup:o,disableBreaks:!0,replMode:!0,silent:void 0,returnByValue:void 0,allowUnsafeEvalBlockedByCSP:void 0},l=await a.evaluate(p,!1,!1);return{preview:JavaScriptREPL._buildEvaluationPreview(l,i),result:l}}static _buildEvaluationPreview(e,t){const r=document.createDocumentFragment();if("error"in e)return r;if(e.exceptionDetails&&e.exceptionDetails.exception&&e.exceptionDetails.exception.description){const i=e.exceptionDetails.exception.description;return(i.startsWith("TypeError: ")||t)&&(r.createChild("span").textContent=e.exceptionDetails.text+" "+i),r}const i=new RemoteObjectPreviewFormatter,{preview:o,type:n,subtype:a,className:s,description:c}=e.object;if(o&&"object"===n&&"node"!==a&&"trustedtype"!==a)i.appendObjectPreview(r,o,!1);else{const e=i.renderPropertyPreview(n,a,s,Platform.StringUtilities.trimEndWithMaxLength(c||"",400));r.appendChild(e)}return r}}export const MaxLengthForEvaluation=2e3;