fastify-uws
Version:
A performant HTTP and WebSocket server for Fastify with uWebSockets.
2 lines (1 loc) • 2.76 kB
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("uWebSockets.js"),a=require("eventemitter3");require("streamx");const m=require("./http-socket.cjs"),b=require("./request.cjs"),E=require("./response.cjs"),n=require("./symbols.cjs"),g={compression:k.SHARED_COMPRESSOR,maxPayloadLength:16*1024*1024,idleTimeout:16},p="!",S=Buffer.from(p);class h extends a.EventEmitter{namespace;connection;static allocTopic(e,r){if(r[n.kTopic])return r;const o=Buffer.concat([e,S,Buffer.isBuffer(r)?r:Buffer.from(r)]);return o[n.kTopic]=!0,o}constructor(e,r,o={}){super(),this.namespace=e,this.connection=r,r.websocket=this,this.topics=o,this[n.kEnded]=!1}get uws(){return!0}allocTopic(e){return this.topics[e]?this.topics[e]:h.allocTopic(this.namespace,e)}send(e,r,o){if(!this[n.kEnded])return this.connection.send(e,r,o)}publish(e,r,o,u){if(!this[n.kEnded])return this.connection.publish(this.allocTopic(e),r,o,u)}subscribe(e){if(!this[n.kEnded])return this.connection.subscribe(this.allocTopic(e))}unsubscribe(e){if(!this[n.kEnded])return this.connection.unsubscribe(this.allocTopic(e))}isSubscribed(e){return this[n.kEnded]?!1:this.connection.isSubscribed(this.allocTopic(e))}getTopics(){return this[n.kEnded]?[]:this.connection.getTopics().map(e=>e.slice(e.indexOf(p)+1))}close(){if(!this[n.kEnded])return this[n.kEnded]=!0,this.connection.close()}end(e,r){if(!this[n.kEnded])return this[n.kEnded]=!0,this.connection.end(e,r)}cork(e){if(!this[n.kEnded])return this.connection.cork(e)}getBufferedAmount(){return this[n.kEnded]?0:this.connection.getBufferedAmount()}ping(e){if(!this[n.kEnded])return this.connection.ping(e)}}class T extends a.EventEmitter{constructor(e={}){super(),this.options={...e,...g},this.connections=new Set}addServer(e){const{options:r}=this,o=e[n.kApp],u=e[n.kHandler];o.ws("/*",{upgrade:async(t,i,s)=>{const c=i.getMethod().toUpperCase(),d=new m.HTTPSocket(e,t,c==="GET"||c==="HEAD"),f=new b.Request(i,d,c),l=new E.Response(d);f[n.kWs]=s,e.emit("upgrade",f,d),u(f,l)},open:t=>{this.connections.add(t),t.handler(t),this.emit("open",t)},close:(t,i,s)=>{this.connections.delete(t),t.websocket[n.kEnded]=!0,t.req.socket.destroy();const c=s instanceof ArrayBuffer?Buffer.from(s):s;t.websocket.emit("close",i,c),this.emit("close",t,i,c)},drain:t=>{t.websocket.emit("drain"),this.emit("drain",t)},message:(t,i,s)=>{const c=i instanceof ArrayBuffer?Buffer.from(i):i;t.websocket.emit("message",c,s),this.emit("message",t,c,s)},ping:(t,i)=>{const s=i instanceof ArrayBuffer?Buffer.from(i):i;t.websocket.emit("ping",s),this.emit("ping",t,s)},pong:(t,i)=>{const s=i instanceof ArrayBuffer?Buffer.from(i):i;t.websocket.emit("pong",s),this.emit("pong",t,s)},...r})}}exports.WebSocket=h;exports.WebSocketServer=T;