import*as Common from"../common/common.js";import*as SDK from"../sdk/sdk.js";let lastId=1;export class ProtocolService extends Common.ObjectWrapper.ObjectWrapper{async attach(){await SDK.SDKModel.TargetManager.instance().suspendAllTargets();const e=SDK.SDKModel.TargetManager.instance().mainTarget();if(!e)throw new Error("Unable to find main target required for LightHouse");const s=e.model(SDK.ChildTargetManager.ChildTargetManager);if(!s)throw new Error("Unable to find child target manager required for LightHouse");this.rawConnection=await s.createParallelConnection((e=>{"string"===typeof e&&(e=JSON.parse(e)),this.dispatchProtocolMessage(e)}))}getLocales(){return navigator.languages}startLighthouse(e,s,t){return this.sendWithResponse("start",{url:e,categoryIDs:s,flags:t,locales:this.getLocales()})}async detach(){const e=this.lighthouseWorkerPromise,s=this.rawConnection;this.lighthouseWorkerPromise=void 0,this.rawConnection=void 0,e&&(await e).terminate(),s&&await s.disconnect(),await SDK.SDKModel.TargetManager.instance().resumeAllTargets()}registerStatusCallback(e){this.lighthouseMessageUpdateCallback=e}dispatchProtocolMessage(e){const s=e;(s.sessionId||s.method&&s.method.startsWith("Target"))&&this.sendWithoutResponse("dispatchProtocolMessage",{message:JSON.stringify(e)})}initWorker(){return this.lighthouseWorkerPromise=new Promise((e=>{const s=new Worker(new URL("../lighthouse_worker.js",import.meta.url),{type:"module"});s.addEventListener("message",(t=>{if("workerReady"===t.data)return void e(s);const a=JSON.parse(t.data);"statusUpdate"===a.method?this.lighthouseMessageUpdateCallback&&a.params&&"message"in a.params&&this.lighthouseMessageUpdateCallback(a.params.message):"sendProtocolMessage"===a.method&&a.params&&"message"in a.params&&this.sendProtocolMessage(a.params.message)}))})),this.lighthouseWorkerPromise}async ensureWorkerExists(){let e;return e=this.lighthouseWorkerPromise?await this.lighthouseWorkerPromise:await this.initWorker(),e}sendProtocolMessage(e){this.rawConnection&&this.rawConnection.sendRawMessage(e)}async sendWithoutResponse(e,s={}){const t=await this.ensureWorkerExists(),a=lastId++;t.postMessage(JSON.stringify({id:a,method:e,params:{...s,id:a}}))}async sendWithResponse(e,s={}){const t=await this.ensureWorkerExists(),a=lastId++,r=new Promise((e=>{const s=r=>{const o=JSON.parse(r.data);o.id===a&&(t.removeEventListener("message",s),e(o.result))};t.addEventListener("message",s)}));return t.postMessage(JSON.stringify({id:a,method:e,params:{...s,id:a}})),r}}