"use strict";var m=Object.defineProperty,P=Object.defineProperties,K=Object.getOwnPropertyDescriptor,V=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertyNames,p=Object.getOwnPropertySymbols;var _=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var T=(s,e,n)=>e in s?m(s,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[e]=n,f=(s,e)=>{for(var n in e||(e={}))_.call(e,n)&&T(s,n,e[n]);if(p)for(var n of p(e))L.call(e,n)&&T(s,n,e[n]);return s},R=(s,e)=>P(s,V(e));var y=(s,e)=>{var n={};for(var r in s)_.call(s,r)&&e.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&p)for(var r of p(s))e.indexOf(r)<0&&L.call(s,r)&&(n[r]=s[r]);return n};var F=(s,e)=>{for(var n in e)m(s,n,{get:e[n],enumerable:!0})},G=(s,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of B(e))!_.call(s,t)&&t!==n&&m(s,t,{get:()=>e[t],enumerable:!(r=K(e,t))||r.enumerable});return s};var $=s=>G(m({},"__esModule",{value:!0}),s);var g=(s,e,n)=>T(s,typeof e!="symbol"?e+"":e,n);var q=(s,e,n)=>new Promise((r,t)=>{var d=o=>{try{c(n.next(o))}catch(h){t(h)}},E=o=>{try{c(n.throw(o))}catch(h){t(h)}},c=o=>o.done?r(o.value):Promise.resolve(o.value).then(d,E);c((n=n.apply(s,e)).next())});var Y={};F(Y,{EditorBroadcastChannelNature:()=>b,default:()=>j});module.exports=$(Y);var N=require("zalgo-promise");function I(s,e){let n;function r(){n=setTimeout(()=>{s(),r()},e)}return r(),{cancel(){clearTimeout(n)}}}function k(s){let e=crypto.randomUUID().split("-")[0];return s?`${s}-${e}`:e}var l="advanced-broadcast-message";var C=class{constructor(e){this.config=e;g(this,"prefix",l);this.log=this.log.bind(this),this.info=this.info.bind(this),this.debug=this.debug.bind(this),this.error=this.error.bind(this)}log(...e){console.log(this.prefix,...e)}info(...e){console.info(this.prefix,...e)}debug(...e){this.config.get("developmentConfig.debug")&&console.debug(this.prefix,"DEBUG:",...e,this.getDebugOptions())}error(...e){this.config.get("developmentConfig.suppressErrors")||console.error(this.prefix,...e)}getDebugOptions(){return{}}};function a(s){return l+": "+s}var i={common:{channelIdRequired:"The channelId is required",channelIsClosed:"The broadcast channel is closed"},sendEvent:{receiverReturnedError:"The receiver returned an error",eventCancelled:"The event was cancelled",noAckReceived:"The ACK was not received"},receiveEvent:{noRequestListenerFound(s){return`No request listener found for event "${s}"`},codeReturnedError:"The code returned an error",noResponseListenerFound(s){return`No response listener found for hash "${s}"`},noAckListenerFound(s){return`No ack listener found for hash "${s}"`},unknownNature(s){return`The nature "${s}" is unknown`}},registerEvent:{eventAlreadyRegistered(s){return`The event "${s}" is already registered`}},unregisterEvent:{eventDoesNotExist(s){return`The event "${s}" does not exist`}}},w={common:{},sendEvent:{receiverReturnedError:"RECEIVER_RETURNED_ERROR",eventCancelled:"EVENT_CANCELLED",noAckReceived:"NO_ACK_RECEIVED"},receiveEvent:{noRequestListenerFound:"NO_REQUEST_LISTENER_FOUND",codeReturnedError:"CODE_RETURNED_ERROR",noResponseListenerFound:"NO_RESPONSE_LISTENER_FOUND",noAckListenerFound:"NO_ACK_LISTENER_FOUND",unknownNature:"UNKNOWN_NATURE"},registerEvent:{eventAlreadyRegistered:"EVENT_ALREADY_REGISTERED"},unregisterEvent:{eventDoesNotExist:"EVENT_DOES_NOT_EXIST"}};function x(){return{channelId:"",developmentConfig:{debug:!1,suppressErrors:!1},channelConfig:{}}}var M=require("lodash-es");var v=class{constructor(e,n={}){g(this,"config");this.config=Q(f({channelId:e},n))}set(e,n){(0,M.set)(this.config,e,n)}get(e){return(0,M.get)(this.config,e)}getAll(){return this.config}reset(){this.config=x()}};function Q(s){if(s.channelId==="")throw new Error(a(i.common.channelIdRequired));let e=x();e.channelId=s.channelId;let d=s,{debug:n,suppressErrors:r}=d,t=y(d,["debug","suppressErrors"]);return e.developmentConfig.debug=n!=null?n:e.developmentConfig.debug,e.developmentConfig.suppressErrors=r!=null?r:e.developmentConfig.suppressErrors,e.channelConfig=t,e}var b=(r=>(r.ACK="ACK",r.RESPONSE="RESPONSE",r.REQUEST="REQUEST",r))(b||{});var U=require("broadcast-channel");var A=class{constructor(e,n){this.logger=e;g(this,"config");g(this,"broadcastChannel");this.sendResponse=this.sendResponse.bind(this),this.sendRequest=this.sendRequest.bind(this),this.sendAck=this.sendAck.bind(this),this.getMessage=this.getMessage.bind(this),this.config=n,this.broadcastChannel=new U.BroadcastChannel(this.config.get("channelId"),this.config.get("channelConfig"))}sendRequest(e){let n=R(f({},e),{nature:"REQUEST"});this.logger.debug("Sending REQUEST",n);let r=this.getMessage(n);this.broadcastChannel.postMessage(r)}sendResponse(e){let n=R(f({},e),{nature:"RESPONSE"});this.logger.debug("Sending RESPONSE",n);let r=this.getMessage(n);this.broadcastChannel.postMessage(r)}sendAck(e){let n=R(f({},e),{payload:void 0,error:void 0,nature:"ACK"});this.logger.debug("Sending ACK",n);let r=this.getMessage(n);this.broadcastChannel.postMessage(r)}getMessage(e){let{nature:n,hash:r,payload:t,type:d,error:E}=e;return{eventManager:l,metadata:{hash:r,nature:n},channel:this.config.get("channelId"),error:E,payload:t,type:d}}onMessage(e){if(this.broadcastChannel.isClosed)throw new Error(i.common.channelIsClosed);this.broadcastChannel.onmessage=e}get isClosed(){return this.broadcastChannel.isClosed}close(){this.broadcastChannel.close()}};var S=class{constructor(e,n={}){g(this,"requestMessageHandlers",new Map);g(this,"responseMessageHandlers",new Map);g(this,"broadcastMessenger");g(this,"logger");g(this,"config");if(!e)throw new Error(a(i.common.channelIdRequired));this.config=new v(e,n),this.logger=new C(this.config),this.broadcastMessenger=new A(this.logger,this.config),this.handleIncomingMessage=this.handleIncomingMessage.bind(this),this.send=this.send.bind(this),this.on=this.on.bind(this),this.unregisterEvent=this.unregisterEvent.bind(this),this.broadcastMessenger.onMessage(this.handleIncomingMessage)}handleIncomingMessage(e){return q(this,null,function*(){let{type:n,channel:r,payload:t,eventManager:d,metadata:E,error:c}=e;if(d!==l||r!==this.config.get("channelId"))return;let{hash:o,nature:h}=E;switch(h){case"REQUEST":{if(this.logger.debug("REQUEST received",e),this.broadcastMessenger.isClosed&&this.logger.error(a(i.common.channelIsClosed)),this.broadcastMessenger.sendAck({type:n,hash:o}),!this.requestMessageHandlers.has(n)){this.logger.debug(a(i.receiveEvent.noRequestListenerFound(n))),this.broadcastMessenger.sendResponse({type:n,hash:o,payload:void 0,error:{code:w.receiveEvent.noRequestListenerFound,message:a(i.receiveEvent.noRequestListenerFound(n))}});return}let{handler:u}=this.requestMessageHandlers.get(n),H={data:t};return N.ZalgoPromise.all([N.ZalgoPromise.try(()=>u(H)).then(O=>{this.broadcastMessenger.sendResponse({type:n,hash:o,payload:O,error:void 0})}).catch(O=>{this.logger.error(a(i.receiveEvent.codeReturnedError),O)})])}case"RESPONSE":{if(this.logger.debug("RESPONSE received",e),!this.responseMessageHandlers.has(o)){this.logger.error(a(i.receiveEvent.noResponseListenerFound(o)));return}let u=this.responseMessageHandlers.get(o);c?u.promise.reject(c):u.promise.resolve(t);break}case"ACK":{if(this.logger.debug("ACK received",e),!this.responseMessageHandlers.has(o)){this.logger.error(a(i.receiveEvent.noAckListenerFound(o)));return}let u=this.responseMessageHandlers.get(o);u.hasReceivedAck=!0;break}default:this.logger.error(a(i.receiveEvent.unknownNature(h)),e)}})}send(e,n){return q(this,null,function*(){let r=new N.ZalgoPromise,t=k(e),d={type:e,promise:r,hasCancelled:!1,hasReceivedAck:!1};this.responseMessageHandlers.set(t,d);let c=1e3,o=I(()=>{if(this.broadcastMessenger.isClosed)return r.reject(new Error(a(i.common.channelIsClosed)));if(c=Math.max(c-500,0),!d.hasReceivedAck&&c<=0)return r.reject(a(i.sendEvent.noAckReceived))},500);return r.finally(()=>{this.responseMessageHandlers.delete(t),o.cancel()}).catch(h=>{this.logger.debug(a(i.sendEvent.receiverReturnedError),h)}),this.broadcastMessenger.sendRequest({type:e,hash:t,error:void 0,payload:n}),r})}on(e,n){this.requestMessageHandlers.has(e)&&this.logger.error(a(i.registerEvent.eventAlreadyRegistered(e)));let r={handler:n};return this.requestMessageHandlers.set(e,r),{unregister:()=>{this.unregisterEvent(e)}}}unregisterEvent(e){this.requestMessageHandlers.has(e)?(this.logger.debug("Unregistering event",e),this.requestMessageHandlers.delete(e)):this.logger.error(a(i.unregisterEvent.eventDoesNotExist(e)))}destroy(e){this.requestMessageHandlers.clear(),this.responseMessageHandlers.clear(),e!=null&&e.soft||this.broadcastMessenger.close()}};var j=S;0&&(module.exports={EditorBroadcastChannelNature}); //# sourceMappingURL=index.cjs.map