class MessageChannel {
  appOrigin;
  channel = null;
  bufferedMessages = [];
  constructor({ appOrigin }) {
    this.appOrigin = appOrigin;
  }
  postMessage(message, transferables) {
    if (this.channel) {
      this.channel.postMessage(message, transferables ?? []);
    } else {
      this.bufferedMessages.push([message, transferables]);
    }
  }
  setup(onMessage) {
    const channel = new window.MessageChannel();
    channel.port1.onmessage = onMessage;
    window.parent.postMessage(channel.port2, this.appOrigin, [channel.port2]);
    this.channel = channel.port1;
  }
  dispatchBuffered() {
    console.assert(this.channel != null, "channel is not setup");
    this.bufferedMessages.forEach(([message, transferables]) => {
      this.channel?.postMessage(message, transferables ?? []);
    });
    this.bufferedMessages = [];
  }
  teardown() {
    if (this.channel) {
      this.channel.onmessage = null;
      this.channel.close();
    }
  }
}
export {
  MessageChannel
};
//# sourceMappingURL=message-channel.js.map