import EventEmitter from 'events';

const cable = {
  __proto__: EventEmitter.prototype,

  init(websocket) {
    if (this._websocket) {
      this._websocket.terminate();
    }
    this._websocket = websocket;
    this.emit('ready');
  },

  get websocket() {
    return new Promise((resolve, reject) => {
      if (this._websocket) {
        resolve(this._websocket);
      } else {
        this.on('ready', () => resolve(this._websocket));
      }
    });
  }
};

const cp = async (msg, comment, opts) => (await cable.websocket).
  send(JSON.stringify({msg, comment, opts}));

export {
  cable,
  cp
};

@@ -83,16 +83,691 @@
 otype,%0A%0A
+  // Call as early as possible on new client connecting%0A  /* e.g. in a pre-routing http get middleware%0A    httpRouter.get('/', (ctx, next) =%3E %7B%0A      peek42.cable.init0();%0A%0A      next();%0A    %7D);%0A  */%0A  init0() %7B%0A    this.init(null);%0A  %7D,%0A%0A  // Between init0 and init calls, any cp call will%0A  // wait for the websocket promise to resolve.%0A  // (If init0 is not called, there will be a dead zone during%0A  // which cp calls will use the previous (probably stale)%0A  // peek42 websocket)%0A%0A  // Call as soon as peek42 websocket is available%0A  /* e.g. in the peek42 websocket get middleware%0A    wsRouter.get('/peek42', ctx =%3E %7B%0A      peek42.cable.init(ctx.websocket);%0A    %7D);%0A  */%0A
   init(w
@@ -842,24 +842,92 @@
 te();%0A    %7D%0A
+%0A    if (!websocket) %7B%0A      this._websocket = null;%0A    %7D else %7B%0A  
     this._we
@@ -947,16 +947,19 @@
 socket;%0A
+%0A  
     this
@@ -974,16 +974,22 @@
 eady');%0A
+    %7D%0A
   %7D,%0A%0A  

Tweak peek42 websocket node init code