buddy

node MVC discord bot
Log | Files | Refs | README

WebSocket.js (1368B)


      1 'use strict';
      2 
      3 const { browser } = require('./util/Constants');
      4 
      5 let erlpack;
      6 
      7 try {
      8   erlpack = require('erlpack');
      9   if (!erlpack.pack) erlpack = null;
     10 } catch {} // eslint-disable-line no-empty
     11 
     12 let TextDecoder;
     13 
     14 if (browser) {
     15   TextDecoder = window.TextDecoder; // eslint-disable-line no-undef
     16   exports.WebSocket = window.WebSocket; // eslint-disable-line no-undef
     17 } else {
     18   TextDecoder = require('util').TextDecoder;
     19   exports.WebSocket = require('ws');
     20 }
     21 
     22 const ab = new TextDecoder();
     23 
     24 exports.encoding = erlpack ? 'etf' : 'json';
     25 
     26 exports.pack = erlpack ? erlpack.pack : JSON.stringify;
     27 
     28 exports.unpack = (data, type) => {
     29   if (exports.encoding === 'json' || type === 'json') {
     30     if (typeof data !== 'string') {
     31       data = ab.decode(data);
     32     }
     33     return JSON.parse(data);
     34   }
     35   if (!Buffer.isBuffer(data)) data = Buffer.from(new Uint8Array(data));
     36   return erlpack.unpack(data);
     37 };
     38 
     39 exports.create = (gateway, query = {}, ...args) => {
     40   const [g, q] = gateway.split('?');
     41   query.encoding = exports.encoding;
     42   query = new URLSearchParams(query);
     43   if (q) new URLSearchParams(q).forEach((v, k) => query.set(k, v));
     44   const ws = new exports.WebSocket(`${g}?${query}`, ...args);
     45   if (browser) ws.binaryType = 'arraybuffer';
     46   return ws;
     47 };
     48 
     49 for (const state of ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']) exports[state] = exports.WebSocket[state];