class e extends Event{constructor(){super("queueempty")}}class r extends Event{constructor(){super("newframe")}}let t;class n extends EventTarget{constructor(){super(...arguments),this.observe=!1,this.recordStorageLimit=100,this.observeOnlyNamed=!0,this.logInternal=[],this.pendingWorkFrames=[],this.resolvers=new WeakMap,this.labels=new WeakMap,this.scheduledWorkId=0}static instance({forceNew:e=!1}={}){return t&&!e||(t=new n),t}done(){return 0===this.pendingWorkFrames.length?Promise.resolve():new Promise((e=>this.addEventListener("queueempty",(()=>e()),{once:!0})))}async read(e,r){if("string"==typeof e){if(!r)throw new Error("Read called with label but no callback");return this.enqueueHandler(r,"read",e)}return this.enqueueHandler(e,"read","Unnamed read")}async write(e,r){if("string"==typeof e){if(!r)throw new Error("Write called with label but no callback");return this.enqueueHandler(r,"write",e)}return this.enqueueHandler(e,"write","Unnamed write")}takeRecords(){const e=[...this.logInternal];return this.logInternal.length=0,e}async scroll(e,r){if("string"==typeof e){if(!r)throw new Error("Scroll called with label but no callback");return this.enqueueHandler(r,"read",e)}return this.enqueueHandler(e,"read","Unnamed scroll")}enqueueHandler(e,r,t=""){this.labels.set(e,`${"read"===r?"[Read]":"[Write]"}: ${t}`),0===this.pendingWorkFrames.length&&this.pendingWorkFrames.push({readers:[],writers:[]});const n=this.pendingWorkFrames[0];if(!n)throw new Error("No frame available");switch(r){case"read":n.readers.push(e);break;case"write":n.writers.push(e);break;default:throw new Error("Unknown action: "+r)}const s=new Promise((r=>{this.resolvers.set(e,r)}));return this.scheduleWork(),s}handleWork(e){const r=e.call(void 0),t=this.resolvers.get(e);if(!t)throw new Error("Unable to locate resolver");t.call(void 0,r),this.resolvers.delete(e)}scheduleWork(){0!==this.scheduledWorkId||(this.scheduledWorkId=requestAnimationFrame((()=>{if(!(this.pendingWorkFrames.length>0))return this.dispatchEvent(new e),this.logIfEnabled("[Queue empty]"),void(this.scheduledWorkId=0);this.dispatchEvent(new r),this.logIfEnabled("[New frame]");const t=this.pendingWorkFrames.shift();if(t){for(const e of t.readers)this.logIfEnabled(this.labels.get(e)),this.handleWork(e);for(const e of t.writers)this.logIfEnabled(this.labels.get(e)),this.handleWork(e);this.scheduledWorkId=0,this.scheduleWork()}})))}logIfEnabled(e){if(!this.observe||!e)return;if(!(e.endsWith("Unnamed read")||e.endsWith("Unnamed write")||e.endsWith("Unnamed scroll"))||!this.observeOnlyNamed)for(this.logInternal.push({time:performance.now(),value:e});this.logInternal.length>this.recordStorageLimit;)this.logInternal.shift()}}var s=Object.freeze({__proto__:null,RenderCoordinatorQueueEmptyEvent:e,RenderCoordinatorNewFrameEvent:r,RenderCoordinator:n});export{s as RenderCoordinator};
