@yuebai008/cli
Version:
Command line interface for rapid qg-minigame development
1 lines • 13.4 kB
JavaScript
import*as Common from"../common/common.js";import*as Host from"../host/host.js";import*as i18n from"../i18n/i18n.js";import*as Platform from"../platform/platform.js";import{FrontendMessageSource,FrontendMessageType}from"./ConsoleModelTypes.js";export{FrontendMessageSource,FrontendMessageType}from"./ConsoleModelTypes.js";import{CPUProfilerModel,Events as CPUProfilerModelEvents}from"./CPUProfilerModel.js";import{Events as DebuggerModelEvents,COND_BREAKPOINT_SOURCE_URL,LOGPOINT_SOURCE_URL}from"./DebuggerModel.js";import{LogModel}from"./LogModel.js";import{RemoteObject}from"./RemoteObject.js";import{Events as ResourceTreeModelEvents,ResourceTreeModel}from"./ResourceTreeModel.js";import{Events as RuntimeModelEvents,RuntimeModel}from"./RuntimeModel.js";import{Capability,Type}from"./Target.js";import{TargetManager}from"./TargetManager.js";import{SDKModel}from"./SDKModel.js";const UIStrings={navigatedToS:"Navigated to {PH1}",bfcacheNavigation:"Navigation to {PH1} was restored from back/forward cache (see https://web.dev/bfcache/)",profileSStarted:"Profile ''{PH1}'' started.",profileSFinished:"Profile ''{PH1}'' finished.",failedToSaveToTempVariable:"Failed to save to temp variable."},str_=i18n.i18n.registerUIStrings("core/sdk/ConsoleModel.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class ConsoleModel extends SDKModel{#e;#t;#s;#n;#r;#o;#i;#a;constructor(e){super(e),this.#e=[],this.#t=new Platform.MapUtilities.Multimap,this.#s=new Map,this.#n=0,this.#r=0,this.#o=0,this.#i=0,this.#a=new WeakMap;const t=e.model(ResourceTreeModel);if(!t||t.cachedResourcesLoaded())return void this.initTarget(e);const s=t.addEventListener(ResourceTreeModelEvents.CachedResourcesLoaded,(()=>{Common.EventTarget.removeEventListeners([s]),this.initTarget(e)}))}initTarget(e){const t=[],s=e.model(CPUProfilerModel);s&&(t.push(s.addEventListener(CPUProfilerModelEvents.ConsoleProfileStarted,this.consoleProfileStarted.bind(this,s))),t.push(s.addEventListener(CPUProfilerModelEvents.ConsoleProfileFinished,this.consoleProfileFinished.bind(this,s))));const n=e.model(ResourceTreeModel);n&&e.parentTarget()?.type()!==Type.Frame&&t.push(n.addEventListener(ResourceTreeModelEvents.PrimaryPageChanged,this.primaryPageChanged,this));const r=e.model(RuntimeModel);r&&(t.push(r.addEventListener(RuntimeModelEvents.ExceptionThrown,this.exceptionThrown.bind(this,r))),t.push(r.addEventListener(RuntimeModelEvents.ExceptionRevoked,this.exceptionRevoked.bind(this,r))),t.push(r.addEventListener(RuntimeModelEvents.ConsoleAPICalled,this.consoleAPICalled.bind(this,r))),e.parentTarget()?.type()!==Type.Frame&&t.push(r.debuggerModel().addEventListener(DebuggerModelEvents.GlobalObjectCleared,this.clearIfNecessary,this)),t.push(r.addEventListener(RuntimeModelEvents.QueryObjectRequested,this.queryObjectRequested.bind(this,r)))),this.#a.set(e,t)}targetRemoved(e){const t=e.model(RuntimeModel);t&&this.#s.delete(t),Common.EventTarget.removeEventListeners(this.#a.get(e)||[])}async evaluateCommandInConsole(e,t,s,n){const r=await e.evaluate({expression:s,objectGroup:"console",includeCommandLineAPI:n,silent:!1,returnByValue:!1,generatePreview:!0,replMode:!0,allowUnsafeEvalBlockedByCSP:!1},Common.Settings.Settings.instance().moduleSetting("consoleUserActivationEval").get(),!1);Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConsoleEvaluated),"error"in r||(await Common.Console.Console.instance().showPromise(),this.dispatchEventToListeners(Events.CommandEvaluated,{result:r.object,commandMessage:t,exceptionDetails:r.exceptionDetails}))}addCommandMessage(e,t){const s=new ConsoleMessage(e.runtimeModel,"javascript",null,t,{type:FrontendMessageType.Command});return s.setExecutionContextId(e.id),this.addMessage(s),s}addMessage(e){e.setPageLoadSequenceNumber(this.#i),e.source===FrontendMessageSource.ConsoleAPI&&"clear"===e.type&&this.clearIfNecessary(),this.#e.push(e),this.#t.set(e.timestamp,e);const t=e.runtimeModel(),s=e.getExceptionId();if(s&&t){let n=this.#s.get(t);n||(n=new Map,this.#s.set(t,n)),n.set(s,e)}this.incrementErrorWarningCount(e),this.dispatchEventToListeners(Events.MessageAdded,e)}exceptionThrown(e,t){const s=t.data,n=extractExceptionMetaData(s.details.exceptionMetaData),r=ConsoleMessage.fromException(e,s.details,void 0,s.timestamp,void 0,n);r.setExceptionId(s.details.exceptionId),this.addMessage(r)}exceptionRevoked(e,t){const s=t.data,n=this.#s.get(e),r=n?n.get(s):null;r&&(this.#r--,r.level="verbose",this.dispatchEventToListeners(Events.MessageUpdated,r))}consoleAPICalled(e,t){const s=t.data;let n="info";"debug"===s.type?n="verbose":"error"===s.type||"assert"===s.type?n="error":"warning"===s.type?n="warning":"info"!==s.type&&"log"!==s.type||(n="info");let r="";s.args.length&&s.args[0].unserializableValue?r=s.args[0].unserializableValue:!s.args.length||"object"==typeof s.args[0].value&&null!==s.args[0].value?s.args.length&&s.args[0].description&&(r=s.args[0].description):r=String(s.args[0].value);const o=s.stackTrace&&s.stackTrace.callFrames.length?s.stackTrace.callFrames[0]:null,i={type:s.type,url:o?.url,line:o?.lineNumber,column:o?.columnNumber,parameters:s.args,stackTrace:s.stackTrace,timestamp:s.timestamp,executionContextId:s.executionContextId,context:s.context},a=new ConsoleMessage(e,FrontendMessageSource.ConsoleAPI,n,r,i);for(const e of this.#t.get(a.timestamp).values())if(a.isEqual(e))return;this.addMessage(a)}queryObjectRequested(e,t){const{objects:s,executionContextId:n}=t.data,r={type:FrontendMessageType.QueryObjectResult,parameters:[s],executionContextId:n},o=new ConsoleMessage(e,FrontendMessageSource.ConsoleAPI,"info","",r);this.addMessage(o)}clearIfNecessary(){Common.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()||this.clear(),++this.#i}primaryPageChanged(e){if(Common.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()){const{frame:t}=e.data;t.backForwardCacheDetails.restoredFromCache?Common.Console.Console.instance().log(i18nString(UIStrings.bfcacheNavigation,{PH1:t.url})):Common.Console.Console.instance().log(i18nString(UIStrings.navigatedToS,{PH1:t.url}))}}consoleProfileStarted(e,t){const{data:s}=t;this.addConsoleProfileMessage(e,"profile",s.scriptLocation,i18nString(UIStrings.profileSStarted,{PH1:s.title}))}consoleProfileFinished(e,t){const{data:s}=t;this.addConsoleProfileMessage(e,"profileEnd",s.scriptLocation,i18nString(UIStrings.profileSFinished,{PH1:s.title}))}addConsoleProfileMessage(e,t,s,n){const r=s.script(),o=[{functionName:"",scriptId:s.scriptId,url:r?r.contentURL():"",lineNumber:s.lineNumber,columnNumber:s.columnNumber||0}];this.addMessage(new ConsoleMessage(e.runtimeModel(),FrontendMessageSource.ConsoleAPI,"info",n,{type:t,stackTrace:{callFrames:o}}))}incrementErrorWarningCount(e){if("violation"!==e.source)switch(e.level){case"warning":this.#n++;break;case"error":this.#r++}else this.#o++}messages(){return this.#e}static allMessagesUnordered(){const e=[];for(const t of TargetManager.instance().targets()){const s=t.model(ConsoleModel)?.messages()||[];e.push(...s)}return e}static requestClearMessages(){for(const e of TargetManager.instance().models(LogModel))e.requestClear();for(const e of TargetManager.instance().models(RuntimeModel))e.discardConsoleEntries();for(const e of TargetManager.instance().targets())e.model(ConsoleModel)?.clear()}clear(){this.#e=[],this.#t.clear(),this.#s.clear(),this.#r=0,this.#n=0,this.#o=0,this.dispatchEventToListeners(Events.ConsoleCleared)}errors(){return this.#r}static allErrors(){let e=0;for(const t of TargetManager.instance().targets())e+=t.model(ConsoleModel)?.errors()||0;return e}warnings(){return this.#n}static allWarnings(){let e=0;for(const t of TargetManager.instance().targets())e+=t.model(ConsoleModel)?.warnings()||0;return e}violations(){return this.#o}static allViolations(){let e=0;for(const t of TargetManager.instance().targets())e+=t.model(ConsoleModel)?.violations()||0;return e}async saveToTempVariable(e,t){if(!t||!e)return void i(null);const s=e,n=await s.globalObject("",!1);if("error"in n||Boolean(n.exceptionDetails)||!n.object)return void i("object"in n&&n.object||null);const r=n.object,o=await r.callFunction((function(e){const t="temp";let s=1;for(;t+s in this;)++s;const n=t+s;return this[n]=e,n}),[RemoteObject.toCallArgument(t)]);if(r.release(),o.wasThrown||!o.object||"string"!==o.object.type)i(o.object||null);else{const e=o.object.value,t=this.addCommandMessage(s,e);this.evaluateCommandInConsole(s,t,e,!1)}function i(e){let t=i18nString(UIStrings.failedToSaveToTempVariable);e&&(t=t+" "+e.description),Common.Console.Console.instance().error(t)}o.object&&o.object.release()}}export var Events;function extractExceptionMetaData(e){if(e)return{requestId:e.requestId||void 0,issueId:e.issueId||void 0}}function areAffectedResourcesEquivalent(e,t){return e?.requestId===t?.requestId}function areStackTracesEquivalent(e,t){if(!e!=!t)return!1;if(!e||!t)return!0;const s=e.callFrames,n=t.callFrames;if(s.length!==n.length)return!1;for(let e=0,t=s.length;e<t;++e)if(s[e].scriptId!==n[e].scriptId||s[e].functionName!==n[e].functionName||s[e].lineNumber!==n[e].lineNumber||s[e].columnNumber!==n[e].columnNumber)return!1;return areStackTracesEquivalent(e.parent,t.parent)}!function(e){e.ConsoleCleared="ConsoleCleared",e.MessageAdded="MessageAdded",e.MessageUpdated="MessageUpdated",e.CommandEvaluated="CommandEvaluated"}(Events||(Events={}));export class ConsoleMessage{#l;source;level;messageText;type;url;line;column;parameters;stackTrace;timestamp;#c;scriptId;workerId;context;#d=null;#i=void 0;#u=void 0;#m;category;stackFrameWithBreakpoint=null;#g=null;constructor(e,t,s,n,r){if(this.#l=e,this.source=t,this.level=s,this.messageText=n,this.type=r?.type||"log",this.url=r?.url,this.line=r?.line||0,this.column=r?.column||0,this.parameters=r?.parameters,this.stackTrace=r?.stackTrace,this.timestamp=r?.timestamp||Date.now(),this.#c=r?.executionContextId||0,this.scriptId=r?.scriptId,this.workerId=r?.workerId,this.#m=r?.affectedResources,this.category=r?.category,!this.#c&&this.#l&&(this.scriptId?this.#c=this.#l.executionContextIdForScriptId(this.scriptId):this.stackTrace&&(this.#c=this.#l.executionContextForStackTrace(this.stackTrace))),r?.context){const e=r?.context.match(/[^#]*/);this.context=e?.[0]}if(this.stackTrace){const{callFrame:e,type:t}=ConsoleMessage.#p(this.stackTrace);this.stackFrameWithBreakpoint=e,this.#g=t}}getAffectedResources(){return this.#m}setPageLoadSequenceNumber(e){this.#i=e}static fromException(e,t,s,n,r,o){const i={type:s,url:r||t.url,line:t.lineNumber,column:t.columnNumber,parameters:t.exception?[RemoteObject.fromLocalObject(t.text),t.exception]:void 0,stackTrace:t.stackTrace,timestamp:n,executionContextId:t.executionContextId,scriptId:t.scriptId,affectedResources:o};return new ConsoleMessage(e,"javascript","error",RuntimeModel.simpleTextFromException(t),i)}runtimeModel(){return this.#l}target(){return this.#l?this.#l.target():null}setOriginatingMessage(e){this.#d=e,this.#c=e.#c}originatingMessage(){return this.#d}setExecutionContextId(e){this.#c=e}getExecutionContextId(){return this.#c}getExceptionId(){return this.#u}setExceptionId(e){this.#u=e}isGroupMessage(){return"startGroup"===this.type||"startGroupCollapsed"===this.type||"endGroup"===this.type}isGroupStartMessage(){return"startGroup"===this.type||"startGroupCollapsed"===this.type}isErrorOrWarning(){return"warning"===this.level||"error"===this.level}isGroupable(){const e="error"===this.level&&("javascript"===this.source||"network"===this.source);return this.source!==FrontendMessageSource.ConsoleAPI&&this.type!==FrontendMessageType.Command&&this.type!==FrontendMessageType.Result&&this.type!==FrontendMessageType.System&&!e}groupCategoryKey(){return[this.source,this.level,this.type,this.#i].join(":")}isEqual(e){if(!e)return!1;if(this.parameters){if(!e.parameters||this.parameters.length!==e.parameters.length)return!1;for(let t=0;t<e.parameters.length;++t){const s=e.parameters[t],n=this.parameters[t];if("string"==typeof s||"string"==typeof n)return!1;if("object"===s.type&&"error"!==s.subtype)return!1;if(n.type!==s.type||n.value!==s.value||n.description!==s.description)return!1}}return this.runtimeModel()===e.runtimeModel()&&this.source===e.source&&this.type===e.type&&this.level===e.level&&this.line===e.line&&this.url===e.url&&this.scriptId===e.scriptId&&this.messageText===e.messageText&&this.#c===e.#c&&areAffectedResourcesEquivalent(this.#m,e.#m)&&areStackTracesEquivalent(this.stackTrace,e.stackTrace)}get originatesFromLogpoint(){return"LOGPOINT"===this.#g}get originatesFromConditionalBreakpoint(){return"CONDITIONAL_BREAKPOINT"===this.#g}static#p({callFrames:e}){const t=[COND_BREAKPOINT_SOURCE_URL,LOGPOINT_SOURCE_URL],s=e.findLastIndex((({url:e})=>t.includes(e)));if(-1===s||s===e.length-1)return{callFrame:null,type:null};const n=e[s].url===LOGPOINT_SOURCE_URL?"LOGPOINT":"CONDITIONAL_BREAKPOINT";return{callFrame:e[s+1],type:n}}}SDKModel.register(ConsoleModel,{capabilities:Capability.JS,autostart:!0});export const MessageSourceDisplayName=new Map([["xml","xml"],["javascript","javascript"],["network","network"],[FrontendMessageSource.ConsoleAPI,"console-api"],["storage","storage"],["appcache","appcache"],["rendering","rendering"],[FrontendMessageSource.CSS,"css"],["security","security"],["deprecation","deprecation"],["worker","worker"],["violation","violation"],["intervention","intervention"],["recommendation","recommendation"],["other","other"]]);