Socket
Socket
Sign inDemoInstall

graphql-ws

Package Overview
Dependencies
Maintainers
1
Versions
103
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-ws - npm Package Compare versions

Comparing version 5.5.3 to 5.5.4

10

lib/client.js

@@ -392,12 +392,10 @@ "use strict";

})()
.catch((err) => {
(errored = true), (done = true);
sink.error(err);
}) // rejects on close events and errors
.then(() => {
done = true;
// delivering either an error or a complete terminates the sequence
if (!errored)
sink.complete();
}); // resolves on release or normal closure
}) // resolves on release or normal closure
.catch((err) => {
sink.error(err);
}); // rejects on close events and errors
return () => {

@@ -404,0 +402,0 @@ // dispose only of active subscriptions

51

lib/use/fastify-websocket.js

@@ -23,5 +23,50 @@ "use strict";

const server = (0, server_1.makeServer)(options);
return (connection, request) => {
// we dont have access to the fastify-websocket server instance yet,
// register an error handler on first connection ONCE only
let handlingServerEmittedErrors = false;
return function handler(connection, request) {
const { socket } = connection;
socket.on('error', (err) => socket.close(common_1.CloseCode.InternalServerError, isProd ? 'Internal server error' : err.message));
// handle server emitted errors only if not already handling
if (!handlingServerEmittedErrors) {
handlingServerEmittedErrors = true;
this.websocketServer.once('error', (err) => {
console.error('Internal error emitted on the WebSocket server. ' +
'Please check your implementation.', err);
// catch the first thrown error and re-throw it once all clients have been notified
let firstErr = null;
// report server errors by erroring out all clients with the same error
for (const client of this.websocketServer.clients) {
try {
client.close(common_1.CloseCode.InternalServerError,
// close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
isProd || err.message.length > 123
? 'Internal server error'
: err.message);
}
catch (err) {
firstErr = firstErr !== null && firstErr !== void 0 ? firstErr : err;
}
}
if (firstErr)
throw firstErr;
});
}
// used as listener on two streams, prevent superfluous calls on close
let emittedErrorHandled = false;
function handleEmittedError(err) {
if (emittedErrorHandled)
return;
emittedErrorHandled = true;
console.error('Internal error emitted on a WebSocket socket. ' +
'Please check your implementation.', err);
socket.close(common_1.CloseCode.InternalServerError,
// close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
isProd || err.message.length > 123
? 'Internal server error'
: err.message);
}
// fastify-websocket uses the WebSocket.createWebSocketStream,
// therefore errors get emitted on both the connection and the socket
connection.once('error', handleEmittedError);
socket.once('error', handleEmittedError);
// keep alive through ping-pong messages

@@ -76,3 +121,3 @@ let pongWait = null;

clearInterval(pingInterval);
if (!isProd && code === 4406)
if (!isProd && code === common_1.CloseCode.SubprotocolNotAcceptable)
console.warn(`WebSocket protocol error occured. It was most likely caused due to an ` +

@@ -79,0 +124,0 @@ `unsupported subprotocol "${socket.protocol}" requested by the client. ` +

@@ -23,3 +23,5 @@ "use strict";

const server = (0, server_1.makeServer)(options);
ws.on('error', (err) => {
ws.once('error', (err) => {
console.error('Internal error emitted on the WebSocket server. ' +
'Please check your implementation.', err);
// catch the first thrown error and re-throw it once all clients have been notified

@@ -30,3 +32,7 @@ let firstErr = null;

try {
client.close(common_1.CloseCode.InternalServerError, isProd ? 'Internal server error' : err.message);
client.close(common_1.CloseCode.InternalServerError,
// close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
isProd || err.message.length > 123
? 'Internal server error'
: err.message);
}

@@ -41,2 +47,11 @@ catch (err) {

ws.on('connection', (socket, request) => {
socket.once('error', (err) => {
console.error('Internal error emitted on a WebSocket socket. ' +
'Please check your implementation.', err);
socket.close(common_1.CloseCode.InternalServerError,
// close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
isProd || err.message.length > 123
? 'Internal server error'
: err.message);
});
// keep alive through ping-pong messages

@@ -91,3 +106,3 @@ let pongWait = null;

clearInterval(pingInterval);
if (!isProd && code === 4406)
if (!isProd && code === common_1.CloseCode.SubprotocolNotAcceptable)
console.warn(`WebSocket protocol error occured. It was most likely caused due to an ` +

@@ -94,0 +109,0 @@ `unsupported subprotocol "${socket.protocol}" requested by the client. ` +

{
"name": "graphql-ws",
"version": "5.5.3",
"version": "5.5.4",
"description": "Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client",

@@ -5,0 +5,0 @@ "keywords": [

@@ -58,6 +58,8 @@ <div align="center">

```ts
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
const server = new ws.Server({
const server = new WebSocketServer({
port: 4000,

@@ -788,3 +790,5 @@ path: '/graphql',

import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { makeServer, CloseCode } from 'graphql-ws';

@@ -797,3 +801,3 @@ import { schema } from './my-graphql-schema';

// create websocket server
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -847,3 +851,5 @@ path: '/graphql',

import http from 'http';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { makeServer, CloseCode } from 'graphql-ws';

@@ -888,3 +894,3 @@ import { schema } from './my-graphql-schema';

// create websocket server
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -944,3 +950,5 @@ path: '/graphql',

```ts
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import {

@@ -958,3 +966,3 @@ makeServer,

// create websocket server
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1033,3 +1041,5 @@ path: '/graphql',

```typescript
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import express from 'express';

@@ -1046,3 +1056,3 @@ import { graphqlHTTP } from 'express-graphql';

// create and use the websocket server
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
server,

@@ -1064,3 +1074,5 @@ path: '/graphql',

import { ApolloServer } from 'apollo-server-express';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';

@@ -1080,3 +1092,3 @@ import { schema } from './my-graphql-schema';

// create and use the websocket server
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
server,

@@ -1097,3 +1109,5 @@ path: '/graphql',

import http from 'http';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { execute, subscribe } from 'graphql';

@@ -1106,7 +1120,7 @@ import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from 'graphql-ws';

// graphql-ws
const graphqlWs = new ws.Server({ noServer: true });
const graphqlWs = new WebSocketServer({ noServer: true });
useServer({ schema }, graphqlWs);
// subscriptions-transport-ws
const subTransWs = new ws.Server({ noServer: true });
const subTransWs = new WebSocketServer({ noServer: true });
SubscriptionServer.create(

@@ -1158,7 +1172,9 @@ {

```typescript
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
import { schema } from './my-graphql-schema';
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1198,3 +1214,5 @@ path: '/graphql',

import http from 'http';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import url from 'url';

@@ -1214,4 +1232,4 @@ import { useServer } from 'graphql-ws/lib/use/ws';

*/
const waveWS = new ws.Server({ noServer: true });
const graphqlWS = new ws.Server({ noServer: true });
const waveWS = new WebSocketServer({ noServer: true });
const graphqlWS = new WebSocketServer({ noServer: true });

@@ -1254,7 +1272,9 @@ // delegate upgrade requests to relevant destinations

```typescript
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
import { schema, roots, getDynamicContext } from './my-graphql';
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1282,7 +1302,9 @@ path: '/graphql',

```typescript
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
import { schema, checkIsAdmin, getDebugSchema } from './my-graphql';
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1315,3 +1337,5 @@ path: '/graphql',

```typescript
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';

@@ -1321,3 +1345,3 @@ import { validate } from 'graphql';

const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1343,7 +1367,9 @@ path: '/graphql',

import { parse, validate } from 'graphql';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
import { schema, myValidationRules } from './my-graphql';
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1383,7 +1409,9 @@ path: '/graphql',

import { parse, validate, getOperationAST, GraphQLError } from 'graphql';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';
import { schema } from './my-graphql';
const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1443,3 +1471,5 @@ path: '/graphql',

import { parse, ExecutionArgs } from 'graphql';
import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';

@@ -1460,3 +1490,3 @@ import { schema } from './my-graphql-schema';

const wsServer = new ws.Server({
const wsServer = new WebSocketServer({
port: 4000,

@@ -1530,3 +1560,5 @@ path: '/graphql',

import ws from 'ws'; // yarn add ws
import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { useServer } from 'graphql-ws/lib/use/ws';

@@ -1533,0 +1565,0 @@ import { CloseCode } from 'graphql-ws';

@@ -540,12 +540,10 @@ (function (global, factory) {

})()
.catch((err) => {
(errored = true), (done = true);
sink.error(err);
}) // rejects on close events and errors
.then(() => {
done = true;
// delivering either an error or a complete terminates the sequence
if (!errored)
sink.complete();
}); // resolves on release or normal closure
}) // resolves on release or normal closure
.catch((err) => {
sink.error(err);
}); // rejects on close events and errors
return () => {

@@ -552,0 +550,0 @@ // dispose only of active subscriptions

@@ -1,1 +0,1 @@

!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o((e="undefined"!=typeof globalThis?globalThis:e||self).graphqlWs={})}(this,(function(e){"use strict";const o=Object.prototype.hasOwnProperty;function n(e){return"object"==typeof e&&null!==e}function t(e,n){return o.call(e,n)}function r(e,t){return o.call(e,t)&&n(e[t])}function i(e,n){return o.call(e,n)&&"string"==typeof e[n]}const a="graphql-transport-ws";var s,l;function c(o){if(n(o)){if(!i(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:return!t(o,"payload")||void 0===o.payload||n(o.payload);case e.MessageType.Subscribe:return i(o,"id")&&r(o,"payload")&&(!t(o.payload,"operationName")||void 0===o.payload.operationName||null===o.payload.operationName||"string"==typeof o.payload.operationName)&&i(o.payload,"query")&&(!t(o.payload,"variables")||void 0===o.payload.variables||null===o.payload.variables||r(o.payload,"variables"))&&(!t(o.payload,"extensions")||void 0===o.payload.extensions||null===o.payload.extensions||r(o.payload,"extensions"));case e.MessageType.Next:return i(o,"id")&&r(o,"payload");case e.MessageType.Error:return i(o,"id")&&(a=o.payload,Array.isArray(a)&&a.length>0&&a.every((e=>"message"in e)));case e.MessageType.Complete:return i(o,"id");default:return!1}}var a;return!1}function d(e,o){if(c(e))return e;if("string"!=typeof e)throw new Error("Message not parsable");const n=JSON.parse(e,o);if(!c(n))throw new Error("Invalid message");return n}function p(e,o){if(!c(e))throw new Error("Cannot stringify invalid message");return JSON.stringify(e,o)}function u(e){return n(e)&&"code"in e&&"reason"in e}e.CloseCode=void 0,(s=e.CloseCode||(e.CloseCode={}))[s.InternalServerError=4500]="InternalServerError",s[s.InternalClientError=4005]="InternalClientError",s[s.BadRequest=4400]="BadRequest",s[s.BadResponse=4004]="BadResponse",s[s.Unauthorized=4401]="Unauthorized",s[s.Forbidden=4403]="Forbidden",s[s.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",s[s.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",s[s.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",s[s.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",s[s.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests",e.MessageType=void 0,(l=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",l.ConnectionAck="connection_ack",l.Ping="ping",l.Pong="pong",l.Subscribe="subscribe",l.Next="next",l.Error="error",l.Complete="complete",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=a,e.createClient=function(o){const{url:n,connectionParams:t,lazy:r=!0,onNonLazyError:i=console.error,lazyCloseTimeout:s=0,keepAlive:l=0,disablePong:c,connectionAckWaitTimeout:y=0,retryAttempts:g=5,retryWait:f=async function(e){let o=1e3;for(let n=0;n<e;n++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},isFatalConnectionProblem:m=(e=>!u(e)),on:C,webSocketImpl:b,generateID:w=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const o=16*Math.random()|0;return("x"==e?o:3&o|8).toString(16)}))},jsonMessageReplacer:x,jsonMessageReviver:v}=o;let T;if(b){if(!("function"==typeof(M=b)&&"constructor"in M&&"CLOSED"in M&&"CLOSING"in M&&"CONNECTING"in M&&"OPEN"in M))throw new Error("Invalid WebSocket implementation provided");T=b}else"undefined"!=typeof WebSocket?T=WebSocket:"undefined"!=typeof global?T=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(T=window.WebSocket||window.MozWebSocket);var M;if(!T)throw new Error("WebSocket implementation missing");const S=T,h=(()=>{const e=(()=>{const e={};return{on:(o,n)=>(e[o]=n,()=>{delete e[o]}),emit(o){var n;"id"in o&&(null===(n=e[o.id])||void 0===n||n.call(e,o))}}})(),o={connecting:(null==C?void 0:C.connecting)?[C.connecting]:[],opened:(null==C?void 0:C.opened)?[C.opened]:[],connected:(null==C?void 0:C.connected)?[C.connected]:[],ping:(null==C?void 0:C.ping)?[C.ping]:[],pong:(null==C?void 0:C.pong)?[C.pong]:[],message:(null==C?void 0:C.message)?[e.emit,C.message]:[e.emit],closed:(null==C?void 0:C.closed)?[C.closed]:[],error:(null==C?void 0:C.error)?[C.error]:[]};return{onMessage:e.on,on(e,n){const t=o[e];return t.push(n),()=>{t.splice(t.indexOf(n),1)}},emit(e,...n){for(const t of o[e])t(...n)}}})();let E,N=0,P=!1,I=0,A=!1;async function k(){const[o,r]=await(null!=E?E:E=new Promise(((o,r)=>(async()=>{if(P){if(await f(I),!N)return E=void 0,r({code:1e3,reason:"All Subscriptions Gone"});I++}h.emit("connecting");const i=new S("function"==typeof n?await n():n,a);let s,u;function g(){isFinite(l)&&l>0&&(clearTimeout(u),u=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(p({type:e.MessageType.Ping})),h.emit("ping",!1,void 0))}),l))}i.onerror=e=>{h.emit("error",e)},i.onclose=e=>{E=void 0,clearTimeout(s),clearTimeout(u),h.emit("closed",e),r(e)},i.onopen=async()=>{try{h.emit("opened",i);const o="function"==typeof t?await t():t;i.send(p(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},x)),isFinite(y)&&y>0&&(s=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),y)),g()}catch(o){i.close(e.CloseCode.InternalClientError,o instanceof Error?o.message:new Error(o).message)}};let m=!1;i.onmessage=({data:n})=>{try{const t=d(n,v);if(h.emit("message",t),"ping"===t.type||"pong"===t.type)return h.emit(t.type,!0,t.payload),void("pong"===t.type?g():c||(i.send(p(t.payload?{type:e.MessageType.Pong,payload:t.payload}:{type:e.MessageType.Pong})),h.emit("pong",!1,t.payload)));if(m)return;if(t.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${t.type}`);clearTimeout(s),m=!0,h.emit("connected",i,t.payload),P=!1,I=0,o([i,new Promise(((e,o)=>i.addEventListener("close",o)))])}catch(o){i.onmessage=null,i.close(e.CloseCode.BadResponse,o instanceof Error?o.message:new Error(o).message)}}})())));o.readyState===S.CLOSING&&await r;let i=()=>{};const u=new Promise((e=>i=e));return[o,i,Promise.race([u.then((()=>{if(!N){const e=()=>o.close(1e3,"Normal Closure");isFinite(s)&&s>0?setTimeout((()=>{N||o.readyState!==S.OPEN||e()}),s):e()}})),r])]}function O(o){if(u(o)&&(n=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(n)&&n>=1e3&&n<=1999||[e.CloseCode.InternalServerError,e.CloseCode.InternalClientError,e.CloseCode.BadRequest,e.CloseCode.BadResponse,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(A)return!1;if(u(o)&&1e3===o.code)return N>0;if(!g||I>=g)throw o;if(m(o))throw o;return P=!0}return r||(async()=>{for(N++;;)try{const[,,e]=await k();await e}catch(e){try{if(!O(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:h.on,subscribe(o,n){const t=w();let r=!1,i=!1,a=()=>{N--,r=!0};return(async()=>{for(N++;;)try{const[s,l,c]=await k();if(r)return l();const d=h.onMessage(t,(o=>{switch(o.type){case e.MessageType.Next:return void n.next(o.payload);case e.MessageType.Error:return i=!0,r=!0,n.error(o.payload),void a();case e.MessageType.Complete:return r=!0,void a()}}));return s.send(p({id:t,type:e.MessageType.Subscribe,payload:o},x)),a=()=>{r||s.readyState!==S.OPEN||s.send(p({id:t,type:e.MessageType.Complete},x)),N--,r=!0,l()},void await c.finally(d)}catch(e){if(!O(e))return}})().catch((e=>{i=!0,r=!0,n.error(e)})).then((()=>{r=!0,i||n.complete()})),()=>{r||a()}},async dispose(){if(A=!0,E){const[e]=await E;e.close(1e3,"Normal Closure")}}}},e.isMessage=c,e.parseMessage=d,e.stringifyMessage=p,Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o((e="undefined"!=typeof globalThis?globalThis:e||self).graphqlWs={})}(this,(function(e){"use strict";const o=Object.prototype.hasOwnProperty;function n(e){return"object"==typeof e&&null!==e}function t(e,n){return o.call(e,n)}function r(e,t){return o.call(e,t)&&n(e[t])}function i(e,n){return o.call(e,n)&&"string"==typeof e[n]}const a="graphql-transport-ws";var s,l;function c(o){if(n(o)){if(!i(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:return!t(o,"payload")||void 0===o.payload||n(o.payload);case e.MessageType.Subscribe:return i(o,"id")&&r(o,"payload")&&(!t(o.payload,"operationName")||void 0===o.payload.operationName||null===o.payload.operationName||"string"==typeof o.payload.operationName)&&i(o.payload,"query")&&(!t(o.payload,"variables")||void 0===o.payload.variables||null===o.payload.variables||r(o.payload,"variables"))&&(!t(o.payload,"extensions")||void 0===o.payload.extensions||null===o.payload.extensions||r(o.payload,"extensions"));case e.MessageType.Next:return i(o,"id")&&r(o,"payload");case e.MessageType.Error:return i(o,"id")&&(a=o.payload,Array.isArray(a)&&a.length>0&&a.every((e=>"message"in e)));case e.MessageType.Complete:return i(o,"id");default:return!1}}var a;return!1}function d(e,o){if(c(e))return e;if("string"!=typeof e)throw new Error("Message not parsable");const n=JSON.parse(e,o);if(!c(n))throw new Error("Invalid message");return n}function p(e,o){if(!c(e))throw new Error("Cannot stringify invalid message");return JSON.stringify(e,o)}function u(e){return n(e)&&"code"in e&&"reason"in e}e.CloseCode=void 0,(s=e.CloseCode||(e.CloseCode={}))[s.InternalServerError=4500]="InternalServerError",s[s.InternalClientError=4005]="InternalClientError",s[s.BadRequest=4400]="BadRequest",s[s.BadResponse=4004]="BadResponse",s[s.Unauthorized=4401]="Unauthorized",s[s.Forbidden=4403]="Forbidden",s[s.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",s[s.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",s[s.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",s[s.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",s[s.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests",e.MessageType=void 0,(l=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",l.ConnectionAck="connection_ack",l.Ping="ping",l.Pong="pong",l.Subscribe="subscribe",l.Next="next",l.Error="error",l.Complete="complete",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=a,e.createClient=function(o){const{url:n,connectionParams:t,lazy:r=!0,onNonLazyError:i=console.error,lazyCloseTimeout:s=0,keepAlive:l=0,disablePong:c,connectionAckWaitTimeout:y=0,retryAttempts:g=5,retryWait:f=async function(e){let o=1e3;for(let n=0;n<e;n++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},isFatalConnectionProblem:m=(e=>!u(e)),on:C,webSocketImpl:b,generateID:w=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const o=16*Math.random()|0;return("x"==e?o:3&o|8).toString(16)}))},jsonMessageReplacer:x,jsonMessageReviver:v}=o;let T;if(b){if(!("function"==typeof(M=b)&&"constructor"in M&&"CLOSED"in M&&"CLOSING"in M&&"CONNECTING"in M&&"OPEN"in M))throw new Error("Invalid WebSocket implementation provided");T=b}else"undefined"!=typeof WebSocket?T=WebSocket:"undefined"!=typeof global?T=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(T=window.WebSocket||window.MozWebSocket);var M;if(!T)throw new Error("WebSocket implementation missing");const S=T,h=(()=>{const e=(()=>{const e={};return{on:(o,n)=>(e[o]=n,()=>{delete e[o]}),emit(o){var n;"id"in o&&(null===(n=e[o.id])||void 0===n||n.call(e,o))}}})(),o={connecting:(null==C?void 0:C.connecting)?[C.connecting]:[],opened:(null==C?void 0:C.opened)?[C.opened]:[],connected:(null==C?void 0:C.connected)?[C.connected]:[],ping:(null==C?void 0:C.ping)?[C.ping]:[],pong:(null==C?void 0:C.pong)?[C.pong]:[],message:(null==C?void 0:C.message)?[e.emit,C.message]:[e.emit],closed:(null==C?void 0:C.closed)?[C.closed]:[],error:(null==C?void 0:C.error)?[C.error]:[]};return{onMessage:e.on,on(e,n){const t=o[e];return t.push(n),()=>{t.splice(t.indexOf(n),1)}},emit(e,...n){for(const t of o[e])t(...n)}}})();let E,N=0,P=!1,I=0,A=!1;async function k(){const[o,r]=await(null!=E?E:E=new Promise(((o,r)=>(async()=>{if(P){if(await f(I),!N)return E=void 0,r({code:1e3,reason:"All Subscriptions Gone"});I++}h.emit("connecting");const i=new S("function"==typeof n?await n():n,a);let s,u;function g(){isFinite(l)&&l>0&&(clearTimeout(u),u=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(p({type:e.MessageType.Ping})),h.emit("ping",!1,void 0))}),l))}i.onerror=e=>{h.emit("error",e)},i.onclose=e=>{E=void 0,clearTimeout(s),clearTimeout(u),h.emit("closed",e),r(e)},i.onopen=async()=>{try{h.emit("opened",i);const o="function"==typeof t?await t():t;i.send(p(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},x)),isFinite(y)&&y>0&&(s=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),y)),g()}catch(o){i.close(e.CloseCode.InternalClientError,o instanceof Error?o.message:new Error(o).message)}};let m=!1;i.onmessage=({data:n})=>{try{const t=d(n,v);if(h.emit("message",t),"ping"===t.type||"pong"===t.type)return h.emit(t.type,!0,t.payload),void("pong"===t.type?g():c||(i.send(p(t.payload?{type:e.MessageType.Pong,payload:t.payload}:{type:e.MessageType.Pong})),h.emit("pong",!1,t.payload)));if(m)return;if(t.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${t.type}`);clearTimeout(s),m=!0,h.emit("connected",i,t.payload),P=!1,I=0,o([i,new Promise(((e,o)=>i.addEventListener("close",o)))])}catch(o){i.onmessage=null,i.close(e.CloseCode.BadResponse,o instanceof Error?o.message:new Error(o).message)}}})())));o.readyState===S.CLOSING&&await r;let i=()=>{};const u=new Promise((e=>i=e));return[o,i,Promise.race([u.then((()=>{if(!N){const e=()=>o.close(1e3,"Normal Closure");isFinite(s)&&s>0?setTimeout((()=>{N||o.readyState!==S.OPEN||e()}),s):e()}})),r])]}function O(o){if(u(o)&&(n=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(n)&&n>=1e3&&n<=1999||[e.CloseCode.InternalServerError,e.CloseCode.InternalClientError,e.CloseCode.BadRequest,e.CloseCode.BadResponse,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(A)return!1;if(u(o)&&1e3===o.code)return N>0;if(!g||I>=g)throw o;if(m(o))throw o;return P=!0}return r||(async()=>{for(N++;;)try{const[,,e]=await k();await e}catch(e){try{if(!O(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:h.on,subscribe(o,n){const t=w();let r=!1,i=!1,a=()=>{N--,r=!0};return(async()=>{for(N++;;)try{const[s,l,c]=await k();if(r)return l();const d=h.onMessage(t,(o=>{switch(o.type){case e.MessageType.Next:return void n.next(o.payload);case e.MessageType.Error:return i=!0,r=!0,n.error(o.payload),void a();case e.MessageType.Complete:return r=!0,void a()}}));return s.send(p({id:t,type:e.MessageType.Subscribe,payload:o},x)),a=()=>{r||s.readyState!==S.OPEN||s.send(p({id:t,type:e.MessageType.Complete},x)),N--,r=!0,l()},void await c.finally(d)}catch(e){if(!O(e))return}})().then((()=>{i||n.complete()})).catch((e=>{n.error(e)})),()=>{r||a()}},async dispose(){if(A=!0,E){const[e]=await E;e.close(1e3,"Normal Closure")}}}},e.isMessage=c,e.parseMessage=d,e.stringifyMessage=p,Object.defineProperty(e,"__esModule",{value:!0})}));

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc