Socket
Socket
Sign inDemoInstall

graphql-ws

Package Overview
Dependencies
0
Maintainers
1
Versions
103
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.4.1 to 5.5.0

14

lib/client.d.ts

@@ -232,2 +232,16 @@ /**

/**
* The amount of time for which the client will wait
* for `ConnectionAck` message.
*
* Set the value to `Infinity`, `''`, `0`, `null` or `undefined` to skip waiting.
*
* If the wait timeout has passed and the server
* has not responded with `ConnectionAck` message,
* the client will terminate the socket by
* dispatching a close event `4418: Connection acknowledgement timeout`
*
* @default 0
*/
connectionAckWaitTimeout?: number;
/**
* Disable sending the `PongMessage` automatically.

@@ -234,0 +248,0 @@ *

13

lib/client.js

@@ -29,3 +29,3 @@ "use strict";

function createClient(options) {
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) {
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) {
let retryDelay = 1000; // start with 1s delay

@@ -138,3 +138,3 @@ for (let i = 0; i < retries; i++) {

const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, common_1.GRAPHQL_TRANSPORT_WS_PROTOCOL);
let queuedPing;
let connectionAckTimeout, queuedPing;
function enqueuePing() {

@@ -157,2 +157,3 @@ if (isFinite(keepAlive) && keepAlive > 0) {

connecting = undefined;
clearTimeout(connectionAckTimeout);
clearTimeout(queuedPing);

@@ -177,2 +178,8 @@ emitter.emit('closed', event);

}, replacer));
if (isFinite(connectionAckWaitTimeout) &&
connectionAckWaitTimeout > 0) {
connectionAckTimeout = setTimeout(() => {
socket.close(common_1.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout');
}, connectionAckWaitTimeout);
}
enqueuePing(); // enqueue ping (noop if disabled)

@@ -213,2 +220,3 @@ }

throw new Error(`First message cannot be of type ${message.type}`);
clearTimeout(connectionAckTimeout);
acknowledged = true;

@@ -278,2 +286,3 @@ emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged

// CloseCode.ConnectionInitialisationTimeout, might not time out after retry
// CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry
common_1.CloseCode.SubscriberAlreadyExists,

@@ -280,0 +289,0 @@ common_1.CloseCode.TooManyInitialisationRequests,

@@ -6,3 +6,3 @@ /**

*/
import { GraphQLError, ExecutionResult } from 'graphql';
import { GraphQLError } from 'graphql';
/**

@@ -27,2 +27,3 @@ * The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](/PROTOCOL.md).

ConnectionInitialisationTimeout = 4408,
ConnectionAcknowledgementTimeout = 4504,
/** Subscriber distinction is very important */

@@ -113,6 +114,22 @@ SubscriberAlreadyExists = 4409,

/** @category Common */
export interface ExecutionResult<Data = Record<string, unknown>, Extensions = Record<string, unknown>> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
hasNext?: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface ExecutionPatchResult<Data = unknown, Extensions = Record<string, unknown>> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
path?: ReadonlyArray<string | number>;
label?: string;
hasNext: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface NextMessage {
readonly id: ID;
readonly type: MessageType.Next;
readonly payload: ExecutionResult;
readonly payload: ExecutionResult | ExecutionPatchResult;
}

@@ -119,0 +136,0 @@ /** @category Common */

@@ -30,2 +30,3 @@ "use strict";

CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
/** Subscriber distinction is very important */

@@ -32,0 +33,0 @@ CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";

10

lib/server.d.ts

@@ -6,6 +6,6 @@ /**

*/
import { OperationTypeNode, GraphQLSchema, ExecutionArgs, validate as graphqlValidate, GraphQLError, SubscriptionArgs, ExecutionResult } from 'graphql';
import { ID, SubscribeMessage, NextMessage, ErrorMessage, CompleteMessage, JSONMessageReplacer, JSONMessageReviver, PingMessage, PongMessage } from './common';
import { OperationTypeNode, GraphQLSchema, ExecutionArgs, validate as graphqlValidate, GraphQLError, SubscriptionArgs } from 'graphql';
import { ID, SubscribeMessage, NextMessage, ErrorMessage, CompleteMessage, JSONMessageReplacer, JSONMessageReviver, PingMessage, PongMessage, ExecutionResult, ExecutionPatchResult } from './common';
/** @category Server */
export declare type OperationResult = Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult> | AsyncIterableIterator<ExecutionResult> | ExecutionResult;
export declare type OperationResult = Promise<AsyncGenerator<ExecutionResult | ExecutionPatchResult> | AsyncIterable<ExecutionResult | ExecutionPatchResult> | ExecutionResult> | AsyncGenerator<ExecutionResult | ExecutionPatchResult> | AsyncIterable<ExecutionResult | ExecutionPatchResult> | ExecutionResult;
/**

@@ -255,3 +255,3 @@ * A concrete GraphQL execution context value type.

*/
onNext?: (ctx: Context<E>, message: NextMessage, args: ExecutionArgs, result: ExecutionResult) => Promise<ExecutionResult | void> | ExecutionResult | void;
onNext?: (ctx: Context<E>, message: NextMessage, args: ExecutionArgs, result: ExecutionResult | ExecutionPatchResult) => Promise<ExecutionResult | ExecutionPatchResult | void> | ExecutionResult | ExecutionPatchResult | void;
/**

@@ -388,3 +388,3 @@ * The complete callback is executed after the

*/
readonly subscriptions: Record<ID, AsyncIterator<unknown> | null>;
readonly subscriptions: Record<ID, AsyncGenerator<unknown> | AsyncIterable<unknown> | null>;
/**

@@ -391,0 +391,0 @@ * An extra field where you can store your own context values

@@ -56,3 +56,3 @@ "use strict";

var e_1, _a;
var _b, _c;
var _b;
let message;

@@ -202,4 +202,4 @@ try {

// subscription was completed/canceled before the operation settled
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
operationResult.return(); // iterator must implement the return method
if (utils_1.isAsyncGenerator(operationResult))
operationResult.return(undefined);
}

@@ -237,4 +237,5 @@ else {

case common_1.MessageType.Complete: {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await ((_c = ctx.subscriptions[message.id]) === null || _c === void 0 ? void 0 : _c.return()); // iterator must implement the return method
const subscription = ctx.subscriptions[message.id];
if (utils_1.isAsyncGenerator(subscription))
await subscription.return(undefined);
delete ctx.subscriptions[message.id]; // deleting the subscription means no further activity should take place

@@ -252,4 +253,4 @@ return;

for (const sub of Object.values(ctx.subscriptions)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await (sub === null || sub === void 0 ? void 0 : sub.return()); // iterator must implement the return method
if (utils_1.isAsyncGenerator(sub))
await sub.return(undefined);
}

@@ -256,0 +257,0 @@ if (ctx.acknowledged)

@@ -10,4 +10,6 @@ /**

/** @private */
export declare function isAsyncIterable<T = unknown>(val: unknown): val is AsyncIterableIterator<T>;
export declare function isAsyncIterable<T = unknown>(val: unknown): val is AsyncIterable<T>;
/** @private */
export declare function isAsyncGenerator<T = unknown>(val: unknown): val is AsyncGenerator<T>;
/** @private */
export declare function areGraphQLErrors(obj: unknown): obj is readonly GraphQLError[];

@@ -14,0 +16,0 @@ /** @private */

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasOwnStringProperty = exports.hasOwnArrayProperty = exports.hasOwnObjectProperty = exports.hasOwnProperty = exports.areGraphQLErrors = exports.isAsyncIterable = exports.isObject = void 0;
exports.hasOwnStringProperty = exports.hasOwnArrayProperty = exports.hasOwnObjectProperty = exports.hasOwnProperty = exports.areGraphQLErrors = exports.isAsyncGenerator = exports.isAsyncIterable = exports.isObject = void 0;
// Extremely small optimisation, reduces runtime prototype traversal

@@ -17,2 +17,13 @@ const baseHasOwnProperty = Object.prototype.hasOwnProperty;

/** @private */
function isAsyncGenerator(val) {
return (isObject(val) &&
typeof Object(val)[Symbol.asyncIterator] === 'function' &&
typeof val.return === 'function'
// for lazy ones, we only need the return anyway
// typeof val.throw === 'function' &&
// typeof val.next === 'function'
);
}
exports.isAsyncGenerator = isAsyncGenerator;
/** @private */
function areGraphQLErrors(obj) {

@@ -19,0 +30,0 @@ return (Array.isArray(obj) &&

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

@@ -82,3 +82,3 @@ "keywords": [

"devDependencies": {
"@babel/core": "^7.15.0",
"@babel/core": "^7.15.5",
"@babel/plugin-proposal-class-properties": "^7.14.5",

@@ -88,20 +88,20 @@ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.14.5",

"@babel/plugin-proposal-optional-chaining": "^7.14.5",
"@babel/preset-env": "^7.15.0",
"@babel/preset-env": "^7.15.4",
"@babel/preset-typescript": "^7.15.0",
"@rollup/plugin-typescript": "^8.2.5",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.0",
"@semantic-release/git": "^9.0.1",
"@types/jest": "^26.0.24",
"@types/ws": "^7.4.7",
"@typescript-eslint/eslint-plugin": "^4.29.3",
"@typescript-eslint/parser": "^4.29.3",
"babel-jest": "^27.0.6",
"@typescript-eslint/eslint-plugin": "^4.31.0",
"@typescript-eslint/parser": "^4.31.0",
"babel-jest": "^27.1.1",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"fastify": "^3.20.2",
"fastify-websocket": "^3.2.1",
"eslint-plugin-prettier": "^4.0.0",
"fastify": "^3.21.0",
"fastify-websocket": "^4.0.0",
"glob": "^7.1.7",
"graphql": "^16.0.0-rc.1",
"jest": "^27.0.6",
"graphql": "16.0.0-rc.2.experimental-stream-defer.3",
"jest": "^27.1.1",
"prettier": "^2.3.2",

@@ -111,10 +111,10 @@ "replacestream": "^4.0.3",

"rollup-plugin-terser": "^7.0.2",
"semantic-release": "^17.4.6",
"semantic-release": "^17.4.7",
"tslib": "^2.3.1",
"typedoc": "^0.21.6",
"typedoc": "^0.21.9",
"typedoc-plugin-markdown": "^3.10.4",
"typescript": "^4.3.5",
"typescript": "4.3.5",
"uWebSockets.js": "uNetworking/uWebSockets.js#v19.3.0",
"ws": "^8.2.0"
"ws": "^8.2.1"
}
}

@@ -18,3 +18,3 @@ <div align="center">

```shell
$ yarn add graphql-ws
yarn add graphql-ws
```

@@ -264,2 +264,5 @@

},
async throw(err) {
throw err
}
async return() {

@@ -266,0 +269,0 @@ dispose();

@@ -59,2 +59,3 @@ (function (global, factory) {

CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
/** Subscriber distinction is very important */

@@ -175,3 +176,3 @@ CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";

function createClient(options) {
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) {
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) {
let retryDelay = 1000; // start with 1s delay

@@ -284,3 +285,3 @@ for (let i = 0; i < retries; i++) {

const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, GRAPHQL_TRANSPORT_WS_PROTOCOL);
let queuedPing;
let connectionAckTimeout, queuedPing;
function enqueuePing() {

@@ -303,2 +304,3 @@ if (isFinite(keepAlive) && keepAlive > 0) {

connecting = undefined;
clearTimeout(connectionAckTimeout);
clearTimeout(queuedPing);

@@ -323,2 +325,8 @@ emitter.emit('closed', event);

}, replacer));
if (isFinite(connectionAckWaitTimeout) &&
connectionAckWaitTimeout > 0) {
connectionAckTimeout = setTimeout(() => {
socket.close(exports.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout');
}, connectionAckWaitTimeout);
}
enqueuePing(); // enqueue ping (noop if disabled)

@@ -359,2 +367,3 @@ }

throw new Error(`First message cannot be of type ${message.type}`);
clearTimeout(connectionAckTimeout);
acknowledged = true;

@@ -424,2 +433,3 @@ emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged

// CloseCode.ConnectionInitialisationTimeout, might not time out after retry
// CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry
exports.CloseCode.SubscriberAlreadyExists,

@@ -426,0 +436,0 @@ exports.CloseCode.TooManyInitialisationRequests,

@@ -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 a(e,n){return o.call(e,n)&&"string"==typeof e[n]}const i="graphql-transport-ws";var s,l;function c(o){if(n(o)){if(!a(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:return!t(o,"payload")||void 0===o.payload||n(o.payload);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 a(o,"id")&&r(o,"payload")&&(!t(o.payload,"operationName")||void 0===o.payload.operationName||null===o.payload.operationName||"string"==typeof o.payload.operationName)&&a(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 a(o,"id")&&r(o,"payload");case e.MessageType.Error:return a(o,"id")&&(i=o.payload,Array.isArray(i)&&i.length>0&&i.every((e=>"message"in e)));case e.MessageType.Complete:return a(o,"id");default:return!1}}var i;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 y(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.BadRequest=4400]="BadRequest",s[s.Unauthorized=4401]="Unauthorized",s[s.Forbidden=4403]="Forbidden",s[s.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",s[s.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",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=i,e.createClient=function(o){const{url:n,connectionParams:t,lazy:r=!0,onNonLazyError:a=console.error,lazyCloseTimeout:s=0,keepAlive:l=0,disablePong:c,retryAttempts:u=5,retryWait:g=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:f=(e=>!y(e)),on:m,webSocketImpl:b,generateID:x=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:v,jsonMessageReviver:C}=o;let w;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");w=b}else"undefined"!=typeof WebSocket?w=WebSocket:"undefined"!=typeof global?w=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(w=window.WebSocket||window.MozWebSocket);var M;if(!w)throw new Error("WebSocket implementation missing");const T=w,S=(()=>{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==m?void 0:m.connecting)?[m.connecting]:[],opened:(null==m?void 0:m.opened)?[m.opened]:[],connected:(null==m?void 0:m.connected)?[m.connected]:[],ping:(null==m?void 0:m.ping)?[m.ping]:[],pong:(null==m?void 0:m.pong)?[m.pong]:[],message:(null==m?void 0:m.message)?[e.emit,m.message]:[e.emit],closed:(null==m?void 0:m.closed)?[m.closed]:[],error:(null==m?void 0:m.error)?[m.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 h,E=0,N=!1,P=0,I=!1;async function O(){const[o,r]=await(null!=h?h:h=new Promise(((o,r)=>(async()=>{if(N){if(await g(P),!E)return h=void 0,r({code:1e3,reason:"All Subscriptions Gone"});P++}S.emit("connecting");const a=new T("function"==typeof n?await n():n,i);let s;function y(){isFinite(l)&&l>0&&(clearTimeout(s),s=setTimeout((()=>{a.readyState===T.OPEN&&(a.send(p({type:e.MessageType.Ping})),S.emit("ping",!1,void 0))}),l))}a.onerror=e=>{S.emit("error",e)},a.onclose=e=>{h=void 0,clearTimeout(s),S.emit("closed",e),r(e)},a.onopen=async()=>{try{S.emit("opened",a);const o="function"==typeof t?await t():t;a.send(p(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},v)),y()}catch(o){a.close(e.CloseCode.BadRequest,o instanceof Error?o.message:new Error(o).message)}};let u=!1;a.onmessage=({data:n})=>{try{const t=d(n,C);if(S.emit("message",t),"ping"===t.type||"pong"===t.type)return S.emit(t.type,!0,t.payload),void("pong"===t.type?y():c||(a.send(p(t.payload?{type:e.MessageType.Pong,payload:t.payload}:{type:e.MessageType.Pong})),S.emit("pong",!1,t.payload)));if(u)return;if(t.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${t.type}`);u=!0,S.emit("connected",a,t.payload),N=!1,P=0,o([a,new Promise(((e,o)=>a.addEventListener("close",o)))])}catch(o){a.close(e.CloseCode.BadRequest,o instanceof Error?o.message:new Error(o).message)}}})())));o.readyState===T.CLOSING&&await r;let a=()=>{};const y=new Promise((e=>a=e));return[o,a,Promise.race([y.then((()=>{if(!E){const e=()=>o.close(1e3,"Normal Closure");isFinite(s)&&s>0?setTimeout((()=>{E||o.readyState!==T.OPEN||e()}),s):e()}})),r])]}function A(o){if(y(o)&&(n=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(n)&&n>=1e3&&n<=1999||[e.CloseCode.InternalServerError,e.CloseCode.BadRequest,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(I)return!1;if(y(o)&&1e3===o.code)return E>0;if(!u||P>=u)throw o;if(f(o))throw o;return N=!0}return r||(async()=>{for(E++;;)try{const[,,e]=await O();await e}catch(e){try{if(!A(e))return}catch(e){return null==a?void 0:a(e)}}})(),{on:S.on,subscribe(o,n){const t=x();let r=!1,a=!1,i=()=>{E--,r=!0};return(async()=>{for(E++;;)try{const[s,l,c]=await O();if(r)return l();const d=S.onMessage(t,(o=>{switch(o.type){case e.MessageType.Next:return void n.next(o.payload);case e.MessageType.Error:return a=!0,r=!0,n.error(o.payload),void i();case e.MessageType.Complete:return r=!0,void i()}}));return s.send(p({id:t,type:e.MessageType.Subscribe,payload:o},v)),i=()=>{r||s.readyState!==T.OPEN||s.send(p({id:t,type:e.MessageType.Complete},v)),E--,r=!0,l()},void await c.finally(d)}catch(e){if(!A(e))return}})().catch(n.error).then((()=>{a||n.complete()})),()=>{r||i()}},async dispose(){if(I=!0,h){const[e]=await h;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,c;function l(o){if(n(o)){if(!i(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:return!t(o,"payload")||void 0===o.payload||n(o.payload);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(l(e))return e;if("string"!=typeof e)throw new Error("Message not parsable");const n=JSON.parse(e,o);if(!l(n))throw new Error("Invalid message");return n}function p(e,o){if(!l(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.BadRequest=4400]="BadRequest",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,(c=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",c.ConnectionAck="connection_ack",c.Ping="ping",c.Pong="pong",c.Subscribe="subscribe",c.Next="next",c.Error="error",c.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:c=0,disablePong:l,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,A=0,k=!1;async function I(){const[o,r]=await(null!=E?E:E=new Promise(((o,r)=>(async()=>{if(P){if(await f(A),!N)return E=void 0,r({code:1e3,reason:"All Subscriptions Gone"});A++}h.emit("connecting");const i=new S("function"==typeof n?await n():n,a);let s,u;function g(){isFinite(c)&&c>0&&(clearTimeout(u),u=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(p({type:e.MessageType.Ping})),h.emit("ping",!1,void 0))}),c))}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.BadRequest,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():l||(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,A=0,o([i,new Promise(((e,o)=>i.addEventListener("close",o)))])}catch(o){i.close(e.CloseCode.BadRequest,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.BadRequest,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(k)return!1;if(u(o)&&1e3===o.code)return N>0;if(!g||A>=g)throw o;if(m(o))throw o;return P=!0}return r||(async()=>{for(N++;;)try{const[,,e]=await I();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,c,l]=await I();if(r)return c();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,c()},void await l.finally(d)}catch(e){if(!O(e))return}})().catch(n.error).then((()=>{i||n.complete()})),()=>{r||a()}},async dispose(){if(k=!0,E){const[e]=await E;e.close(1e3,"Normal Closure")}}}},e.isMessage=l,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

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc