class e{promise;trigger;cancel;label;handler;constructor(e,t){const{promise:r,resolve:n,reject:o}=Promise.withResolvers();this.promise=r.then((()=>this.handler())),this.trigger=n,this.cancel=o,this.label=e,this.handler=t}}class t extends Event{static eventName="renderqueueempty";constructor(){super(t.eventName)}}class r extends Event{static eventName="newframe";constructor(){super(r.eventName)}}let n=null;const o=[];function i(e,t={}){e?n={onlyNamed:t.onlyNamed,storageLimit:t.storageLimit}:(n=null,o.length=0)}const a="Unnamed read",s="Unnamed write",l="Unnamed scroll",c=1500;globalThis.__getRenderCoordinatorPendingFrames=function(){return m()?1:0};let u=[],d=[],w=0;function m(){return u.length+d.length!==0}function f(e){return m()||e?.waitForWork?new Promise((e=>window.addEventListener(t.eventName,(()=>e()),{once:!0}))):(k("[Queue empty]"),Promise.resolve())}async function h(e,t){if("string"==typeof e){if(!t)throw new Error("Read called with label but no callback");return await v("read",e,t)}return await v("read",a,e)}async function g(e,t){if("string"==typeof e){if(!t)throw new Error("Write called with label but no callback");return await v("write",e,t)}return await v("write",s,e)}function p(){const e=[...o];return o.length=0,e}async function b(e,t){if("string"==typeof e){if(!t)throw new Error("Scroll called with label but no callback");return await v("read",e,t)}return await v("read",l,e)}function v(t,r,n){const o=![a,s,l].includes(r);r=`${"read"===t?"[Read]":"[Write]"}: ${r}`;let i=null;switch(t){case"read":i=u;break;case"write":i=d;break;default:throw new Error(`Unknown action: ${t}`)}let c=o?i.find((e=>e.label===r)):void 0;return c?c.handler=n:(c=new e(r,n),i.push(c)),y(),c.promise}function y(){0===w&&(w=requestAnimationFrame((async()=>{if(!m())return window.dispatchEvent(new t),k("[Queue empty]"),void(w=0);window.dispatchEvent(new r),k("[New frame]");const e=u;u=[];const n=d;d=[];for(const t of e)k(t.label),t.trigger();try{await Promise.race([Promise.all(e.map((e=>e.promise))),new Promise(((e,t)=>{window.setTimeout((()=>t(new Error("Readers took over 1500ms. Possible deadlock?"))),c)}))])}catch(t){E(e,t)}for(const e of n)k(e.label),e.trigger();try{await Promise.race([Promise.all(n.map((e=>e.promise))),new Promise(((e,t)=>{window.setTimeout((()=>t(new Error("Writers took over 1500ms. Possible deadlock?"))),c)}))])}catch(e){E(n,e)}w=0,y()})))}function E(e,t){for(const r of e)r.cancel(t)}function P(){const e=new Error;E(u,e),E(d,e)}function k(e){if(null===n)return;if(n.onlyNamed&&(e.endsWith(a)||e.endsWith(s)||e.endsWith(l)))return;o.push({time:performance.now(),value:e});const t=n.storageLimit??100;for(;o.length>t;)o.shift()}export{r as RenderCoordinatorNewFrameEvent,t as RenderCoordinatorQueueEmptyEvent,P as cancelPending,f as done,m as hasPendingWork,h as read,b as scroll,i as setLoggingEnabled,p as takeLoggingRecords,g as write};
