Initial Save

This commit is contained in:
jackbeeby
2025-03-28 12:30:19 +11:00
parent e381994f19
commit d8773925e8
9910 changed files with 982718 additions and 0 deletions

View File

@@ -0,0 +1,112 @@
import { ListenerFn } from 'eventemitter3';
import { ExecutionResult } from 'graphql/execution/execute';
import { DocumentNode } from 'graphql/language/ast';
export interface Observer<T> {
next?: (value: T) => void;
error?: (error: Error) => void;
complete?: () => void;
}
export interface Observable<T> {
subscribe(observer: Observer<T>): {
unsubscribe: () => void;
};
}
export interface OperationOptions {
query?: string | DocumentNode;
variables?: Object;
operationName?: string;
[key: string]: any;
}
export declare type FormatedError = Error & {
originalError?: any;
};
export interface Operation {
options: OperationOptions;
handler: (error: Error[], result?: any) => void;
}
export interface Operations {
[id: string]: Operation;
}
export interface Middleware {
applyMiddleware(options: OperationOptions, next: Function): void;
}
export declare type ConnectionParams = {
[paramName: string]: any;
};
export declare type ConnectionParamsOptions = ConnectionParams | Function | Promise<ConnectionParams>;
export interface ClientOptions {
connectionParams?: ConnectionParamsOptions;
minTimeout?: number;
timeout?: number;
reconnect?: boolean;
reconnectionAttempts?: number;
connectionCallback?: (error: Error[], result?: any) => void;
lazy?: boolean;
inactivityTimeout?: number;
wsOptionArguments?: any[];
}
export declare class SubscriptionClient {
client: any;
operations: Operations;
private url;
private nextOperationId;
private connectionParams;
private minWsTimeout;
private wsTimeout;
private unsentMessagesQueue;
private reconnect;
private reconnecting;
private reconnectionAttempts;
private backoff;
private connectionCallback;
private eventEmitter;
private lazy;
private inactivityTimeout;
private inactivityTimeoutId;
private closedByUser;
private wsImpl;
private wsProtocols;
private wasKeepAliveReceived;
private tryReconnectTimeoutId;
private checkConnectionIntervalId;
private maxConnectTimeoutId;
private middlewares;
private maxConnectTimeGenerator;
private wsOptionArguments;
constructor(url: string, options?: ClientOptions, webSocketImpl?: any, webSocketProtocols?: string | string[]);
get status(): any;
close(isForced?: boolean, closedByUser?: boolean): void;
request(request: OperationOptions): Observable<ExecutionResult>;
on(eventName: string, callback: ListenerFn, context?: any): Function;
onConnected(callback: ListenerFn, context?: any): Function;
onConnecting(callback: ListenerFn, context?: any): Function;
onDisconnected(callback: ListenerFn, context?: any): Function;
onReconnected(callback: ListenerFn, context?: any): Function;
onReconnecting(callback: ListenerFn, context?: any): Function;
onError(callback: ListenerFn, context?: any): Function;
unsubscribeAll(): void;
applyMiddlewares(options: OperationOptions): Promise<OperationOptions>;
use(middlewares: Middleware[]): SubscriptionClient;
private getConnectionParams;
private executeOperation;
private getObserver;
private createMaxConnectTimeGenerator;
private clearCheckConnectionInterval;
private clearMaxConnectTimeout;
private clearTryReconnectTimeout;
private clearInactivityTimeout;
private setInactivityTimeout;
private checkOperationOptions;
private buildMessage;
private formatErrors;
private sendMessage;
private sendMessageRaw;
private generateOperationId;
private tryReconnect;
private flushUnsentMessagesQueue;
private checkConnection;
private checkMaxConnectTimeout;
private connect;
private processReceivedData;
private unsubscribe;
}

560
node_modules/subscriptions-transport-ws/dist/client.js generated vendored Normal file
View File

@@ -0,0 +1,560 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubscriptionClient = void 0;
var _global = typeof global !== 'undefined' ? global : (typeof window !== 'undefined' ? window : {});
var NativeWebSocket = _global.WebSocket || _global.MozWebSocket;
var Backoff = require("backo2");
var eventemitter3_1 = require("eventemitter3");
var is_string_1 = require("./utils/is-string");
var is_object_1 = require("./utils/is-object");
var printer_1 = require("graphql/language/printer");
var getOperationAST_1 = require("graphql/utilities/getOperationAST");
var symbol_observable_1 = require("symbol-observable");
var protocol_1 = require("./protocol");
var defaults_1 = require("./defaults");
var message_types_1 = require("./message-types");
var SubscriptionClient = (function () {
function SubscriptionClient(url, options, webSocketImpl, webSocketProtocols) {
var _a = (options || {}), _b = _a.connectionCallback, connectionCallback = _b === void 0 ? undefined : _b, _c = _a.connectionParams, connectionParams = _c === void 0 ? {} : _c, _d = _a.minTimeout, minTimeout = _d === void 0 ? defaults_1.MIN_WS_TIMEOUT : _d, _e = _a.timeout, timeout = _e === void 0 ? defaults_1.WS_TIMEOUT : _e, _f = _a.reconnect, reconnect = _f === void 0 ? false : _f, _g = _a.reconnectionAttempts, reconnectionAttempts = _g === void 0 ? Infinity : _g, _h = _a.lazy, lazy = _h === void 0 ? false : _h, _j = _a.inactivityTimeout, inactivityTimeout = _j === void 0 ? 0 : _j, _k = _a.wsOptionArguments, wsOptionArguments = _k === void 0 ? [] : _k;
this.wsImpl = webSocketImpl || NativeWebSocket;
if (!this.wsImpl) {
throw new Error('Unable to find native implementation, or alternative implementation for WebSocket!');
}
this.wsProtocols = webSocketProtocols || protocol_1.GRAPHQL_WS;
this.connectionCallback = connectionCallback;
this.url = url;
this.operations = {};
this.nextOperationId = 0;
this.minWsTimeout = minTimeout;
this.wsTimeout = timeout;
this.unsentMessagesQueue = [];
this.reconnect = reconnect;
this.reconnecting = false;
this.reconnectionAttempts = reconnectionAttempts;
this.lazy = !!lazy;
this.inactivityTimeout = inactivityTimeout;
this.closedByUser = false;
this.backoff = new Backoff({ jitter: 0.5 });
this.eventEmitter = new eventemitter3_1.EventEmitter();
this.middlewares = [];
this.client = null;
this.maxConnectTimeGenerator = this.createMaxConnectTimeGenerator();
this.connectionParams = this.getConnectionParams(connectionParams);
this.wsOptionArguments = wsOptionArguments;
if (!this.lazy) {
this.connect();
}
}
Object.defineProperty(SubscriptionClient.prototype, "status", {
get: function () {
if (this.client === null) {
return this.wsImpl.CLOSED;
}
return this.client.readyState;
},
enumerable: false,
configurable: true
});
SubscriptionClient.prototype.close = function (isForced, closedByUser) {
if (isForced === void 0) { isForced = true; }
if (closedByUser === void 0) { closedByUser = true; }
this.clearInactivityTimeout();
if (this.client !== null) {
this.closedByUser = closedByUser;
if (isForced) {
this.clearCheckConnectionInterval();
this.clearMaxConnectTimeout();
this.clearTryReconnectTimeout();
this.unsubscribeAll();
this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_TERMINATE, null);
}
this.client.close();
this.client.onopen = null;
this.client.onclose = null;
this.client.onerror = null;
this.client.onmessage = null;
this.client = null;
this.eventEmitter.emit('disconnected');
if (!isForced) {
this.tryReconnect();
}
}
};
SubscriptionClient.prototype.request = function (request) {
var _a;
var getObserver = this.getObserver.bind(this);
var executeOperation = this.executeOperation.bind(this);
var unsubscribe = this.unsubscribe.bind(this);
var opId;
this.clearInactivityTimeout();
return _a = {},
_a[symbol_observable_1.default] = function () {
return this;
},
_a.subscribe = function (observerOrNext, onError, onComplete) {
var observer = getObserver(observerOrNext, onError, onComplete);
opId = executeOperation(request, function (error, result) {
if (error === null && result === null) {
if (observer.complete) {
observer.complete();
}
}
else if (error) {
if (observer.error) {
observer.error(error[0]);
}
}
else {
if (observer.next) {
observer.next(result);
}
}
});
return {
unsubscribe: function () {
if (opId) {
unsubscribe(opId);
opId = null;
}
},
};
},
_a;
};
SubscriptionClient.prototype.on = function (eventName, callback, context) {
var handler = this.eventEmitter.on(eventName, callback, context);
return function () {
handler.off(eventName, callback, context);
};
};
SubscriptionClient.prototype.onConnected = function (callback, context) {
return this.on('connected', callback, context);
};
SubscriptionClient.prototype.onConnecting = function (callback, context) {
return this.on('connecting', callback, context);
};
SubscriptionClient.prototype.onDisconnected = function (callback, context) {
return this.on('disconnected', callback, context);
};
SubscriptionClient.prototype.onReconnected = function (callback, context) {
return this.on('reconnected', callback, context);
};
SubscriptionClient.prototype.onReconnecting = function (callback, context) {
return this.on('reconnecting', callback, context);
};
SubscriptionClient.prototype.onError = function (callback, context) {
return this.on('error', callback, context);
};
SubscriptionClient.prototype.unsubscribeAll = function () {
var _this = this;
Object.keys(this.operations).forEach(function (subId) {
_this.unsubscribe(subId);
});
};
SubscriptionClient.prototype.applyMiddlewares = function (options) {
var _this = this;
return new Promise(function (resolve, reject) {
var queue = function (funcs, scope) {
var next = function (error) {
if (error) {
reject(error);
}
else {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyMiddleware.apply(scope, [options, next]);
}
}
else {
resolve(options);
}
}
};
next();
};
queue(__spreadArrays(_this.middlewares), _this);
});
};
SubscriptionClient.prototype.use = function (middlewares) {
var _this = this;
middlewares.map(function (middleware) {
if (typeof middleware.applyMiddleware === 'function') {
_this.middlewares.push(middleware);
}
else {
throw new Error('Middleware must implement the applyMiddleware function.');
}
});
return this;
};
SubscriptionClient.prototype.getConnectionParams = function (connectionParams) {
return function () { return new Promise(function (resolve, reject) {
if (typeof connectionParams === 'function') {
try {
return resolve(connectionParams.call(null));
}
catch (error) {
return reject(error);
}
}
resolve(connectionParams);
}); };
};
SubscriptionClient.prototype.executeOperation = function (options, handler) {
var _this = this;
if (this.client === null) {
this.connect();
}
var opId = this.generateOperationId();
this.operations[opId] = { options: options, handler: handler };
this.applyMiddlewares(options)
.then(function (processedOptions) {
_this.checkOperationOptions(processedOptions, handler);
if (_this.operations[opId]) {
_this.operations[opId] = { options: processedOptions, handler: handler };
_this.sendMessage(opId, message_types_1.default.GQL_START, processedOptions);
}
})
.catch(function (error) {
_this.unsubscribe(opId);
handler(_this.formatErrors(error));
});
return opId;
};
SubscriptionClient.prototype.getObserver = function (observerOrNext, error, complete) {
if (typeof observerOrNext === 'function') {
return {
next: function (v) { return observerOrNext(v); },
error: function (e) { return error && error(e); },
complete: function () { return complete && complete(); },
};
}
return observerOrNext;
};
SubscriptionClient.prototype.createMaxConnectTimeGenerator = function () {
var minValue = this.minWsTimeout;
var maxValue = this.wsTimeout;
return new Backoff({
min: minValue,
max: maxValue,
factor: 1.2,
});
};
SubscriptionClient.prototype.clearCheckConnectionInterval = function () {
if (this.checkConnectionIntervalId) {
clearInterval(this.checkConnectionIntervalId);
this.checkConnectionIntervalId = null;
}
};
SubscriptionClient.prototype.clearMaxConnectTimeout = function () {
if (this.maxConnectTimeoutId) {
clearTimeout(this.maxConnectTimeoutId);
this.maxConnectTimeoutId = null;
}
};
SubscriptionClient.prototype.clearTryReconnectTimeout = function () {
if (this.tryReconnectTimeoutId) {
clearTimeout(this.tryReconnectTimeoutId);
this.tryReconnectTimeoutId = null;
}
};
SubscriptionClient.prototype.clearInactivityTimeout = function () {
if (this.inactivityTimeoutId) {
clearTimeout(this.inactivityTimeoutId);
this.inactivityTimeoutId = null;
}
};
SubscriptionClient.prototype.setInactivityTimeout = function () {
var _this = this;
if (this.inactivityTimeout > 0 && Object.keys(this.operations).length === 0) {
this.inactivityTimeoutId = setTimeout(function () {
if (Object.keys(_this.operations).length === 0) {
_this.close();
}
}, this.inactivityTimeout);
}
};
SubscriptionClient.prototype.checkOperationOptions = function (options, handler) {
var query = options.query, variables = options.variables, operationName = options.operationName;
if (!query) {
throw new Error('Must provide a query.');
}
if (!handler) {
throw new Error('Must provide an handler.');
}
if ((!is_string_1.default(query) && !getOperationAST_1.getOperationAST(query, operationName)) ||
(operationName && !is_string_1.default(operationName)) ||
(variables && !is_object_1.default(variables))) {
throw new Error('Incorrect option types. query must be a string or a document,' +
'`operationName` must be a string, and `variables` must be an object.');
}
};
SubscriptionClient.prototype.buildMessage = function (id, type, payload) {
var payloadToReturn = payload && payload.query ? __assign(__assign({}, payload), { query: typeof payload.query === 'string' ? payload.query : printer_1.print(payload.query) }) :
payload;
return {
id: id,
type: type,
payload: payloadToReturn,
};
};
SubscriptionClient.prototype.formatErrors = function (errors) {
if (Array.isArray(errors)) {
return errors;
}
if (errors && errors.errors) {
return this.formatErrors(errors.errors);
}
if (errors && errors.message) {
return [errors];
}
return [{
name: 'FormatedError',
message: 'Unknown error',
originalError: errors,
}];
};
SubscriptionClient.prototype.sendMessage = function (id, type, payload) {
this.sendMessageRaw(this.buildMessage(id, type, payload));
};
SubscriptionClient.prototype.sendMessageRaw = function (message) {
switch (this.status) {
case this.wsImpl.OPEN:
var serializedMessage = JSON.stringify(message);
try {
JSON.parse(serializedMessage);
}
catch (e) {
this.eventEmitter.emit('error', new Error("Message must be JSON-serializable. Got: " + message));
}
this.client.send(serializedMessage);
break;
case this.wsImpl.CONNECTING:
this.unsentMessagesQueue.push(message);
break;
default:
if (!this.reconnecting) {
this.eventEmitter.emit('error', new Error('A message was not sent because socket is not connected, is closing or ' +
'is already closed. Message was: ' + JSON.stringify(message)));
}
}
};
SubscriptionClient.prototype.generateOperationId = function () {
return String(++this.nextOperationId);
};
SubscriptionClient.prototype.tryReconnect = function () {
var _this = this;
if (!this.reconnect || this.backoff.attempts >= this.reconnectionAttempts) {
return;
}
if (!this.reconnecting) {
Object.keys(this.operations).forEach(function (key) {
_this.unsentMessagesQueue.push(_this.buildMessage(key, message_types_1.default.GQL_START, _this.operations[key].options));
});
this.reconnecting = true;
}
this.clearTryReconnectTimeout();
var delay = this.backoff.duration();
this.tryReconnectTimeoutId = setTimeout(function () {
_this.connect();
}, delay);
};
SubscriptionClient.prototype.flushUnsentMessagesQueue = function () {
var _this = this;
this.unsentMessagesQueue.forEach(function (message) {
_this.sendMessageRaw(message);
});
this.unsentMessagesQueue = [];
};
SubscriptionClient.prototype.checkConnection = function () {
if (this.wasKeepAliveReceived) {
this.wasKeepAliveReceived = false;
return;
}
if (!this.reconnecting) {
this.close(false, true);
}
};
SubscriptionClient.prototype.checkMaxConnectTimeout = function () {
var _this = this;
this.clearMaxConnectTimeout();
this.maxConnectTimeoutId = setTimeout(function () {
if (_this.status !== _this.wsImpl.OPEN) {
_this.reconnecting = true;
_this.close(false, true);
}
}, this.maxConnectTimeGenerator.duration());
};
SubscriptionClient.prototype.connect = function () {
var _a;
var _this = this;
this.client = new ((_a = this.wsImpl).bind.apply(_a, __spreadArrays([void 0, this.url, this.wsProtocols], this.wsOptionArguments)))();
this.checkMaxConnectTimeout();
this.client.onopen = function () { return __awaiter(_this, void 0, void 0, function () {
var connectionParams, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(this.status === this.wsImpl.OPEN)) return [3, 4];
this.clearMaxConnectTimeout();
this.closedByUser = false;
this.eventEmitter.emit(this.reconnecting ? 'reconnecting' : 'connecting');
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4, this.connectionParams()];
case 2:
connectionParams = _a.sent();
this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_INIT, connectionParams);
this.flushUnsentMessagesQueue();
return [3, 4];
case 3:
error_1 = _a.sent();
this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_ERROR, error_1);
this.flushUnsentMessagesQueue();
return [3, 4];
case 4: return [2];
}
});
}); };
this.client.onclose = function () {
if (!_this.closedByUser) {
_this.close(false, false);
}
};
this.client.onerror = function (err) {
_this.eventEmitter.emit('error', err);
};
this.client.onmessage = function (_a) {
var data = _a.data;
_this.processReceivedData(data);
};
};
SubscriptionClient.prototype.processReceivedData = function (receivedData) {
var parsedMessage;
var opId;
try {
parsedMessage = JSON.parse(receivedData);
opId = parsedMessage.id;
}
catch (e) {
throw new Error("Message must be JSON-parseable. Got: " + receivedData);
}
if ([message_types_1.default.GQL_DATA,
message_types_1.default.GQL_COMPLETE,
message_types_1.default.GQL_ERROR,
].indexOf(parsedMessage.type) !== -1 && !this.operations[opId]) {
this.unsubscribe(opId);
return;
}
switch (parsedMessage.type) {
case message_types_1.default.GQL_CONNECTION_ERROR:
if (this.connectionCallback) {
this.connectionCallback(parsedMessage.payload);
}
break;
case message_types_1.default.GQL_CONNECTION_ACK:
this.eventEmitter.emit(this.reconnecting ? 'reconnected' : 'connected', parsedMessage.payload);
this.reconnecting = false;
this.backoff.reset();
this.maxConnectTimeGenerator.reset();
if (this.connectionCallback) {
this.connectionCallback();
}
break;
case message_types_1.default.GQL_COMPLETE:
var handler = this.operations[opId].handler;
delete this.operations[opId];
handler.call(this, null, null);
break;
case message_types_1.default.GQL_ERROR:
this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null);
delete this.operations[opId];
break;
case message_types_1.default.GQL_DATA:
var parsedPayload = !parsedMessage.payload.errors ?
parsedMessage.payload : __assign(__assign({}, parsedMessage.payload), { errors: this.formatErrors(parsedMessage.payload.errors) });
this.operations[opId].handler(null, parsedPayload);
break;
case message_types_1.default.GQL_CONNECTION_KEEP_ALIVE:
var firstKA = typeof this.wasKeepAliveReceived === 'undefined';
this.wasKeepAliveReceived = true;
if (firstKA) {
this.checkConnection();
}
if (this.checkConnectionIntervalId) {
clearInterval(this.checkConnectionIntervalId);
this.checkConnection();
}
this.checkConnectionIntervalId = setInterval(this.checkConnection.bind(this), this.wsTimeout);
break;
default:
throw new Error('Invalid message type!');
}
};
SubscriptionClient.prototype.unsubscribe = function (opId) {
if (this.operations[opId]) {
delete this.operations[opId];
this.setInactivityTimeout();
this.sendMessage(opId, message_types_1.default.GQL_STOP, undefined);
}
};
return SubscriptionClient;
}());
exports.SubscriptionClient = SubscriptionClient;
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
declare const MIN_WS_TIMEOUT = 1000;
declare const WS_TIMEOUT = 30000;
export { MIN_WS_TIMEOUT, WS_TIMEOUT, };

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WS_TIMEOUT = exports.MIN_WS_TIMEOUT = void 0;
var MIN_WS_TIMEOUT = 1000;
exports.MIN_WS_TIMEOUT = MIN_WS_TIMEOUT;
var WS_TIMEOUT = 30000;
exports.WS_TIMEOUT = WS_TIMEOUT;
//# sourceMappingURL=defaults.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":";;;AAAA,IAAM,cAAc,GAAG,IAAI,CAAC;AAI1B,wCAAc;AAHhB,IAAM,UAAU,GAAG,KAAK,CAAC;AAIvB,gCAAU","sourcesContent":["const MIN_WS_TIMEOUT = 1000;\nconst WS_TIMEOUT = 30000;\n\nexport {\n MIN_WS_TIMEOUT,\n WS_TIMEOUT,\n};\n"]}

View File

@@ -0,0 +1,4 @@
export * from './client';
export * from './server';
export { default as MessageTypes } from './message-types';
export * from './protocol';

18
node_modules/subscriptions-transport-ws/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./client"), exports);
__exportStar(require("./server"), exports);
var message_types_1 = require("./message-types");
Object.defineProperty(exports, "MessageTypes", { enumerable: true, get: function () { return message_types_1.default; } });
__exportStar(require("./protocol"), exports);
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,iDAA0D;AAAjD,6GAAA,OAAO,OAAgB;AAChC,6CAA2B","sourcesContent":["export * from './client';\nexport * from './server';\nexport { default as MessageTypes } from './message-types';\nexport * from './protocol';\n"]}

View File

@@ -0,0 +1,2 @@
import { ConnectionContext } from '../server';
export declare const parseLegacyProtocolMessage: (connectionContext: ConnectionContext, message: any) => any;

View File

@@ -0,0 +1,72 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseLegacyProtocolMessage = void 0;
var message_types_1 = require("../message-types");
exports.parseLegacyProtocolMessage = function (connectionContext, message) {
var messageToReturn = message;
switch (message.type) {
case message_types_1.default.INIT:
connectionContext.isLegacy = true;
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.GQL_CONNECTION_INIT });
break;
case message_types_1.default.SUBSCRIPTION_START:
messageToReturn = {
id: message.id,
type: message_types_1.default.GQL_START,
payload: {
query: message.query,
operationName: message.operationName,
variables: message.variables,
},
};
break;
case message_types_1.default.SUBSCRIPTION_END:
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.GQL_STOP });
break;
case message_types_1.default.GQL_CONNECTION_ACK:
if (connectionContext.isLegacy) {
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.INIT_SUCCESS });
}
break;
case message_types_1.default.GQL_CONNECTION_ERROR:
if (connectionContext.isLegacy) {
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.INIT_FAIL, payload: message.payload.message ? { error: message.payload.message } : message.payload });
}
break;
case message_types_1.default.GQL_ERROR:
if (connectionContext.isLegacy) {
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.SUBSCRIPTION_FAIL });
}
break;
case message_types_1.default.GQL_DATA:
if (connectionContext.isLegacy) {
messageToReturn = __assign(__assign({}, message), { type: message_types_1.default.SUBSCRIPTION_DATA });
}
break;
case message_types_1.default.GQL_COMPLETE:
if (connectionContext.isLegacy) {
messageToReturn = null;
}
break;
case message_types_1.default.SUBSCRIPTION_SUCCESS:
if (!connectionContext.isLegacy) {
messageToReturn = null;
}
break;
default:
break;
}
return messageToReturn;
};
//# sourceMappingURL=parse-legacy-protocol.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parse-legacy-protocol.js","sourceRoot":"","sources":["../../src/legacy/parse-legacy-protocol.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,kDAA4C;AAE/B,QAAA,0BAA0B,GAAG,UAAC,iBAAoC,EAAE,OAAY;IAC3F,IAAI,eAAe,GAAG,OAAO,CAAC;IAE9B,QAAQ,OAAO,CAAC,IAAI,EAAE;QACpB,KAAK,uBAAY,CAAC,IAAI;YACpB,iBAAiB,CAAC,QAAQ,GAAG,IAAI,CAAC;YAClC,eAAe,yBAAQ,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,mBAAmB,GAAE,CAAC;YACzE,MAAM;QACR,KAAK,uBAAY,CAAC,kBAAkB;YAClC,eAAe,GAAG;gBAChB,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,IAAI,EAAE,uBAAY,CAAC,SAAS;gBAC5B,OAAO,EAAE;oBACP,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,aAAa,EAAE,OAAO,CAAC,aAAa;oBACpC,SAAS,EAAE,OAAO,CAAC,SAAS;iBAC7B;aACF,CAAC;YACF,MAAM;QACR,KAAK,uBAAY,CAAC,gBAAgB;YAChC,eAAe,yBAAQ,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,QAAQ,GAAE,CAAC;YAC9D,MAAM;QACR,KAAK,uBAAY,CAAC,kBAAkB;YAClC,IAAI,iBAAiB,CAAC,QAAQ,EAAE;gBAC9B,eAAe,yBAAQ,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,YAAY,GAAE,CAAC;aACnE;YACD,MAAM;QACR,KAAK,uBAAY,CAAC,oBAAoB;YACpC,IAAI,iBAAiB,CAAC,QAAQ,EAAE;gBAC9B,eAAe,yBACV,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,SAAS,EACxC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,GACxF,CAAC;aACH;YACD,MAAM;QACR,KAAK,uBAAY,CAAC,SAAS;YACzB,IAAI,iBAAiB,CAAC,QAAQ,EAAE;gBAC9B,eAAe,yBAAQ,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,iBAAiB,GAAE,CAAC;aACxE;YACD,MAAM;QACR,KAAK,uBAAY,CAAC,QAAQ;YACxB,IAAI,iBAAiB,CAAC,QAAQ,EAAE;gBAC9B,eAAe,yBAAQ,OAAO,KAAE,IAAI,EAAE,uBAAY,CAAC,iBAAiB,GAAE,CAAC;aACxE;YACD,MAAM;QACR,KAAK,uBAAY,CAAC,YAAY;YAC5B,IAAI,iBAAiB,CAAC,QAAQ,EAAE;gBAC9B,eAAe,GAAG,IAAI,CAAC;aACxB;YACD,MAAM;QACR,KAAK,uBAAY,CAAC,oBAAoB;YACpC,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE;gBAC/B,eAAe,GAAG,IAAI,CAAC;aACxB;YACD,MAAM;QACR;YACE,MAAM;KACT;IAED,OAAO,eAAe,CAAC;AACzB,CAAC,CAAC","sourcesContent":["import { ConnectionContext } from '../server';\nimport MessageTypes from '../message-types';\n\nexport const parseLegacyProtocolMessage = (connectionContext: ConnectionContext, message: any) => {\n let messageToReturn = message;\n\n switch (message.type) {\n case MessageTypes.INIT:\n connectionContext.isLegacy = true;\n messageToReturn = { ...message, type: MessageTypes.GQL_CONNECTION_INIT };\n break;\n case MessageTypes.SUBSCRIPTION_START:\n messageToReturn = {\n id: message.id,\n type: MessageTypes.GQL_START,\n payload: {\n query: message.query,\n operationName: message.operationName,\n variables: message.variables,\n },\n };\n break;\n case MessageTypes.SUBSCRIPTION_END:\n messageToReturn = { ...message, type: MessageTypes.GQL_STOP };\n break;\n case MessageTypes.GQL_CONNECTION_ACK:\n if (connectionContext.isLegacy) {\n messageToReturn = { ...message, type: MessageTypes.INIT_SUCCESS };\n }\n break;\n case MessageTypes.GQL_CONNECTION_ERROR:\n if (connectionContext.isLegacy) {\n messageToReturn = {\n ...message, type: MessageTypes.INIT_FAIL,\n payload: message.payload.message ? { error: message.payload.message } : message.payload,\n };\n }\n break;\n case MessageTypes.GQL_ERROR:\n if (connectionContext.isLegacy) {\n messageToReturn = { ...message, type: MessageTypes.SUBSCRIPTION_FAIL };\n }\n break;\n case MessageTypes.GQL_DATA:\n if (connectionContext.isLegacy) {\n messageToReturn = { ...message, type: MessageTypes.SUBSCRIPTION_DATA };\n }\n break;\n case MessageTypes.GQL_COMPLETE:\n if (connectionContext.isLegacy) {\n messageToReturn = null;\n }\n break;\n case MessageTypes.SUBSCRIPTION_SUCCESS:\n if (!connectionContext.isLegacy) {\n messageToReturn = null;\n }\n break;\n default:\n break;\n }\n\n return messageToReturn;\n};\n"]}

View File

@@ -0,0 +1,22 @@
export default class MessageTypes {
static GQL_CONNECTION_INIT: string;
static GQL_CONNECTION_ACK: string;
static GQL_CONNECTION_ERROR: string;
static GQL_CONNECTION_KEEP_ALIVE: string;
static GQL_CONNECTION_TERMINATE: string;
static GQL_START: string;
static GQL_DATA: string;
static GQL_ERROR: string;
static GQL_COMPLETE: string;
static GQL_STOP: string;
static SUBSCRIPTION_START: string;
static SUBSCRIPTION_DATA: string;
static SUBSCRIPTION_SUCCESS: string;
static SUBSCRIPTION_FAIL: string;
static SUBSCRIPTION_END: string;
static INIT: string;
static INIT_SUCCESS: string;
static INIT_FAIL: string;
static KEEP_ALIVE: string;
constructor();
}

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MessageTypes = (function () {
function MessageTypes() {
throw new Error('Static Class');
}
MessageTypes.GQL_CONNECTION_INIT = 'connection_init';
MessageTypes.GQL_CONNECTION_ACK = 'connection_ack';
MessageTypes.GQL_CONNECTION_ERROR = 'connection_error';
MessageTypes.GQL_CONNECTION_KEEP_ALIVE = 'ka';
MessageTypes.GQL_CONNECTION_TERMINATE = 'connection_terminate';
MessageTypes.GQL_START = 'start';
MessageTypes.GQL_DATA = 'data';
MessageTypes.GQL_ERROR = 'error';
MessageTypes.GQL_COMPLETE = 'complete';
MessageTypes.GQL_STOP = 'stop';
MessageTypes.SUBSCRIPTION_START = 'subscription_start';
MessageTypes.SUBSCRIPTION_DATA = 'subscription_data';
MessageTypes.SUBSCRIPTION_SUCCESS = 'subscription_success';
MessageTypes.SUBSCRIPTION_FAIL = 'subscription_fail';
MessageTypes.SUBSCRIPTION_END = 'subscription_end';
MessageTypes.INIT = 'init';
MessageTypes.INIT_SUCCESS = 'init_success';
MessageTypes.INIT_FAIL = 'init_fail';
MessageTypes.KEEP_ALIVE = 'keepalive';
return MessageTypes;
}());
exports.default = MessageTypes;
//# sourceMappingURL=message-types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"message-types.js","sourceRoot":"","sources":["../src/message-types.ts"],"names":[],"mappings":";;AAAA;IAqDE;QACE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;IAClC,CAAC;IAtDa,gCAAmB,GAAG,iBAAiB,CAAC;IACxC,+BAAkB,GAAG,gBAAgB,CAAC;IACtC,iCAAoB,GAAG,kBAAkB,CAAC;IAG1C,sCAAyB,GAAG,IAAI,CAAC;IAEjC,qCAAwB,GAAG,sBAAsB,CAAC;IAClD,sBAAS,GAAG,OAAO,CAAC;IACpB,qBAAQ,GAAG,MAAM,CAAC;IAClB,sBAAS,GAAG,OAAO,CAAC;IACpB,yBAAY,GAAG,UAAU,CAAC;IAC1B,qBAAQ,GAAG,MAAM,CAAC;IAMlB,+BAAkB,GAAG,oBAAoB,CAAC;IAI1C,8BAAiB,GAAG,mBAAmB,CAAC;IAIxC,iCAAoB,GAAG,sBAAsB,CAAC;IAI9C,8BAAiB,GAAG,mBAAmB,CAAC;IAIxC,6BAAgB,GAAG,kBAAkB,CAAC;IAItC,iBAAI,GAAG,MAAM,CAAC;IAId,yBAAY,GAAG,cAAc,CAAC;IAI9B,sBAAS,GAAG,WAAW,CAAC;IAIxB,uBAAU,GAAG,WAAW,CAAC;IAKzC,mBAAC;CAAA,AAxDD,IAwDC;kBAxDoB,YAAY","sourcesContent":["export default class MessageTypes {\n public static GQL_CONNECTION_INIT = 'connection_init'; // Client -> Server\n public static GQL_CONNECTION_ACK = 'connection_ack'; // Server -> Client\n public static GQL_CONNECTION_ERROR = 'connection_error'; // Server -> Client\n\n // NOTE: The keep alive message type does not follow the standard due to connection optimizations\n public static GQL_CONNECTION_KEEP_ALIVE = 'ka'; // Server -> Client\n\n public static GQL_CONNECTION_TERMINATE = 'connection_terminate'; // Client -> Server\n public static GQL_START = 'start'; // Client -> Server\n public static GQL_DATA = 'data'; // Server -> Client\n public static GQL_ERROR = 'error'; // Server -> Client\n public static GQL_COMPLETE = 'complete'; // Server -> Client\n public static GQL_STOP = 'stop'; // Client -> Server\n\n // NOTE: The following message types are deprecated and will be removed soon.\n /**\n * @deprecated\n */\n public static SUBSCRIPTION_START = 'subscription_start';\n /**\n * @deprecated\n */\n public static SUBSCRIPTION_DATA = 'subscription_data';\n /**\n * @deprecated\n */\n public static SUBSCRIPTION_SUCCESS = 'subscription_success';\n /**\n * @deprecated\n */\n public static SUBSCRIPTION_FAIL = 'subscription_fail';\n /**\n * @deprecated\n */\n public static SUBSCRIPTION_END = 'subscription_end';\n /**\n * @deprecated\n */\n public static INIT = 'init';\n /**\n * @deprecated\n */\n public static INIT_SUCCESS = 'init_success';\n /**\n * @deprecated\n */\n public static INIT_FAIL = 'init_fail';\n /**\n * @deprecated\n */\n public static KEEP_ALIVE = 'keepalive';\n\n constructor() {\n throw new Error('Static Class');\n }\n}\n"]}

View File

@@ -0,0 +1,3 @@
declare const GRAPHQL_WS = "graphql-ws";
declare const GRAPHQL_SUBSCRIPTIONS = "graphql-subscriptions";
export { GRAPHQL_WS, GRAPHQL_SUBSCRIPTIONS, };

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GRAPHQL_SUBSCRIPTIONS = exports.GRAPHQL_WS = void 0;
var GRAPHQL_WS = 'graphql-ws';
exports.GRAPHQL_WS = GRAPHQL_WS;
var GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';
exports.GRAPHQL_SUBSCRIPTIONS = GRAPHQL_SUBSCRIPTIONS;
//# sourceMappingURL=protocol.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":";;;AAAA,IAAM,UAAU,GAAG,YAAY,CAAC;AAQ9B,gCAAU;AAHZ,IAAM,qBAAqB,GAAG,uBAAuB,CAAC;AAIpD,sDAAqB","sourcesContent":["const GRAPHQL_WS = 'graphql-ws';\n// NOTE: This protocol is deprecated and will be removed soon.\n/**\n * @deprecated\n */\nconst GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';\n\nexport {\n GRAPHQL_WS,\n GRAPHQL_SUBSCRIPTIONS,\n};\n"]}

View File

@@ -0,0 +1,82 @@
/// <reference types="node" />
import * as WebSocket from 'ws';
import { ExecutionResult, GraphQLSchema, DocumentNode, ValidationContext, GraphQLFieldResolver } from 'graphql';
import { IncomingMessage } from 'http';
export declare type ExecutionIterator = AsyncIterator<ExecutionResult>;
export interface ExecutionParams<TContext = any> {
query: string | DocumentNode;
variables: {
[key: string]: any;
};
operationName: string;
context: TContext;
formatResponse?: Function;
formatError?: Function;
callback?: Function;
schema?: GraphQLSchema;
}
export declare type ConnectionContext = {
initPromise?: Promise<any>;
isLegacy: boolean;
socket: WebSocket;
request: IncomingMessage;
operations: {
[opId: string]: ExecutionIterator;
};
};
export interface OperationMessagePayload {
[key: string]: any;
query?: string;
variables?: {
[key: string]: any;
};
operationName?: string;
}
export interface OperationMessage {
payload?: OperationMessagePayload;
id?: string;
type: string;
}
export declare type ExecuteFunction = (schema: GraphQLSchema, document: DocumentNode, rootValue?: any, contextValue?: any, variableValues?: {
[key: string]: any;
}, operationName?: string, fieldResolver?: GraphQLFieldResolver<any, any>) => ExecutionResult | Promise<ExecutionResult> | AsyncIterator<ExecutionResult>;
export declare type SubscribeFunction = (schema: GraphQLSchema, document: DocumentNode, rootValue?: any, contextValue?: any, variableValues?: {
[key: string]: any;
}, operationName?: string, fieldResolver?: GraphQLFieldResolver<any, any>, subscribeFieldResolver?: GraphQLFieldResolver<any, any>) => AsyncIterator<ExecutionResult> | Promise<AsyncIterator<ExecutionResult> | ExecutionResult>;
export interface ServerOptions {
rootValue?: any;
schema?: GraphQLSchema;
execute?: ExecuteFunction;
subscribe?: SubscribeFunction;
validationRules?: Array<(context: ValidationContext) => any> | ReadonlyArray<any>;
onOperation?: Function;
onOperationComplete?: Function;
onConnect?: Function;
onDisconnect?: Function;
keepAlive?: number;
}
export declare class SubscriptionServer {
private onOperation;
private onOperationComplete;
private onConnect;
private onDisconnect;
private wsServer;
private execute;
private subscribe;
private schema;
private rootValue;
private keepAlive;
private closeHandler;
private specifiedRules;
static create(options: ServerOptions, socketOptionsOrServer: WebSocket.ServerOptions | WebSocket.Server): SubscriptionServer;
constructor(options: ServerOptions, socketOptionsOrServer: WebSocket.ServerOptions | WebSocket.Server);
get server(): WebSocket.Server;
close(): void;
private loadExecutor;
private unsubscribe;
private onClose;
private onMessage;
private sendKeepAlive;
private sendMessage;
private sendError;
}

299
node_modules/subscriptions-transport-ws/dist/server.js generated vendored Normal file
View File

@@ -0,0 +1,299 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubscriptionServer = void 0;
var WebSocket = require("ws");
var message_types_1 = require("./message-types");
var protocol_1 = require("./protocol");
var is_object_1 = require("./utils/is-object");
var graphql_1 = require("graphql");
var empty_iterable_1 = require("./utils/empty-iterable");
var iterall_1 = require("iterall");
var is_subscriptions_1 = require("./utils/is-subscriptions");
var parse_legacy_protocol_1 = require("./legacy/parse-legacy-protocol");
var isWebSocketServer = function (socket) { return socket.on; };
var SubscriptionServer = (function () {
function SubscriptionServer(options, socketOptionsOrServer) {
var _this = this;
var onOperation = options.onOperation, onOperationComplete = options.onOperationComplete, onConnect = options.onConnect, onDisconnect = options.onDisconnect, keepAlive = options.keepAlive;
this.specifiedRules = options.validationRules || graphql_1.specifiedRules;
this.loadExecutor(options);
this.onOperation = onOperation;
this.onOperationComplete = onOperationComplete;
this.onConnect = onConnect;
this.onDisconnect = onDisconnect;
this.keepAlive = keepAlive;
if (isWebSocketServer(socketOptionsOrServer)) {
this.wsServer = socketOptionsOrServer;
}
else {
this.wsServer = new WebSocket.Server(socketOptionsOrServer || {});
}
var connectionHandler = (function (socket, request) {
socket.upgradeReq = request;
if (socket.protocol === undefined ||
(socket.protocol.indexOf(protocol_1.GRAPHQL_WS) === -1 && socket.protocol.indexOf(protocol_1.GRAPHQL_SUBSCRIPTIONS) === -1)) {
socket.close(1002);
return;
}
var connectionContext = Object.create(null);
connectionContext.initPromise = Promise.resolve(true);
connectionContext.isLegacy = false;
connectionContext.socket = socket;
connectionContext.request = request;
connectionContext.operations = {};
var connectionClosedHandler = function (error) {
if (error) {
_this.sendError(connectionContext, '', { message: error.message ? error.message : error }, message_types_1.default.GQL_CONNECTION_ERROR);
setTimeout(function () {
connectionContext.socket.close(1011);
}, 10);
}
_this.onClose(connectionContext);
if (_this.onDisconnect) {
_this.onDisconnect(socket, connectionContext);
}
};
socket.on('error', connectionClosedHandler);
socket.on('close', connectionClosedHandler);
socket.on('message', _this.onMessage(connectionContext));
});
this.wsServer.on('connection', connectionHandler);
this.closeHandler = function () {
_this.wsServer.removeListener('connection', connectionHandler);
_this.wsServer.close();
};
}
SubscriptionServer.create = function (options, socketOptionsOrServer) {
return new SubscriptionServer(options, socketOptionsOrServer);
};
Object.defineProperty(SubscriptionServer.prototype, "server", {
get: function () {
return this.wsServer;
},
enumerable: false,
configurable: true
});
SubscriptionServer.prototype.close = function () {
this.closeHandler();
};
SubscriptionServer.prototype.loadExecutor = function (options) {
var execute = options.execute, subscribe = options.subscribe, schema = options.schema, rootValue = options.rootValue;
if (!execute) {
throw new Error('Must provide `execute` for websocket server constructor.');
}
this.schema = schema;
this.rootValue = rootValue;
this.execute = execute;
this.subscribe = subscribe;
};
SubscriptionServer.prototype.unsubscribe = function (connectionContext, opId) {
if (connectionContext.operations && connectionContext.operations[opId]) {
if (connectionContext.operations[opId].return) {
connectionContext.operations[opId].return();
}
delete connectionContext.operations[opId];
if (this.onOperationComplete) {
this.onOperationComplete(connectionContext.socket, opId);
}
}
};
SubscriptionServer.prototype.onClose = function (connectionContext) {
var _this = this;
Object.keys(connectionContext.operations).forEach(function (opId) {
_this.unsubscribe(connectionContext, opId);
});
};
SubscriptionServer.prototype.onMessage = function (connectionContext) {
var _this = this;
return function (message) {
var parsedMessage;
try {
parsedMessage = parse_legacy_protocol_1.parseLegacyProtocolMessage(connectionContext, JSON.parse(message));
}
catch (e) {
_this.sendError(connectionContext, null, { message: e.message }, message_types_1.default.GQL_CONNECTION_ERROR);
return;
}
var opId = parsedMessage.id;
switch (parsedMessage.type) {
case message_types_1.default.GQL_CONNECTION_INIT:
if (_this.onConnect) {
connectionContext.initPromise = new Promise(function (resolve, reject) {
try {
resolve(_this.onConnect(parsedMessage.payload, connectionContext.socket, connectionContext));
}
catch (e) {
reject(e);
}
});
}
connectionContext.initPromise.then(function (result) {
if (result === false) {
throw new Error('Prohibited connection!');
}
_this.sendMessage(connectionContext, undefined, message_types_1.default.GQL_CONNECTION_ACK, undefined);
if (_this.keepAlive) {
_this.sendKeepAlive(connectionContext);
var keepAliveTimer_1 = setInterval(function () {
if (connectionContext.socket.readyState === WebSocket.OPEN) {
_this.sendKeepAlive(connectionContext);
}
else {
clearInterval(keepAliveTimer_1);
}
}, _this.keepAlive);
}
}).catch(function (error) {
_this.sendError(connectionContext, opId, { message: error.message }, message_types_1.default.GQL_CONNECTION_ERROR);
setTimeout(function () {
connectionContext.socket.close(1011);
}, 10);
});
break;
case message_types_1.default.GQL_CONNECTION_TERMINATE:
connectionContext.socket.close();
break;
case message_types_1.default.GQL_START:
connectionContext.initPromise.then(function (initResult) {
if (connectionContext.operations && connectionContext.operations[opId]) {
_this.unsubscribe(connectionContext, opId);
}
var baseParams = {
query: parsedMessage.payload.query,
variables: parsedMessage.payload.variables,
operationName: parsedMessage.payload.operationName,
context: is_object_1.default(initResult) ? Object.assign(Object.create(Object.getPrototypeOf(initResult)), initResult) : {},
formatResponse: undefined,
formatError: undefined,
callback: undefined,
schema: _this.schema,
};
var promisedParams = Promise.resolve(baseParams);
connectionContext.operations[opId] = empty_iterable_1.createEmptyIterable();
if (_this.onOperation) {
var messageForCallback = parsedMessage;
promisedParams = Promise.resolve(_this.onOperation(messageForCallback, baseParams, connectionContext.socket));
}
return promisedParams.then(function (params) {
if (typeof params !== 'object') {
var error = "Invalid params returned from onOperation! return values must be an object!";
_this.sendError(connectionContext, opId, { message: error });
throw new Error(error);
}
if (!params.schema) {
var error = 'Missing schema information. The GraphQL schema should be provided either statically in' +
' the `SubscriptionServer` constructor or as a property on the object returned from onOperation!';
_this.sendError(connectionContext, opId, { message: error });
throw new Error(error);
}
var document = typeof baseParams.query !== 'string' ? baseParams.query : graphql_1.parse(baseParams.query);
var executionPromise;
var validationErrors = graphql_1.validate(params.schema, document, _this.specifiedRules);
if (validationErrors.length > 0) {
executionPromise = Promise.resolve({ errors: validationErrors });
}
else {
var executor = _this.execute;
if (_this.subscribe && is_subscriptions_1.isASubscriptionOperation(document, params.operationName)) {
executor = _this.subscribe;
}
executionPromise = Promise.resolve(executor(params.schema, document, _this.rootValue, params.context, params.variables, params.operationName));
}
return executionPromise.then(function (executionResult) { return ({
executionIterable: iterall_1.isAsyncIterable(executionResult) ?
executionResult : iterall_1.createAsyncIterator([executionResult]),
params: params,
}); });
}).then(function (_a) {
var executionIterable = _a.executionIterable, params = _a.params;
iterall_1.forAwaitEach(executionIterable, function (value) {
var result = value;
if (params.formatResponse) {
try {
result = params.formatResponse(value, params);
}
catch (err) {
console.error('Error in formatResponse function:', err);
}
}
_this.sendMessage(connectionContext, opId, message_types_1.default.GQL_DATA, result);
})
.then(function () {
_this.sendMessage(connectionContext, opId, message_types_1.default.GQL_COMPLETE, null);
})
.catch(function (e) {
var error = e;
if (params.formatError) {
try {
error = params.formatError(e, params);
}
catch (err) {
console.error('Error in formatError function: ', err);
}
}
if (Object.keys(error).length === 0) {
error = { name: error.name, message: error.message };
}
_this.sendError(connectionContext, opId, error);
});
return executionIterable;
}).then(function (subscription) {
connectionContext.operations[opId] = subscription;
}).then(function () {
_this.sendMessage(connectionContext, opId, message_types_1.default.SUBSCRIPTION_SUCCESS, undefined);
}).catch(function (e) {
if (e.errors) {
_this.sendMessage(connectionContext, opId, message_types_1.default.GQL_DATA, { errors: e.errors });
}
else {
_this.sendError(connectionContext, opId, { message: e.message });
}
_this.unsubscribe(connectionContext, opId);
return;
});
}).catch(function (error) {
_this.sendError(connectionContext, opId, { message: error.message });
_this.unsubscribe(connectionContext, opId);
});
break;
case message_types_1.default.GQL_STOP:
_this.unsubscribe(connectionContext, opId);
break;
default:
_this.sendError(connectionContext, opId, { message: 'Invalid message type!' });
}
};
};
SubscriptionServer.prototype.sendKeepAlive = function (connectionContext) {
if (connectionContext.isLegacy) {
this.sendMessage(connectionContext, undefined, message_types_1.default.KEEP_ALIVE, undefined);
}
else {
this.sendMessage(connectionContext, undefined, message_types_1.default.GQL_CONNECTION_KEEP_ALIVE, undefined);
}
};
SubscriptionServer.prototype.sendMessage = function (connectionContext, opId, type, payload) {
var parsedMessage = parse_legacy_protocol_1.parseLegacyProtocolMessage(connectionContext, {
type: type,
id: opId,
payload: payload,
});
if (parsedMessage && connectionContext.socket.readyState === WebSocket.OPEN) {
connectionContext.socket.send(JSON.stringify(parsedMessage));
}
};
SubscriptionServer.prototype.sendError = function (connectionContext, opId, errorPayload, overrideDefaultErrorType) {
var sanitizedOverrideDefaultErrorType = overrideDefaultErrorType || message_types_1.default.GQL_ERROR;
if ([
message_types_1.default.GQL_CONNECTION_ERROR,
message_types_1.default.GQL_ERROR,
].indexOf(sanitizedOverrideDefaultErrorType) === -1) {
throw new Error('overrideDefaultErrorType should be one of the allowed error messages' +
' GQL_CONNECTION_ERROR or GQL_ERROR');
}
this.sendMessage(connectionContext, opId, sanitizedOverrideDefaultErrorType, errorPayload);
};
return SubscriptionServer;
}());
exports.SubscriptionServer = SubscriptionServer;
//# sourceMappingURL=server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import { $$asyncIterator } from 'iterall';
declare type EmptyIterable = AsyncIterator<any> & {
[$$asyncIterator]: any;
};
export declare const createEmptyIterable: () => EmptyIterable;
export {};

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEmptyIterable = void 0;
var iterall_1 = require("iterall");
exports.createEmptyIterable = function () {
var _a;
return _a = {
next: function () {
return Promise.resolve({ value: undefined, done: true });
},
return: function () {
return Promise.resolve({ value: undefined, done: true });
},
throw: function (e) {
return Promise.reject(e);
}
},
_a[iterall_1.$$asyncIterator] = function () {
return this;
},
_a;
};
//# sourceMappingURL=empty-iterable.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"empty-iterable.js","sourceRoot":"","sources":["../../src/utils/empty-iterable.ts"],"names":[],"mappings":";;;AAAA,mCAA0C;AAI7B,QAAA,mBAAmB,GAAG;;IACjC,OAAO;YACL,IAAI;gBACF,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;YAC3D,CAAC;YACD,MAAM;gBACJ,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;YAC3D,CAAC;YACD,KAAK,EAAL,UAAM,CAAQ;gBACZ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAC3B,CAAC;;QACD,GAAC,yBAAe,IAAhB;YACE,OAAO,IAAI,CAAC;QACd,CAAC;UACK,CAAC;AACX,CAAC,CAAC","sourcesContent":["import { $$asyncIterator } from 'iterall';\n\ntype EmptyIterable = AsyncIterator<any> & { [$$asyncIterator]: any };\n\nexport const createEmptyIterable = (): EmptyIterable => {\n return {\n next() {\n return Promise.resolve({ value: undefined, done: true });\n },\n return() {\n return Promise.resolve({ value: undefined, done: true });\n },\n throw(e: Error) {\n return Promise.reject(e);\n },\n [$$asyncIterator]() {\n return this;\n },\n } as any;\n};\n"]}

View File

@@ -0,0 +1 @@
export default function isObject(value?: any): boolean;

View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isObject(value) {
return ((value !== null) && (typeof value === 'object'));
}
exports.default = isObject;
//# sourceMappingURL=is-object.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"is-object.js","sourceRoot":"","sources":["../../src/utils/is-object.ts"],"names":[],"mappings":";;AAAA,SAAwB,QAAQ,CAAC,KAAW;IAC1C,OAAO,CAAC,CAAC,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC;AAC3D,CAAC;AAFD,2BAEC","sourcesContent":["export default function isObject(value?: any): boolean {\n return ((value !== null) && (typeof value === 'object'));\n}\n"]}

View File

@@ -0,0 +1 @@
export default function isString(value?: any): value is string;

View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isString(value) {
return typeof value === 'string';
}
exports.default = isString;
//# sourceMappingURL=is-string.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"is-string.js","sourceRoot":"","sources":["../../src/utils/is-string.ts"],"names":[],"mappings":";;AAAA,SAAwB,QAAQ,CAAC,KAAW;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC;AACnC,CAAC;AAFD,2BAEC","sourcesContent":["export default function isString(value?: any): value is string {\n return typeof value === 'string';\n}\n"]}

View File

@@ -0,0 +1,2 @@
import { DocumentNode } from 'graphql';
export declare const isASubscriptionOperation: (document: DocumentNode, operationName: string) => boolean;

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isASubscriptionOperation = void 0;
var graphql_1 = require("graphql");
exports.isASubscriptionOperation = function (document, operationName) {
var operationAST = graphql_1.getOperationAST(document, operationName);
return !!operationAST && operationAST.operation === 'subscription';
};
//# sourceMappingURL=is-subscriptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"is-subscriptions.js","sourceRoot":"","sources":["../../src/utils/is-subscriptions.ts"],"names":[],"mappings":";;;AAAA,mCAAwD;AAE3C,QAAA,wBAAwB,GAAG,UAAC,QAAsB,EAAE,aAAqB;IACpF,IAAM,YAAY,GAAG,yBAAe,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;IAE9D,OAAO,CAAC,CAAC,YAAY,IAAI,YAAY,CAAC,SAAS,KAAK,cAAc,CAAC;AACrE,CAAC,CAAC","sourcesContent":["import { DocumentNode, getOperationAST } from 'graphql';\n\nexport const isASubscriptionOperation = (document: DocumentNode, operationName: string): boolean => {\n const operationAST = getOperationAST(document, operationName);\n\n return !!operationAST && operationAST.operation === 'subscription';\n};\n"]}