graphql-ws
Advanced tools
Comparing version
@@ -33,3 +33,3 @@ "use strict"; | ||
function createClient(options) { | ||
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) { | ||
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout: lazyCloseTimeoutMs = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) { | ||
let retryDelay = 1000; // start with 1s delay | ||
@@ -143,4 +143,7 @@ for (let i = 0; i < retries; i++) { | ||
} | ||
let connecting, locks = 0, retrying = false, retries = 0, disposed = false; | ||
let connecting, locks = 0, lazyCloseTimeout, retrying = false, retries = 0, disposed = false; | ||
async function connect() { | ||
// clear the lazy close timeout immediatelly so that close gets debounced | ||
// see: https://github.com/enisdenjo/graphql-ws/issues/388 | ||
clearTimeout(lazyCloseTimeout); | ||
const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : (connecting = new Promise((connected, denied) => (async () => { | ||
@@ -277,10 +280,9 @@ if (retrying) { | ||
const complete = () => socket.close(1000, 'Normal Closure'); | ||
if (isFinite(lazyCloseTimeout) && lazyCloseTimeout > 0) { | ||
if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { | ||
// if the keepalive is set, allow for the specified calmdown time and | ||
// then complete. but only if no lock got created in the meantime and | ||
// if the socket is still open | ||
setTimeout(() => { | ||
if (!locks && socket.readyState === WebSocketImpl.OPEN) | ||
// then complete if the socket is still open. | ||
lazyCloseTimeout = setTimeout(() => { | ||
if (socket.readyState === WebSocketImpl.OPEN) | ||
complete(); | ||
}, lazyCloseTimeout); | ||
}, lazyCloseTimeoutMs); | ||
} | ||
@@ -287,0 +289,0 @@ else { |
{ | ||
"name": "graphql-ws", | ||
"version": "5.10.0", | ||
"version": "5.10.1", | ||
"description": "Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client", | ||
@@ -30,3 +30,3 @@ "keywords": [ | ||
}, | ||
"packageManager": "yarn@3.2.1", | ||
"packageManager": "yarn@3.2.2", | ||
"main": "lib/index.js", | ||
@@ -106,14 +106,14 @@ "module": "lib/index.mjs", | ||
"@semantic-release/git": "^10.0.1", | ||
"@types/jest": "^28.1.6", | ||
"@types/jest": "^28.1.7", | ||
"@types/ws": "^8.5.3", | ||
"@typescript-eslint/eslint-plugin": "^5.33.0", | ||
"@typescript-eslint/parser": "^5.33.0", | ||
"@typescript-eslint/eslint-plugin": "^5.33.1", | ||
"@typescript-eslint/parser": "^5.33.1", | ||
"babel-jest": "^28.1.3", | ||
"eslint": "^8.21.0", | ||
"eslint": "^8.22.0", | ||
"eslint-config-prettier": "^8.5.0", | ||
"eslint-plugin-prettier": "^4.2.1", | ||
"fastify": "^4.4.0", | ||
"fastify": "^4.5.2", | ||
"fastify-websocket": "4.2.2", | ||
"glob": "^8.0.3", | ||
"graphql": "^16.5.0", | ||
"graphql": "^16.6.0", | ||
"jest": "^28.1.3", | ||
@@ -124,3 +124,3 @@ "jest-environment-jsdom": "^28.1.3", | ||
"replacestream": "^4.0.3", | ||
"rollup": "^2.77.2", | ||
"rollup": "^2.78.1", | ||
"rollup-plugin-terser": "^7.0.2", | ||
@@ -127,0 +127,0 @@ "semantic-release": "^19.0.3", |
@@ -237,3 +237,3 @@ (function (global, factory) { | ||
function createClient(options) { | ||
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) { | ||
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout: lazyCloseTimeoutMs = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) { | ||
let retryDelay = 1000; // start with 1s delay | ||
@@ -347,4 +347,7 @@ for (let i = 0; i < retries; i++) { | ||
} | ||
let connecting, locks = 0, retrying = false, retries = 0, disposed = false; | ||
let connecting, locks = 0, lazyCloseTimeout, retrying = false, retries = 0, disposed = false; | ||
async function connect() { | ||
// clear the lazy close timeout immediatelly so that close gets debounced | ||
// see: https://github.com/enisdenjo/graphql-ws/issues/388 | ||
clearTimeout(lazyCloseTimeout); | ||
const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : (connecting = new Promise((connected, denied) => (async () => { | ||
@@ -481,10 +484,9 @@ if (retrying) { | ||
const complete = () => socket.close(1000, 'Normal Closure'); | ||
if (isFinite(lazyCloseTimeout) && lazyCloseTimeout > 0) { | ||
if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { | ||
// if the keepalive is set, allow for the specified calmdown time and | ||
// then complete. but only if no lock got created in the meantime and | ||
// if the socket is still open | ||
setTimeout(() => { | ||
if (!locks && socket.readyState === WebSocketImpl.OPEN) | ||
// then complete if the socket is still open. | ||
lazyCloseTimeout = setTimeout(() => { | ||
if (socket.readyState === WebSocketImpl.OPEN) | ||
complete(); | ||
}, lazyCloseTimeout); | ||
}, lazyCloseTimeoutMs); | ||
} | ||
@@ -491,0 +493,0 @@ else { |
@@ -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";function o(e){return null===e?"null":Array.isArray(e)?"array":typeof e}function t(e){return"object"===o(e)}function r(e,o){return e.length<124?e:o}const n="graphql-transport-ws";var s,a;function i(r){if(!t(r))throw new Error(`Message is expected to be an object, but got ${o(r)}`);if(!r.type)throw new Error("Message is missing the 'type' property");if("string"!=typeof r.type)throw new Error(`Message is expects the 'type' property to be a string, but got ${o(r.type)}`);switch(r.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:if("payload"in r&&!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object or missing, but got "${r.payload}"`);break;case e.MessageType.Subscribe:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object, but got ${o(r.payload)}`);if("string"!=typeof r.payload.query)throw new Error(`"${r.type}" message payload expects the 'query' property to be a string, but got ${o(r.payload.query)}`);if(null!=r.payload.variables&&!t(r.payload.variables))throw new Error(`"${r.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${o(r.payload.variables)}`);if(null!=r.payload.operationName&&"string"!==o(r.payload.operationName))throw new Error(`"${r.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${o(r.payload.operationName)}`);if(null!=r.payload.extensions&&!t(r.payload.extensions))throw new Error(`"${r.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${o(r.payload.extensions)}`);break;case e.MessageType.Next:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object, but got ${o(r.payload)}`);break;case e.MessageType.Error:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(n=r.payload,!(Array.isArray(n)&&n.length>0&&n.every((e=>"message"in e))))throw new Error(`"${r.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(r.payload)}`);break;case e.MessageType.Complete:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);break;default:throw new Error(`Invalid message 'type' property "${r.type}"`)}var n;return r}function p(e,o){try{return i(e)}catch(t){if("string"!=typeof e)throw new Error("Only strings are parsable messages");return i(JSON.parse(e,o))}}function l(e,o){return i(e),JSON.stringify(e,o)}function c(e){return t(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,(a=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",a.ConnectionAck="connection_ack",a.Ping="ping",a.Pong="pong",a.Subscribe="subscribe",a.Next="next",a.Error="error",a.Complete="complete",e.DEPRECATED_GRAPHQL_WS_PROTOCOL="graphql-ws",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=n,e.createClient=function(o){const{url:t,connectionParams:s,lazy:a=!0,onNonLazyError:i=console.error,lazyCloseTimeout:d=0,keepAlive:y=0,disablePong:u,connectionAckWaitTimeout:g=0,retryAttempts:m=5,retryWait:f=async function(e){let o=1e3;for(let t=0;t<e;t++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},shouldRetry:b=c,isFatalConnectionProblem:w,on:h,webSocketImpl:C,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:E,jsonMessageReviver:T}=o;let v;if(C){if(!("function"==typeof(M=C)&&"constructor"in M&&"CLOSED"in M&&"CLOSING"in M&&"CONNECTING"in M&&"OPEN"in M))throw new Error("Invalid WebSocket implementation provided");v=C}else"undefined"!=typeof WebSocket?v=WebSocket:"undefined"!=typeof global?v=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(v=window.WebSocket||window.MozWebSocket);var M;if(!v)throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");const S=v,$=(()=>{const e=(()=>{const e={};return{on:(o,t)=>(e[o]=t,()=>{delete e[o]}),emit(o){var t;"id"in o&&(null===(t=e[o.id])||void 0===t||t.call(e,o))}}})(),o={connecting:(null==h?void 0:h.connecting)?[h.connecting]:[],opened:(null==h?void 0:h.opened)?[h.opened]:[],connected:(null==h?void 0:h.connected)?[h.connected]:[],ping:(null==h?void 0:h.ping)?[h.ping]:[],pong:(null==h?void 0:h.pong)?[h.pong]:[],message:(null==h?void 0:h.message)?[e.emit,h.message]:[e.emit],closed:(null==h?void 0:h.closed)?[h.closed]:[],error:(null==h?void 0:h.error)?[h.error]:[]};return{onMessage:e.on,on(e,t){const r=o[e];return r.push(t),()=>{r.splice(r.indexOf(t),1)}},emit(e,...t){for(const r of[...o[e]])r(...t)}}})();function N(e){const o=[$.on("error",(t=>{o.forEach((e=>e())),e(t)})),$.on("closed",(t=>{o.forEach((e=>e())),e(t)}))]}let k,P=0,I=!1,A=0,O=!1;async function R(){const[o,a]=await(null!=k?k:k=new Promise(((o,a)=>(async()=>{if(I){if(await f(A),!P)return k=void 0,a({code:1e3,reason:"All Subscriptions Gone"});A++}$.emit("connecting");const i=new S("function"==typeof t?await t():t,n);let d,m;function b(){isFinite(y)&&y>0&&(clearTimeout(m),m=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(l({type:e.MessageType.Ping})),$.emit("ping",!1,void 0))}),y))}N((e=>{k=void 0,clearTimeout(d),clearTimeout(m),a(e),c(e)&&4499===e.code&&(i.close(4499,"Terminated"),i.onerror=null,i.onclose=null)})),i.onerror=e=>$.emit("error",e),i.onclose=e=>$.emit("closed",e),i.onopen=async()=>{try{$.emit("opened",i);const o="function"==typeof s?await s():s;if(i.readyState!==S.OPEN)return;i.send(l(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},E)),isFinite(g)&&g>0&&(d=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),g)),b()}catch(o){$.emit("error",o),i.close(e.CloseCode.InternalClientError,r(o instanceof Error?o.message:new Error(o).message,"Internal client error"))}};let w=!1;i.onmessage=({data:t})=>{try{const r=p(t,T);if($.emit("message",r),"ping"===r.type||"pong"===r.type)return $.emit(r.type,!0,r.payload),void("pong"===r.type?b():u||(i.send(l(r.payload?{type:e.MessageType.Pong,payload:r.payload}:{type:e.MessageType.Pong})),$.emit("pong",!1,r.payload)));if(w)return;if(r.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${r.type}`);clearTimeout(d),w=!0,$.emit("connected",i,r.payload),I=!1,A=0,o([i,new Promise(((e,o)=>N(o)))])}catch(o){i.onmessage=null,$.emit("error",o),i.close(e.CloseCode.BadResponse,r(o instanceof Error?o.message:new Error(o).message,"Bad response"))}}})())));o.readyState===S.CLOSING&&await a;let i=()=>{};const m=new Promise((e=>i=e));return[o,i,Promise.race([m.then((()=>{if(!P){const e=()=>o.close(1e3,"Normal Closure");isFinite(d)&&d>0?setTimeout((()=>{P||o.readyState!==S.OPEN||e()}),d):e()}})),a])]}function q(o){if(c(o)&&(t=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(t)&&t>=1e3&&t<=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 t;if(O)return!1;if(c(o)&&1e3===o.code)return P>0;if(!m||A>=m)throw o;if(!b(o))throw o;if(null==w?void 0:w(o))throw o;return I=!0}return a||(async()=>{for(P++;;)try{const[,,e]=await R();await e}catch(e){try{if(!q(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:$.on,subscribe(o,t){const r=x();let n=!1,s=!1,a=()=>{P--,n=!0};return(async()=>{for(P++;;)try{const[i,p,c]=await R();if(n)return p();const d=$.onMessage(r,(o=>{switch(o.type){case e.MessageType.Next:return void t.next(o.payload);case e.MessageType.Error:return s=!0,n=!0,t.error(o.payload),void a();case e.MessageType.Complete:return n=!0,void a()}}));return i.send(l({id:r,type:e.MessageType.Subscribe,payload:o},E)),a=()=>{n||i.readyState!==S.OPEN||i.send(l({id:r,type:e.MessageType.Complete},E)),P--,n=!0,p()},void await c.finally(d)}catch(e){if(!q(e))return}})().then((()=>{s||t.complete()})).catch((e=>{t.error(e)})),()=>{n||a()}},async dispose(){if(O=!0,k){const[e]=await k;e.close(1e3,"Normal Closure")}},terminate(){k&&$.emit("closed",{code:4499,reason:"Terminated",wasClean:!1})}}},e.isMessage=function(e){try{return i(e),!0}catch(e){return!1}},e.parseMessage=p,e.stringifyMessage=l,e.validateMessage=i,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";function o(e){return null===e?"null":Array.isArray(e)?"array":typeof e}function t(e){return"object"===o(e)}function r(e,o){return e.length<124?e:o}const n="graphql-transport-ws";var s,a;function i(r){if(!t(r))throw new Error(`Message is expected to be an object, but got ${o(r)}`);if(!r.type)throw new Error("Message is missing the 'type' property");if("string"!=typeof r.type)throw new Error(`Message is expects the 'type' property to be a string, but got ${o(r.type)}`);switch(r.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:if("payload"in r&&!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object or missing, but got "${r.payload}"`);break;case e.MessageType.Subscribe:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object, but got ${o(r.payload)}`);if("string"!=typeof r.payload.query)throw new Error(`"${r.type}" message payload expects the 'query' property to be a string, but got ${o(r.payload.query)}`);if(null!=r.payload.variables&&!t(r.payload.variables))throw new Error(`"${r.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${o(r.payload.variables)}`);if(null!=r.payload.operationName&&"string"!==o(r.payload.operationName))throw new Error(`"${r.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${o(r.payload.operationName)}`);if(null!=r.payload.extensions&&!t(r.payload.extensions))throw new Error(`"${r.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${o(r.payload.extensions)}`);break;case e.MessageType.Next:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(!t(r.payload))throw new Error(`"${r.type}" message expects the 'payload' property to be an object, but got ${o(r.payload)}`);break;case e.MessageType.Error:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);if(n=r.payload,!(Array.isArray(n)&&n.length>0&&n.every((e=>"message"in e))))throw new Error(`"${r.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(r.payload)}`);break;case e.MessageType.Complete:if("string"!=typeof r.id)throw new Error(`"${r.type}" message expects the 'id' property to be a string, but got ${o(r.id)}`);if(!r.id)throw new Error(`"${r.type}" message requires a non-empty 'id' property`);break;default:throw new Error(`Invalid message 'type' property "${r.type}"`)}var n;return r}function p(e,o){try{return i(e)}catch(t){if("string"!=typeof e)throw new Error("Only strings are parsable messages");return i(JSON.parse(e,o))}}function l(e,o){return i(e),JSON.stringify(e,o)}function c(e){return t(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,(a=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",a.ConnectionAck="connection_ack",a.Ping="ping",a.Pong="pong",a.Subscribe="subscribe",a.Next="next",a.Error="error",a.Complete="complete",e.DEPRECATED_GRAPHQL_WS_PROTOCOL="graphql-ws",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=n,e.createClient=function(o){const{url:t,connectionParams:s,lazy:a=!0,onNonLazyError:i=console.error,lazyCloseTimeout:d=0,keepAlive:y=0,disablePong:u,connectionAckWaitTimeout:g=0,retryAttempts:m=5,retryWait:f=async function(e){let o=1e3;for(let t=0;t<e;t++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},shouldRetry:b=c,isFatalConnectionProblem:w,on:h,webSocketImpl:C,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:E,jsonMessageReviver:T}=o;let v;if(C){if(!("function"==typeof(M=C)&&"constructor"in M&&"CLOSED"in M&&"CLOSING"in M&&"CONNECTING"in M&&"OPEN"in M))throw new Error("Invalid WebSocket implementation provided");v=C}else"undefined"!=typeof WebSocket?v=WebSocket:"undefined"!=typeof global?v=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(v=window.WebSocket||window.MozWebSocket);var M;if(!v)throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");const S=v,$=(()=>{const e=(()=>{const e={};return{on:(o,t)=>(e[o]=t,()=>{delete e[o]}),emit(o){var t;"id"in o&&(null===(t=e[o.id])||void 0===t||t.call(e,o))}}})(),o={connecting:(null==h?void 0:h.connecting)?[h.connecting]:[],opened:(null==h?void 0:h.opened)?[h.opened]:[],connected:(null==h?void 0:h.connected)?[h.connected]:[],ping:(null==h?void 0:h.ping)?[h.ping]:[],pong:(null==h?void 0:h.pong)?[h.pong]:[],message:(null==h?void 0:h.message)?[e.emit,h.message]:[e.emit],closed:(null==h?void 0:h.closed)?[h.closed]:[],error:(null==h?void 0:h.error)?[h.error]:[]};return{onMessage:e.on,on(e,t){const r=o[e];return r.push(t),()=>{r.splice(r.indexOf(t),1)}},emit(e,...t){for(const r of[...o[e]])r(...t)}}})();function N(e){const o=[$.on("error",(t=>{o.forEach((e=>e())),e(t)})),$.on("closed",(t=>{o.forEach((e=>e())),e(t)}))]}let k,P,I=0,A=!1,O=0,R=!1;async function q(){clearTimeout(P);const[o,a]=await(null!=k?k:k=new Promise(((o,a)=>(async()=>{if(A){if(await f(O),!I)return k=void 0,a({code:1e3,reason:"All Subscriptions Gone"});O++}$.emit("connecting");const i=new S("function"==typeof t?await t():t,n);let d,m;function b(){isFinite(y)&&y>0&&(clearTimeout(m),m=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(l({type:e.MessageType.Ping})),$.emit("ping",!1,void 0))}),y))}N((e=>{k=void 0,clearTimeout(d),clearTimeout(m),a(e),c(e)&&4499===e.code&&(i.close(4499,"Terminated"),i.onerror=null,i.onclose=null)})),i.onerror=e=>$.emit("error",e),i.onclose=e=>$.emit("closed",e),i.onopen=async()=>{try{$.emit("opened",i);const o="function"==typeof s?await s():s;if(i.readyState!==S.OPEN)return;i.send(l(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},E)),isFinite(g)&&g>0&&(d=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),g)),b()}catch(o){$.emit("error",o),i.close(e.CloseCode.InternalClientError,r(o instanceof Error?o.message:new Error(o).message,"Internal client error"))}};let w=!1;i.onmessage=({data:t})=>{try{const r=p(t,T);if($.emit("message",r),"ping"===r.type||"pong"===r.type)return $.emit(r.type,!0,r.payload),void("pong"===r.type?b():u||(i.send(l(r.payload?{type:e.MessageType.Pong,payload:r.payload}:{type:e.MessageType.Pong})),$.emit("pong",!1,r.payload)));if(w)return;if(r.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${r.type}`);clearTimeout(d),w=!0,$.emit("connected",i,r.payload),A=!1,O=0,o([i,new Promise(((e,o)=>N(o)))])}catch(o){i.onmessage=null,$.emit("error",o),i.close(e.CloseCode.BadResponse,r(o instanceof Error?o.message:new Error(o).message,"Bad response"))}}})())));o.readyState===S.CLOSING&&await a;let i=()=>{};const m=new Promise((e=>i=e));return[o,i,Promise.race([m.then((()=>{if(!I){const e=()=>o.close(1e3,"Normal Closure");isFinite(d)&&d>0?P=setTimeout((()=>{o.readyState===S.OPEN&&e()}),d):e()}})),a])]}function W(o){if(c(o)&&(t=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(t)&&t>=1e3&&t<=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 t;if(R)return!1;if(c(o)&&1e3===o.code)return I>0;if(!m||O>=m)throw o;if(!b(o))throw o;if(null==w?void 0:w(o))throw o;return A=!0}return a||(async()=>{for(I++;;)try{const[,,e]=await q();await e}catch(e){try{if(!W(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:$.on,subscribe(o,t){const r=x();let n=!1,s=!1,a=()=>{I--,n=!0};return(async()=>{for(I++;;)try{const[i,p,c]=await q();if(n)return p();const d=$.onMessage(r,(o=>{switch(o.type){case e.MessageType.Next:return void t.next(o.payload);case e.MessageType.Error:return s=!0,n=!0,t.error(o.payload),void a();case e.MessageType.Complete:return n=!0,void a()}}));return i.send(l({id:r,type:e.MessageType.Subscribe,payload:o},E)),a=()=>{n||i.readyState!==S.OPEN||i.send(l({id:r,type:e.MessageType.Complete},E)),I--,n=!0,p()},void await c.finally(d)}catch(e){if(!W(e))return}})().then((()=>{s||t.complete()})).catch((e=>{t.error(e)})),()=>{n||a()}},async dispose(){if(R=!0,k){const[e]=await k;e.close(1e3,"Normal Closure")}},terminate(){k&&$.emit("closed",{code:4499,reason:"Terminated",wasClean:!1})}}},e.isMessage=function(e){try{return i(e),!0}catch(e){return!1}},e.parseMessage=p,e.stringifyMessage=l,e.validateMessage=i,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
306732
0.17%4788
0.13%