Socket
Socket
Sign inDemoInstall

pubnub

Package Overview
Dependencies
Maintainers
7
Versions
224
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pubnub - npm Package Compare versions

Comparing version 7.4.5 to 7.5.0

cucumber.js

2

.eslintrc.js

@@ -20,4 +20,6 @@ module.exports = {

'prefer-destructuring': 0,
'no-unused-vars': 0,
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
};

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

## v7.5.0
January 16 2024
#### Added
- Added `enableEventEngine`, `maintainPresenceState` flags and `retryConfiguration` for retry policy configuration.
#### Fixed
- Fixes issue of allowing duplicate listener registration.
- Fixes file name conflict in lib directory. Fixed the following issues reported by [@priyanshu102002](https://github.com/priyanshu102002): [#355](https://github.com/pubnub/javascript/issues/355).
## v7.4.5

@@ -2,0 +12,0 @@ November 28 2023

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

var setup = _a.setup;
var _b, _c, _d;
var _b, _c, _d, _e;
this._PNSDKSuffix = {};

@@ -44,4 +44,4 @@ this.instanceId = "pn-".concat(uuid_1.default.createUUID());

this.useRandomIVs = (_c = setup.useRandomIVs) !== null && _c !== void 0 ? _c : true;
// flag for beta subscribe feature enablement
this.enableSubscribeBeta = (_d = setup.enableSubscribeBeta) !== null && _d !== void 0 ? _d : false;
this.enableEventEngine = (_d = setup.enableEventEngine) !== null && _d !== void 0 ? _d : false;
this.maintainPresenceState = (_e = setup.maintainPresenceState) !== null && _e !== void 0 ? _e : true;
// if location config exist and we are in https, force secure to true.

@@ -58,2 +58,5 @@ if (typeof location !== 'undefined' && location.protocol === 'https:') {

this.requestMessageCountThreshold = setup.requestMessageCountThreshold;
if (setup.retryConfiguration) {
this._setRetryConfiguration(setup.retryConfiguration);
}
// set timeout to how long a transaction request will wait for the server (default 15 seconds)

@@ -183,4 +186,19 @@ this.setTransactionTimeout(setup.transactionalRequestTimeout || 15 * 1000);

default_1.prototype.getVersion = function () {
return '7.4.5';
return '7.5.0';
};
default_1.prototype._setRetryConfiguration = function (configuration) {
if (configuration.minimumdelay < 2) {
throw new Error('Minimum delay can not be set less than 2 seconds for retry');
}
if (configuration.maximumDelay > 150) {
throw new Error('Maximum delay can not be set more than 150 seconds for retry');
}
if (configuration.maximumDelay && maximumRetry > 6) {
throw new Error('Maximum retry for exponential retry policy can not be more than 6');
}
else if (configuration.maximumRetry > 10) {
throw new Error('Maximum retry for linear retry policy can not be more than 10');
}
this.retryConfiguration = configuration;
};
default_1.prototype._addPnsdkSuffix = function (name, suffix) {

@@ -187,0 +205,0 @@ this._PNSDKSuffix[name] = suffix;

7

lib/core/components/listener_manager.js

@@ -11,4 +11,7 @@ "use strict";

}
default_1.prototype.addListener = function (newListeners) {
this._listeners.push(newListeners);
default_1.prototype.addListener = function (newListener) {
if (this._listeners.includes(newListener)) {
return;
}
this._listeners.push(newListener);
};

@@ -15,0 +18,0 @@ default_1.prototype.removeListener = function (deprecatedListener) {

"use strict";
/* */
/* eslint max-classes-per-file: ["error", 5] */
var __extends = (this && this.__extends) || (function () {

@@ -3,0 +5,0 @@ var extendStatics = function (d, b) {

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

PNRequestMessageCountExceededCategory: 'PNRequestMessageCountExceededCategory',
PNDisconnectedCategory: 'PNDisconnectedCategory',
PNConnectionErrorCategory: 'PNConnectionErrorCategory',
PNDisconnectedUnexpectedlyCategory: 'PNDisconnectedUnexpectedlyCategory',
};
"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ function getOperation() {

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

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

function prepareParams(modules, incomingParams) {
var _a = incomingParams.channelGroups, channelGroups = _a === void 0 ? [] : _a, _b = incomingParams.state, state = _b === void 0 ? {} : _b;
var _a = incomingParams.channelGroups, channelGroups = _a === void 0 ? [] : _a, state = incomingParams.state;
var config = modules.config;

@@ -44,3 +44,5 @@ var params = {};

}
params.state = JSON.stringify(state);
if (state) {
params.state = JSON.stringify(state);
}
params.heartbeat = config.getPresenceTimeout();

@@ -47,0 +49,0 @@ return params;

"use strict";
/* */
var __assign = (this && this.__assign) || function () {

@@ -19,2 +18,3 @@ __assign = Object.assign || function(t) {

exports.handleError = exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -21,0 +21,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../../utils"));

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.postPayload = exports.isAuthSupported = exports.getRequestTimeout = exports.postURL = exports.getURL = exports.usePost = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../utils"));

"use strict";
/* */
var __assign = (this && this.__assign) || function () {

@@ -19,2 +18,3 @@ __assign = Object.assign || function(t) {

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../../constants/operations"));

@@ -21,0 +21,0 @@ function getOperation() {

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.handleResponse = exports.prepareParams = exports.isAuthSupported = exports.getRequestTimeout = exports.getURL = exports.validateParams = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../constants/operations"));

@@ -10,0 +10,0 @@ var utils_1 = __importDefault(require("../utils"));

@@ -31,2 +31,9 @@ "use strict";

outParams.tt = 0;
if (params.state) {
outParams.state = JSON.stringify(params.state);
}
if (params.filterExpression && params.filterExpression.length > 0) {
outParams['filter-expr'] = params.filterExpression;
}
outParams.ee = '';
return outParams;

@@ -33,0 +40,0 @@ },

@@ -37,4 +37,8 @@ "use strict";

}
if (params.filterExpression && params.filterExpression.length > 0) {
outParams['filter-expr'] = params.filterExpression;
}
outParams.tt = params.timetoken;
outParams.tr = params.region;
outParams.ee = '';
return outParams;

@@ -41,0 +45,0 @@ },

"use strict";
/* */
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -8,2 +7,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.validateParams = exports.handleResponse = exports.isAuthSupported = exports.prepareParams = exports.getRequestTimeout = exports.getURL = exports.getOperation = void 0;
/* */
var operations_1 = __importDefault(require("../constants/operations"));

@@ -10,0 +10,0 @@ function getOperation() {

@@ -15,3 +15,7 @@ "use strict";

if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {

@@ -33,2 +37,13 @@ if (k2 === undefined) k2 = k;

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {

@@ -131,4 +146,6 @@ var m = typeof Symbol === "function" && o[Symbol.iterator];

var event_engine_1 = require("../event-engine");
var presence_1 = require("../event-engine/presence/presence");
var retryPolicy_1 = require("../event-engine/core/retryPolicy");
var eventEmitter_1 = __importDefault(require("./components/eventEmitter"));
var default_1 = /** @class */ (function () {
//
function default_1(setup) {

@@ -187,6 +204,77 @@ var _this = this;

this.receiveMessages = endpoint_1.default.bind(this, modules, receiveMessages_1.default);
if (config.enableSubscribeBeta === true) {
var eventEngine = new event_engine_1.EventEngine({ handshake: this.handshake, receiveEvents: this.receiveMessages });
if (config.enableEventEngine === true) {
this._eventEmitter = new eventEmitter_1.default({
modules: modules,
listenerManager: this._listenerManager,
getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); },
});
if (config.maintainPresenceState) {
this.presenceState = {};
this.setState = function (args) {
var _a, _b;
(_a = args.channels) === null || _a === void 0 ? void 0 : _a.forEach(function (channel) { return (_this.presenceState[channel] = args.state); });
(_b = args.channelGroups) === null || _b === void 0 ? void 0 : _b.forEach(function (group) { return (_this.presenceState[group] = args.state); });
return _this.setPresenceState({
channels: args.channels,
channelGroups: args.channelGroups,
state: _this.presenceState,
});
};
}
if (config.getHeartbeatInterval()) {
var presenceEventEngine = new presence_1.PresenceEventEngine({
heartbeat: this.iAmHere,
leave: this.iAmAway,
heartbeatDelay: function () {
return new Promise(function (resolve) { return setTimeout(resolve, modules.config.getHeartbeatInterval() * 1000); });
},
retryDelay: function (amount) { return new Promise(function (resolve) { return setTimeout(resolve, amount); }); },
config: modules.config,
presenceState: this.presenceState,
emitStatus: function (status) {
listenerManager.announceStatus(status);
},
});
this.presenceEventEngine = presenceEventEngine;
this.join = this.presenceEventEngine.join.bind(presenceEventEngine);
this.leave = this.presenceEventEngine.leave.bind(presenceEventEngine);
this.leaveAll = this.presenceEventEngine.leaveAll.bind(presenceEventEngine);
}
var eventEngine = new event_engine_1.EventEngine({
handshake: this.handshake,
receiveMessages: this.receiveMessages,
delay: function (amount) { return new Promise(function (resolve) { return setTimeout(resolve, amount); }); },
join: this.join,
leave: this.leave,
leaveAll: this.leaveAll,
presenceState: this.presenceState,
config: modules.config,
emitMessages: function (events) {
var e_1, _a;
try {
for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) {
var event_1 = events_1_1.value;
_this._eventEmitter.emitEvent(event_1);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1);
}
finally { if (e_1) throw e_1.error; }
}
},
emitStatus: function (status) {
listenerManager.announceStatus(status);
},
});
this.subscribe = eventEngine.subscribe.bind(eventEngine);
this.unsubscribe = eventEngine.unsubscribe.bind(eventEngine);
this.unsubscribeAll = eventEngine.unsubscribeAll.bind(eventEngine);
this.reconnect = eventEngine.reconnect.bind(eventEngine);
this.disconnect = eventEngine.disconnect.bind(eventEngine);
this.destroy = eventEngine.dispose.bind(eventEngine);
this.getSubscribedChannels = eventEngine.getSubscribedChannels.bind(eventEngine);
this.getSubscribedChannelGroups = eventEngine.getSubscribedChannelGroups.bind(eventEngine);
this.eventEngine = eventEngine;

@@ -528,3 +616,2 @@ }

this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config);
// this.setCipherKey = modules.config.setCipherKey.bind(modules.config);
this.setCipherKey = function (key) { return modules.config.setCipherKey(key, setup, modules); };

@@ -567,4 +654,6 @@ this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config);

default_1.CATEGORIES = categories_1.default;
default_1.LinearRetryPolicy = retryPolicy_1.RetryPolicy.LinearRetryPolicy;
default_1.ExponentialRetryPolicy = retryPolicy_1.RetryPolicy.ExponentialRetryPolicy;
return default_1;
}());
exports.default = default_1;
"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -33,4 +60,21 @@ exports.Dispatcher = void 0;

};
Dispatcher.prototype.dispose = function () {
var e_1, _a;
try {
for (var _b = __values(this.instances.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], instance = _d[1];
instance.cancel();
this.instances.delete(key);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
return Dispatcher;
}());
exports.Dispatcher = Dispatcher;

@@ -37,3 +37,6 @@ "use strict";

AsyncHandler.prototype.start = function () {
this.asyncFunction(this.payload, this.abortSignal, this.dependencies);
this.asyncFunction(this.payload, this.abortSignal, this.dependencies).catch(function (error) {
// console.log('Unhandled error:', error);
// swallow the error
});
};

@@ -40,0 +43,0 @@ AsyncHandler.prototype.cancel = function () {

@@ -17,5 +17,20 @@ "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 __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]; } });
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {

@@ -84,3 +99,3 @@ if (k2 === undefined) k2 = k;

_this.on(effects.handshake.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var handshake = _a.handshake;
var handshake = _a.handshake, presenceState = _a.presenceState, config = _a.config;
return __awaiter(_this, void 0, void 0, function () {

@@ -95,11 +110,6 @@ var result, e_1;

_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, handshake({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
})];
return [4 /*yield*/, handshake(__assign({ abortSignal: abortSignal, channels: payload.channels, channelGroups: payload.groups, filterExpression: config.filterExpression }, (config.maintainPresenceState && { state: presenceState })))];
case 2:
result = _b.sent();
engine.transition(events.handshakingSuccess(result));
return [3 /*break*/, 4];
return [2 /*return*/, engine.transition(events.handshakeSuccess(result))];
case 3:

@@ -111,3 +121,3 @@ e_1 = _b.sent();

if (e_1 instanceof endpoint_1.PubNubError) {
return [2 /*return*/, engine.transition(events.handshakingFailure(e_1))];
return [2 /*return*/, engine.transition(events.handshakeFailure(e_1))];
}

@@ -120,4 +130,4 @@ return [3 /*break*/, 4];

}));
_this.on(effects.receiveEvents.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var receiveEvents = _a.receiveEvents;
_this.on(effects.receiveMessages.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var receiveMessages = _a.receiveMessages, config = _a.config;
return __awaiter(_this, void 0, void 0, function () {

@@ -132,3 +142,3 @@ var result, error_1;

_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, receiveEvents({
return [4 /*yield*/, receiveMessages({
abortSignal: abortSignal,

@@ -139,6 +149,7 @@ channels: payload.channels,

region: payload.cursor.region,
filterExpression: config.filterExpression,
})];
case 2:
result = _b.sent();
engine.transition(events.receivingSuccess(result.metadata, result.messages));
engine.transition(events.receiveSuccess(result.metadata, result.messages));
return [3 /*break*/, 4];

@@ -150,4 +161,4 @@ case 3:

}
if (error_1 instanceof endpoint_1.PubNubError) {
return [2 /*return*/, engine.transition(events.receivingFailure(error_1))];
if (error_1 instanceof endpoint_1.PubNubError && !abortSignal.aborted) {
return [2 /*return*/, engine.transition(events.receiveFailure(error_1))];
}

@@ -160,8 +171,8 @@ return [3 /*break*/, 4];

}));
_this.on(effects.emitEvents.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var receiveEvents = _a.receiveEvents;
_this.on(effects.emitMessages.type, (0, core_1.asyncHandler)(function (payload, _, _a) {
var emitMessages = _a.emitMessages;
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_b) {
if (payload.length > 0) {
console.log(payload);
emitMessages(payload);
}

@@ -172,5 +183,14 @@ return [2 /*return*/];

}));
_this.on(effects.reconnect.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var receiveEvents = _a.receiveEvents, shouldRetry = _a.shouldRetry, getRetryDelay = _a.getRetryDelay, delay = _a.delay;
_this.on(effects.emitStatus.type, (0, core_1.asyncHandler)(function (payload, _, _a) {
var emitStatus = _a.emitStatus;
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_b) {
emitStatus(payload);
return [2 /*return*/];
});
});
}));
_this.on(effects.receiveReconnect.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var receiveMessages = _a.receiveMessages, delay = _a.delay, config = _a.config;
return __awaiter(_this, void 0, void 0, function () {
var result, error_2;

@@ -180,7 +200,5 @@ return __generator(this, function (_b) {

case 0:
if (!shouldRetry(payload.reason, payload.attempts)) {
return [2 /*return*/, engine.transition(events.reconnectingGiveup())];
}
if (!(config.retryConfiguration && config.retryConfiguration.shouldRetry(payload.reason, payload.attempts))) return [3 /*break*/, 6];
abortSignal.throwIfAborted();
return [4 /*yield*/, delay(getRetryDelay(payload.attempts))];
return [4 /*yield*/, delay(config.retryConfiguration.getDelay(payload.attempts, payload.reason))];
case 1:

@@ -192,3 +210,3 @@ _b.sent();

_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, receiveEvents({
return [4 /*yield*/, receiveMessages({
abortSignal: abortSignal,

@@ -199,6 +217,7 @@ channels: payload.channels,

region: payload.cursor.region,
filterExpression: config.filterExpression,
})];
case 3:
result = _b.sent();
return [2 /*return*/, engine.transition(events.reconnectingSuccess(result.metadata, result.messages))];
return [2 /*return*/, engine.transition(events.receiveReconnectSuccess(result.metadata, result.messages))];
case 4:

@@ -210,6 +229,8 @@ error_2 = _b.sent();

if (error_2 instanceof endpoint_1.PubNubError) {
return [2 /*return*/, engine.transition(events.reconnectingFailure(error_2))];
return [2 /*return*/, engine.transition(events.receiveReconnectFailure(error_2))];
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
case 5: return [3 /*break*/, 7];
case 6: return [2 /*return*/, engine.transition(events.receiveReconnectGiveup(new endpoint_1.PubNubError(config.retryConfiguration.getGiveupReason(payload.reason, payload.attempts))))];
case 7: return [2 /*return*/];
}

@@ -220,3 +241,3 @@ });

_this.on(effects.handshakeReconnect.type, (0, core_1.asyncHandler)(function (payload, abortSignal, _a) {
var handshake = _a.handshake, shouldRetry = _a.shouldRetry, getRetryDelay = _a.getRetryDelay, delay = _a.delay;
var handshake = _a.handshake, delay = _a.delay, presenceState = _a.presenceState, config = _a.config;
return __awaiter(_this, void 0, void 0, function () {

@@ -227,7 +248,5 @@ var result, error_3;

case 0:
if (!shouldRetry(payload.reason, payload.attempts)) {
return [2 /*return*/, engine.transition(events.handshakingReconnectingGiveup())];
}
if (!(config.retryConfiguration && config.retryConfiguration.shouldRetry(payload.reason, payload.attempts))) return [3 /*break*/, 6];
abortSignal.throwIfAborted();
return [4 /*yield*/, delay(getRetryDelay(payload.attempts))];
return [4 /*yield*/, delay(config.retryConfiguration.getDelay(payload.attempts, payload.reason))];
case 1:

@@ -239,10 +258,6 @@ _b.sent();

_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, handshake({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
})];
return [4 /*yield*/, handshake(__assign({ abortSignal: abortSignal, channels: payload.channels, channelGroups: payload.groups, filterExpression: config.filterExpression }, (config.maintainPresenceState && { state: presenceState })))];
case 3:
result = _b.sent();
return [2 /*return*/, engine.transition(events.handshakingReconnectingSuccess(result.metadata))];
return [2 /*return*/, engine.transition(events.handshakeReconnectSuccess(result))];
case 4:

@@ -254,6 +269,8 @@ error_3 = _b.sent();

if (error_3 instanceof endpoint_1.PubNubError) {
return [2 /*return*/, engine.transition(events.handshakingReconnectingFailure(error_3))];
return [2 /*return*/, engine.transition(events.handshakeReconnectFailure(error_3))];
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
case 5: return [3 /*break*/, 7];
case 6: return [2 /*return*/, engine.transition(events.handshakeReconnectGiveup(new endpoint_1.PubNubError(config.retryConfiguration.getGiveupReason(payload.reason, payload.attempts))))];
case 7: return [2 /*return*/];
}

@@ -260,0 +277,0 @@ });

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handshakeReconnect = exports.reconnect = exports.emitEvents = exports.receiveEvents = exports.handshake = void 0;
exports.handshakeReconnect = exports.receiveReconnect = exports.emitStatus = exports.emitMessages = exports.receiveMessages = exports.handshake = void 0;
var core_1 = require("./core");

@@ -9,5 +9,6 @@ exports.handshake = (0, core_1.createManagedEffect)('HANDSHAKE', function (channels, groups) { return ({

}); });
exports.receiveEvents = (0, core_1.createManagedEffect)('RECEIVE_EVENTS', function (channels, groups, cursor) { return ({ channels: channels, groups: groups, cursor: cursor }); });
exports.emitEvents = (0, core_1.createEffect)('EMIT_EVENTS', function (events) { return events; });
exports.reconnect = (0, core_1.createManagedEffect)('RECONNECT', function (context) { return context; });
exports.receiveMessages = (0, core_1.createManagedEffect)('RECEIVE_MESSAGES', function (channels, groups, cursor) { return ({ channels: channels, groups: groups, cursor: cursor }); });
exports.emitMessages = (0, core_1.createEffect)('EMIT_MESSAGES', function (events) { return events; });
exports.emitStatus = (0, core_1.createEffect)('EMIT_STATUS', function (status) { return status; });
exports.receiveReconnect = (0, core_1.createManagedEffect)('RECEIVE_RECONNECT', function (context) { return context; });
exports.handshakeReconnect = (0, core_1.createManagedEffect)('HANDSHAKE_RECONNECT', function (context) { return context; });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reconnectingRetry = exports.reconnectingGiveup = exports.reconnectingFailure = exports.reconnectingSuccess = exports.receivingFailure = exports.receivingSuccess = exports.handshakingReconnectingRetry = exports.handshakingReconnectingGiveup = exports.handshakingReconnectingFailure = exports.handshakingReconnectingSuccess = exports.handshakingFailure = exports.handshakingSuccess = exports.restore = exports.reconnect = exports.disconnect = exports.subscriptionChange = void 0;
exports.unsubscribeAll = exports.reconnect = exports.disconnect = exports.receiveReconnectGiveup = exports.receiveReconnectFailure = exports.receiveReconnectSuccess = exports.receiveFailure = exports.receiveSuccess = exports.handshakeReconnectGiveup = exports.handshakeReconnectFailure = exports.handshakeReconnectSuccess = exports.handshakeFailure = exports.handshakeSuccess = exports.restore = exports.subscriptionChange = void 0;
var core_1 = require("./core");
exports.subscriptionChange = (0, core_1.createEvent)('SUBSCRIPTION_CHANGE', function (channels, groups) { return ({
exports.subscriptionChange = (0, core_1.createEvent)('SUBSCRIPTION_CHANGED', function (channels, groups) { return ({
channels: channels,
groups: groups,
}); });
exports.disconnect = (0, core_1.createEvent)('DISCONNECT', function () { return ({}); });
exports.reconnect = (0, core_1.createEvent)('RECONNECT', function () { return ({}); });
exports.restore = (0, core_1.createEvent)('RESTORE', function (channels, groups, timetoken, region) { return ({
exports.restore = (0, core_1.createEvent)('SUBSCRIPTION_RESTORED', function (channels, groups, timetoken, region) { return ({
channels: channels,
groups: groups,
timetoken: timetoken,
region: region,
cursor: {
timetoken: timetoken,
region: region !== null && region !== void 0 ? region : 0,
},
}); });
exports.handshakingSuccess = (0, core_1.createEvent)('HANDSHAKING_SUCCESS', function (cursor) { return cursor; });
exports.handshakingFailure = (0, core_1.createEvent)('HANDSHAKING_FAILURE', function (error) { return error; });
exports.handshakingReconnectingSuccess = (0, core_1.createEvent)('HANDSHAKING_RECONNECTING_SUCCESS', function (cursor) { return ({
exports.handshakeSuccess = (0, core_1.createEvent)('HANDSHAKE_SUCCESS', function (cursor) { return cursor; });
exports.handshakeFailure = (0, core_1.createEvent)('HANDSHAKE_FAILURE', function (error) { return error; });
exports.handshakeReconnectSuccess = (0, core_1.createEvent)('HANDSHAKE_RECONNECT_SUCCESS', function (cursor) { return ({
cursor: cursor,
}); });
exports.handshakingReconnectingFailure = (0, core_1.createEvent)('HANDSHAKING_RECONNECTING_FAILURE', function (error) { return error; });
exports.handshakingReconnectingGiveup = (0, core_1.createEvent)('HANDSHAKING_RECONNECTING_GIVEUP', function () { return ({}); });
exports.handshakingReconnectingRetry = (0, core_1.createEvent)('HANDSHAKING_RECONNECTING_RETRY', function () { return ({}); });
exports.receivingSuccess = (0, core_1.createEvent)('RECEIVING_SUCCESS', function (cursor, events) { return ({
exports.handshakeReconnectFailure = (0, core_1.createEvent)('HANDSHAKE_RECONNECT_FAILURE', function (error) { return error; });
exports.handshakeReconnectGiveup = (0, core_1.createEvent)('HANDSHAKE_RECONNECT_GIVEUP', function (error) { return error; });
exports.receiveSuccess = (0, core_1.createEvent)('RECEIVE_SUCCESS', function (cursor, events) { return ({
cursor: cursor,
events: events,
}); });
exports.receivingFailure = (0, core_1.createEvent)('RECEIVING_FAILURE', function (error) { return error; });
exports.reconnectingSuccess = (0, core_1.createEvent)('RECONNECTING_SUCCESS', function (cursor, events) { return ({
exports.receiveFailure = (0, core_1.createEvent)('RECEIVE_FAILURE', function (error) { return error; });
exports.receiveReconnectSuccess = (0, core_1.createEvent)('RECEIVE_RECONNECT_SUCCESS', function (cursor, events) { return ({
cursor: cursor,
events: events,
}); });
exports.reconnectingFailure = (0, core_1.createEvent)('RECONNECTING_FAILURE', function (error) { return error; });
exports.reconnectingGiveup = (0, core_1.createEvent)('RECONNECTING_GIVEUP', function () { return ({}); });
exports.reconnectingRetry = (0, core_1.createEvent)('RECONNECTING_RETRY', function () { return ({}); });
exports.receiveReconnectFailure = (0, core_1.createEvent)('RECEIVE_RECONNECT_FAILURE', function (error) { return error; });
exports.receiveReconnectGiveup = (0, core_1.createEvent)('RECEIVING_RECONNECT_GIVEUP', function (error) { return error; });
exports.disconnect = (0, core_1.createEvent)('DISCONNECT', function () { return ({}); });
exports.reconnect = (0, core_1.createEvent)('RECONNECT', function (timetoken, region) { return ({
cursor: {
timetoken: timetoken !== null && timetoken !== void 0 ? timetoken : '',
region: region !== null && region !== void 0 ? region : 0,
},
}); });
exports.unsubscribeAll = (0, core_1.createEvent)('UNSUBSCRIBE_ALL', function () { return ({}); });
"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]; } });
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {

@@ -58,4 +62,5 @@ if (k2 === undefined) k2 = k;

this.groups = [];
this.dependencies = dependencies;
this.dispatcher = new dispatcher_1.EventEngineDispatcher(this.engine, dependencies);
this.engine.subscribe(function (change) {
this._unsubscribeEngine = this.engine.subscribe(function (change) {
if (change.type === 'invocationDispatched') {

@@ -75,12 +80,43 @@ _this.dispatcher.dispatch(change.invocation);

EventEngine.prototype.subscribe = function (_a) {
var channels = _a.channels, groups = _a.groups;
var _this = this;
var channels = _a.channels, channelGroups = _a.channelGroups, timetoken = _a.timetoken, withPresence = _a.withPresence;
this.channels = __spreadArray(__spreadArray([], __read(this.channels), false), __read((channels !== null && channels !== void 0 ? channels : [])), false);
this.groups = __spreadArray(__spreadArray([], __read(this.groups), false), __read((groups !== null && groups !== void 0 ? groups : [])), false);
this.engine.transition(events.subscriptionChange(this.channels, this.groups));
this.groups = __spreadArray(__spreadArray([], __read(this.groups), false), __read((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false);
if (withPresence) {
this.channels.map(function (c) { return _this.channels.push("".concat(c, "-pnpres")); });
this.groups.map(function (g) { return _this.groups.push("".concat(g, "-pnpres")); });
}
if (timetoken) {
this.engine.transition(events.restore(this.channels, this.groups, timetoken));
}
else {
this.engine.transition(events.subscriptionChange(this.channels, this.groups));
}
if (this.dependencies.join) {
this.dependencies.join({
channels: this.channels.filter(function (c) { return !c.endsWith('-pnpres'); }),
groups: this.groups.filter(function (g) { return !g.endsWith('-pnpres'); }),
});
}
};
EventEngine.prototype.unsubscribe = function (_a) {
var _this = this;
var channels = _a.channels, groups = _a.groups;
this.channels = this.channels.filter(function (channel) { var _a; return (_a = !(channels === null || channels === void 0 ? void 0 : channels.includes(channel))) !== null && _a !== void 0 ? _a : true; });
this.groups = this.groups.filter(function (group) { var _a; return (_a = !(groups === null || groups === void 0 ? void 0 : groups.includes(group))) !== null && _a !== void 0 ? _a : true; });
var channlesWithPres = channels === null || channels === void 0 ? void 0 : channels.slice(0);
channels === null || channels === void 0 ? void 0 : channels.map(function (c) { return channlesWithPres.push("".concat(c, "-pnpres")); });
this.channels = this.channels.filter(function (channel) { return !(channlesWithPres === null || channlesWithPres === void 0 ? void 0 : channlesWithPres.includes(channel)); });
var groupsWithPres = groups === null || groups === void 0 ? void 0 : groups.slice(0);
groups === null || groups === void 0 ? void 0 : groups.map(function (g) { return groupsWithPres.push("".concat(g, "-pnpres")); });
this.groups = this.groups.filter(function (group) { return !(groupsWithPres === null || groupsWithPres === void 0 ? void 0 : groupsWithPres.includes(group)); });
if (this.dependencies.presenceState) {
channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { return delete _this.dependencies.presenceState[c]; });
groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { return delete _this.dependencies.presenceState[g]; });
}
this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0)));
if (this.dependencies.leave) {
this.dependencies.leave({
channels: channels,
groups: groups,
});
}
};

@@ -90,12 +126,33 @@ EventEngine.prototype.unsubscribeAll = function () {

this.groups = [];
if (this.dependencies.presenceState) {
this.dependencies.presenceState = {};
}
this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0)));
if (this.dependencies.leaveAll) {
this.dependencies.leaveAll();
}
};
EventEngine.prototype.reconnect = function () {
this.engine.transition(events.reconnect());
EventEngine.prototype.reconnect = function (_a) {
var timetoken = _a.timetoken, region = _a.region;
this.engine.transition(events.reconnect(timetoken, region));
};
EventEngine.prototype.disconnect = function () {
this.engine.transition(events.disconnect());
if (this.dependencies.leaveAll) {
this.dependencies.leaveAll();
}
};
EventEngine.prototype.getSubscribedChannels = function () {
return this.channels.slice(0);
};
EventEngine.prototype.getSubscribedChannelGroups = function () {
return this.groups.slice(0);
};
EventEngine.prototype.dispose = function () {
this.disconnect();
this._unsubscribeEngine();
this.dispatcher.dispose();
};
return EventEngine;
}());
exports.EventEngine = EventEngine;

@@ -17,8 +17,5 @@ "use strict";

var events_1 = require("../events");
var handshake_reconnecting_1 = require("./handshake_reconnecting");
var handshake_stopped_1 = require("./handshake_stopped");
var handshaking_1 = require("./handshaking");
exports.HandshakeFailureState = new state_1.State('HANDSHAKE_FAILURE');
exports.HandshakeFailureState.on(events_1.handshakingReconnectingRetry.type, function (context) {
return handshake_reconnecting_1.HandshakeReconnectingState.with(__assign(__assign({}, context), { attempts: 0 }));
});
exports.HandshakeFailureState.on(events_1.disconnect.type, function (context) {

@@ -30,1 +27,2 @@ return handshake_stopped_1.HandshakeStoppedState.with({

});
exports.HandshakeFailureState.on(events_1.reconnect.type, function (context) { return handshaking_1.HandshakingState.with(__assign({}, context)); });

@@ -13,2 +13,5 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -19,24 +22,34 @@ exports.HandshakeReconnectingState = void 0;

var events_1 = require("../events");
var handshake_failure_1 = require("./handshake_failure");
var handshake_failed_1 = require("./handshake_failed");
var handshake_stopped_1 = require("./handshake_stopped");
var handshaking_1 = require("./handshaking");
var receiving_1 = require("./receiving");
var unsubscribed_1 = require("./unsubscribed");
var categories_1 = __importDefault(require("../../core/constants/categories"));
exports.HandshakeReconnectingState = new state_1.State('HANDSHAKE_RECONNECTING');
exports.HandshakeReconnectingState.onEnter(function (context) { return (0, effects_1.handshakeReconnect)(context); });
exports.HandshakeReconnectingState.onExit(function () { return effects_1.reconnect.cancel; });
exports.HandshakeReconnectingState.on(events_1.reconnectingSuccess.type, function (context, event) {
exports.HandshakeReconnectingState.onExit(function () { return effects_1.handshakeReconnect.cancel; });
exports.HandshakeReconnectingState.on(events_1.handshakeReconnectSuccess.type, function (context, event) {
var _a, _b;
var cursor = {
timetoken: !!((_a = context.cursor) === null || _a === void 0 ? void 0 : _a.timetoken) ? (_b = context.cursor) === null || _b === void 0 ? void 0 : _b.timetoken : event.payload.cursor.timetoken,
region: event.payload.cursor.region,
};
return receiving_1.ReceivingState.with({
channels: context.channels,
groups: context.groups,
cursor: event.payload.cursor,
}, [(0, effects_1.emitEvents)(event.payload.events)]);
cursor: cursor,
}, [(0, effects_1.emitStatus)({ category: categories_1.default.PNConnectedCategory })]);
});
exports.HandshakeReconnectingState.on(events_1.reconnectingFailure.type, function (context, event) {
exports.HandshakeReconnectingState.on(events_1.handshakeReconnectFailure.type, function (context, event) {
return exports.HandshakeReconnectingState.with(__assign(__assign({}, context), { attempts: context.attempts + 1, reason: event.payload }));
});
exports.HandshakeReconnectingState.on(events_1.reconnectingGiveup.type, function (context) {
return handshake_failure_1.HandshakeFailureState.with({
exports.HandshakeReconnectingState.on(events_1.handshakeReconnectGiveup.type, function (context, event) {
var _a;
return handshake_failed_1.HandshakeFailedState.with({
groups: context.groups,
channels: context.channels,
reason: context.reason,
});
cursor: context.cursor,
reason: event.payload,
}, [(0, effects_1.emitStatus)({ category: categories_1.default.PNConnectionErrorCategory, error: (_a = event.payload) === null || _a === void 0 ? void 0 : _a.message })]);
});

@@ -47,3 +60,23 @@ exports.HandshakeReconnectingState.on(events_1.disconnect.type, function (context) {

groups: context.groups,
cursor: context.cursor,
});
});
exports.HandshakeReconnectingState.on(events_1.subscriptionChange.type, function (context, event) {
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
});
});
exports.HandshakeReconnectingState.on(events_1.restore.type, function (context, event) {
var _a, _b;
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: ((_a = event.payload.cursor) === null || _a === void 0 ? void 0 : _a.region) || ((_b = context === null || context === void 0 ? void 0 : context.cursor) === null || _b === void 0 ? void 0 : _b.region) || 0,
},
});
});
exports.HandshakeReconnectingState.on(events_1.unsubscribeAll.type, function (_) { return unsubscribed_1.UnsubscribedState.with(undefined); });

@@ -18,9 +18,25 @@ "use strict";

var handshaking_1 = require("./handshaking");
exports.HandshakeStoppedState = new state_1.State('STOPPED');
exports.HandshakeStoppedState.on(events_1.subscriptionChange.type, function (_context, event) {
var unsubscribed_1 = require("./unsubscribed");
exports.HandshakeStoppedState = new state_1.State('HANDSHAKE_STOPPED');
exports.HandshakeStoppedState.on(events_1.subscriptionChange.type, function (context, event) {
return exports.HandshakeStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
});
});
exports.HandshakeStoppedState.on(events_1.reconnect.type, function (context) { return handshaking_1.HandshakingState.with(__assign({}, context)); });
exports.HandshakeStoppedState.on(events_1.reconnect.type, function (context, event) {
return handshaking_1.HandshakingState.with(__assign(__assign({}, context), { cursor: event.payload.cursor || context.cursor }));
});
exports.HandshakeStoppedState.on(events_1.restore.type, function (context, event) {
var _a;
return exports.HandshakeStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || ((_a = context === null || context === void 0 ? void 0 : context.cursor) === null || _a === void 0 ? void 0 : _a.region) || 0,
},
});
});
exports.HandshakeStoppedState.on(events_1.unsubscribeAll.type, function (_) { return unsubscribed_1.UnsubscribedState.with(); });
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};

@@ -22,2 +14,3 @@ Object.defineProperty(exports, "__esModule", { value: true });

var unsubscribed_1 = require("./unsubscribed");
var categories_1 = __importDefault(require("../../core/constants/categories"));
exports.HandshakingState = new state_1.State('HANDSHAKING');

@@ -30,14 +23,32 @@ exports.HandshakingState.onEnter(function (context) { return (0, effects_1.handshake)(context.channels, context.groups); });

}
return exports.HandshakingState.with({ channels: event.payload.channels, groups: event.payload.groups });
return exports.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
});
});
exports.HandshakingState.on(events_1.handshakingSuccess.type, function (context, event) {
exports.HandshakingState.on(events_1.handshakeSuccess.type, function (context, event) {
var _a, _b;
return receiving_1.ReceivingState.with({
channels: context.channels,
groups: context.groups,
cursor: event.payload,
cursor: {
timetoken: !!((_a = context === null || context === void 0 ? void 0 : context.cursor) === null || _a === void 0 ? void 0 : _a.timetoken) ? (_b = context === null || context === void 0 ? void 0 : context.cursor) === null || _b === void 0 ? void 0 : _b.timetoken : event.payload.timetoken,
region: event.payload.region,
},
}, [
(0, effects_1.emitStatus)({
category: categories_1.default.PNConnectedCategory,
}),
]);
});
exports.HandshakingState.on(events_1.handshakeFailure.type, function (context, event) {
return handshake_reconnecting_1.HandshakeReconnectingState.with({
channels: context.channels,
groups: context.groups,
cursor: context.cursor,
attempts: 0,
reason: event.payload,
});
});
exports.HandshakingState.on(events_1.handshakingFailure.type, function (context, event) {
return handshake_reconnecting_1.HandshakeReconnectingState.with(__assign(__assign({}, context), { attempts: 0, reason: event.payload }));
});
exports.HandshakingState.on(events_1.disconnect.type, function (context) {

@@ -47,3 +58,16 @@ return handshake_stopped_1.HandshakeStoppedState.with({

groups: context.groups,
cursor: context.cursor,
});
});
exports.HandshakingState.on(events_1.restore.type, function (context, event) {
var _a;
return exports.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || ((_a = context === null || context === void 0 ? void 0 : context.cursor) === null || _a === void 0 ? void 0 : _a.region) || 0,
},
});
});
exports.HandshakingState.on(events_1.unsubscribeAll.type, function (_) { return unsubscribed_1.UnsubscribedState.with(); });
"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 });

@@ -17,7 +6,12 @@ exports.ReceiveFailureState = void 0;

var events_1 = require("../events");
var receive_reconnecting_1 = require("./receive_reconnecting");
var handshaking_1 = require("./handshaking");
var receive_stopped_1 = require("./receive_stopped");
exports.ReceiveFailureState = new state_1.State('RECEIVE_FAILURE');
var unsubscribed_1 = require("./unsubscribed");
exports.ReceiveFailureState = new state_1.State('RECEIVE_FAILED');
exports.ReceiveFailureState.on(events_1.reconnectingRetry.type, function (context) {
return receive_reconnecting_1.ReceiveReconnectingState.with(__assign(__assign({}, context), { attempts: 0 }));
return handshaking_1.HandshakingState.with({
channels: context.channels,
groups: context.groups,
timetoken: context.cursor.timetoken,
});
});

@@ -31,1 +25,16 @@ exports.ReceiveFailureState.on(events_1.disconnect.type, function (context) {

});
exports.ReceiveFailureState.on(events_1.subscriptionChange.type, function (_, event) {
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
timetoken: event.payload.timetoken,
});
});
exports.ReceiveFailureState.on(events_1.restore.type, function (_, event) {
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
timetoken: event.payload.timetoken,
});
});
exports.ReceiveFailureState.on(events_1.unsubscribeAll.type, function (_) { return unsubscribed_1.UnsubscribedState.with(undefined); });

@@ -13,2 +13,5 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -20,8 +23,10 @@ exports.ReceiveReconnectingState = void 0;

var receiving_1 = require("./receiving");
var receive_failure_1 = require("./receive_failure");
var receive_failed_1 = require("./receive_failed");
var receive_stopped_1 = require("./receive_stopped");
var unsubscribed_1 = require("./unsubscribed");
var categories_1 = __importDefault(require("../../core/constants/categories"));
exports.ReceiveReconnectingState = new state_1.State('RECEIVE_RECONNECTING');
exports.ReceiveReconnectingState.onEnter(function (context) { return (0, effects_1.reconnect)(context); });
exports.ReceiveReconnectingState.onExit(function () { return effects_1.reconnect.cancel; });
exports.ReceiveReconnectingState.on(events_1.reconnectingSuccess.type, function (context, event) {
exports.ReceiveReconnectingState.onEnter(function (context) { return (0, effects_1.receiveReconnect)(context); });
exports.ReceiveReconnectingState.onExit(function () { return effects_1.receiveReconnect.cancel; });
exports.ReceiveReconnectingState.on(events_1.receiveReconnectSuccess.type, function (context, event) {
return receiving_1.ReceivingState.with({

@@ -31,14 +36,15 @@ channels: context.channels,

cursor: event.payload.cursor,
}, [(0, effects_1.emitEvents)(event.payload.events)]);
}, [(0, effects_1.emitMessages)(event.payload.events)]);
});
exports.ReceiveReconnectingState.on(events_1.reconnectingFailure.type, function (context, event) {
exports.ReceiveReconnectingState.on(events_1.receiveReconnectFailure.type, function (context, event) {
return exports.ReceiveReconnectingState.with(__assign(__assign({}, context), { attempts: context.attempts + 1, reason: event.payload }));
});
exports.ReceiveReconnectingState.on(events_1.reconnectingGiveup.type, function (context) {
return receive_failure_1.ReceiveFailureState.with({
exports.ReceiveReconnectingState.on(events_1.receiveReconnectGiveup.type, function (context, event) {
var _a;
return receive_failed_1.ReceiveFailedState.with({
groups: context.groups,
channels: context.channels,
cursor: context.cursor,
reason: context.reason,
});
reason: event.payload,
}, [(0, effects_1.emitStatus)({ category: categories_1.default.PNDisconnectedUnexpectedlyCategory, error: (_a = event.payload) === null || _a === void 0 ? void 0 : _a.message })]);
});

@@ -50,3 +56,23 @@ exports.ReceiveReconnectingState.on(events_1.disconnect.type, function (context) {

cursor: context.cursor,
}, [(0, effects_1.emitStatus)({ category: categories_1.default.PNDisconnectedCategory })]);
});
exports.ReceiveReconnectingState.on(events_1.restore.type, function (context, event) {
return receiving_1.ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
});
});
exports.ReceiveReconnectingState.on(events_1.subscriptionChange.type, function (context, event) {
return receiving_1.ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
});
});
exports.ReceiveReconnectingState.on(events_1.unsubscribeAll.type, function (_) {
return unsubscribed_1.UnsubscribedState.with(undefined, [(0, effects_1.emitStatus)({ category: categories_1.default.PNDisconnectedCategory })]);
});
"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 });

@@ -17,4 +6,5 @@ exports.ReceiveStoppedState = void 0;

var events_1 = require("../events");
var receiving_1 = require("./receiving");
exports.ReceiveStoppedState = new state_1.State('STOPPED');
var handshaking_1 = require("./handshaking");
var unsubscribed_1 = require("./unsubscribed");
exports.ReceiveStoppedState = new state_1.State('RECEIVE_STOPPED');
exports.ReceiveStoppedState.on(events_1.subscriptionChange.type, function (context, event) {

@@ -27,2 +17,23 @@ return exports.ReceiveStoppedState.with({

});
exports.ReceiveStoppedState.on(events_1.reconnect.type, function (context) { return receiving_1.ReceivingState.with(__assign({}, context)); });
exports.ReceiveStoppedState.on(events_1.restore.type, function (context, event) {
return exports.ReceiveStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
});
});
exports.ReceiveStoppedState.on(events_1.reconnect.type, function (context, event) {
var _a;
return handshaking_1.HandshakingState.with({
channels: context.channels,
groups: context.groups,
cursor: {
timetoken: !!event.payload.cursor.timetoken ? (_a = event.payload.cursor) === null || _a === void 0 ? void 0 : _a.timetoken : context.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
});
});
exports.ReceiveStoppedState.on(events_1.unsubscribeAll.type, function () { return unsubscribed_1.UnsubscribedState.with(undefined); });

@@ -13,2 +13,5 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -22,7 +25,10 @@ exports.ReceivingState = void 0;

var receive_stopped_1 = require("./receive_stopped");
var categories_1 = __importDefault(require("../../core/constants/categories"));
exports.ReceivingState = new state_1.State('RECEIVING');
exports.ReceivingState.onEnter(function (context) { return (0, effects_1.receiveEvents)(context.channels, context.groups, context.cursor); });
exports.ReceivingState.onExit(function () { return effects_1.receiveEvents.cancel; });
exports.ReceivingState.on(events_1.receivingSuccess.type, function (context, event) {
return exports.ReceivingState.with(__assign(__assign({}, context), { cursor: event.payload.cursor }), [(0, effects_1.emitEvents)(event.payload.events)]);
exports.ReceivingState.onEnter(function (context) { return (0, effects_1.receiveMessages)(context.channels, context.groups, context.cursor); });
exports.ReceivingState.onExit(function () { return effects_1.receiveMessages.cancel; });
exports.ReceivingState.on(events_1.receiveSuccess.type, function (context, event) {
return exports.ReceivingState.with({ channels: context.channels, groups: context.groups, cursor: event.payload.cursor }, [
(0, effects_1.emitMessages)(event.payload.events),
]);
});

@@ -33,5 +39,22 @@ exports.ReceivingState.on(events_1.subscriptionChange.type, function (context, event) {

}
return exports.ReceivingState.with(__assign(__assign({}, context), { channels: event.payload.channels, groups: event.payload.groups }));
return exports.ReceivingState.with({
cursor: context.cursor,
channels: event.payload.channels,
groups: event.payload.groups,
});
});
exports.ReceivingState.on(events_1.receivingFailure.type, function (context, event) {
exports.ReceivingState.on(events_1.restore.type, function (context, event) {
if (event.payload.channels.length === 0 && event.payload.groups.length === 0) {
return unsubscribed_1.UnsubscribedState.with(undefined);
}
return exports.ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
});
});
exports.ReceivingState.on(events_1.receiveFailure.type, function (context, event) {
return receive_reconnecting_1.ReceiveReconnectingState.with(__assign(__assign({}, context), { attempts: 0, reason: event.payload }));

@@ -44,3 +67,6 @@ });

cursor: context.cursor,
});
}, [(0, effects_1.emitStatus)({ category: categories_1.default.PNDisconnectedCategory })]);
});
exports.ReceivingState.on(events_1.unsubscribeAll.type, function (_) {
return unsubscribed_1.UnsubscribedState.with(undefined, [(0, effects_1.emitStatus)({ category: categories_1.default.PNDisconnectedCategory })]);
});

@@ -9,3 +9,13 @@ "use strict";

exports.UnsubscribedState.on(events_1.subscriptionChange.type, function (_, event) {
return handshaking_1.HandshakingState.with({ channels: event.payload.channels, groups: event.payload.groups });
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
});
});
exports.UnsubscribedState.on(events_1.restore.type, function (_, event) {
return handshaking_1.HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: event.payload.cursor,
});
});

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

function default_1(setup) {
var _this = this;
setup.db = new common_1.default();

@@ -39,4 +38,3 @@ setup.networking = new networking_1.default({

setup.sdkFamily = 'NativeScript';
_this = _super.call(this, setup) || this;
return _this;
return _super.call(this, setup) || this;
}

@@ -43,0 +41,0 @@ return default_1;

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

function class_1(setup) {
var _this = this;
setup.cbor = new common_1.default(function (buffer) { return cbor_sync_1.default.decode(Buffer.from(buffer)); }, base64_codec_1.decode);

@@ -62,4 +61,3 @@ setup.networking = new networking_1.default({

}
_this = _super.call(this, setup) || this;
return _this;
return _super.call(this, setup) || this;
}

@@ -66,0 +64,0 @@ return class_1;

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

function default_1(setup) {
var _this = this;
setup.cbor = new common_1.default(function (arrayBuffer) { return (0, stringify_buffer_keys_1.stringifyBufferKeys)(cbor_js_1.default.decode(arrayBuffer)); }, base64_codec_1.decode);

@@ -49,4 +48,3 @@ setup.PubNubFile = react_native_2.default;

setup.ssl = true;
_this = _super.call(this, setup) || this;
return _this;
return _super.call(this, setup) || this;
}

@@ -53,0 +51,0 @@ return default_1;

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

function PubNub(setup) {
var _this = this;
setup.cbor = new common_1.default(cbor_sync_1.default.decode, function (base64String) { return Buffer.from(base64String, 'base64'); });

@@ -40,4 +39,3 @@ setup.sdkFamily = 'TitaniumSDK';

});
_this = _super.call(this, setup) || this;
return _this;
return _super.call(this, setup) || this;
}

@@ -44,0 +42,0 @@ return PubNub;

{
"name": "pubnub",
"version": "7.4.5",
"version": "7.5.0",
"author": "PubNub <support@pubnub.com>",

@@ -20,2 +20,6 @@ "description": "Publish & Subscribe Real-time Messaging with PubNub",

"test:feature:fileupload:node": "ts-mocha -p tsconfig.mocha.json --no-config --require test/setup.js --reporter spec test/feature/file_upload.node.test.js",
"test:contract": "npm run test:contract:prepare && npm run test:contract:start",
"test:contract:prepare": "rimraf test/specs && git clone --branch master --depth 1 git@github.com:pubnub/sdk-specifications.git test/specs",
"test:contract:start": "cucumber-js -p default --tags 'not @na=js'",
"test:contract:beta": "cucumber-js -p default --tags 'not @na=js and @beta and not @skip'",
"contract:refresh": "rimraf dist/contract && git clone --branch master git@github.com:pubnub/service-contract-mock.git dist/contract && npm install --prefix dist/contract && npm run refresh-files --prefix dist/contract",

@@ -61,2 +65,3 @@ "contract:server": "npm start --prefix dist/contract consumer",

"@cucumber/cucumber": "^7.3.1",
"@cucumber/pretty-formatter": "^1.0.0",
"@rollup/plugin-commonjs": "^21.0.2",

@@ -66,10 +71,16 @@ "@rollup/plugin-json": "^4.1.0",

"@rollup/plugin-typescript": "^8.3.1",
"@types/chai": "^4.3.3",
"@types/cucumber": "^7.0.0",
"@types/expect": "^24.3.0",
"@types/mocha": "^9.1.0",
"@types/nock": "^9.3.1",
"@types/node-fetch": "^2.6.3",
"@types/pubnub": "^7.2.0",
"@typescript-eslint/eslint-plugin": "^5.12.1",
"@typescript-eslint/parser": "^5.12.1",
"chai": "4.3.4",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"chai-nock": "^1.2.0",
"cucumber-pretty": "^6.0.1",
"cucumber-tsflow": "^4.0.0-rc.11",
"es6-shim": "^0.35.6",

@@ -90,3 +101,3 @@ "eslint": "^8.9.0",

"nock": "^9.6.1",
"node-fetch": "^2.6.1",
"node-fetch": "^2.6.9",
"phantomjs-prebuilt": "^2.1.16",

@@ -100,5 +111,6 @@ "prettier": "^2.5.1",

"sinon-chai": "^3.3.0",
"source-map-support": "^0.5.21",
"ts-mocha": "^9.0.2",
"ts-node": "^10.7.0",
"typescript": "^4.3.5",
"ts-node": "^10.9.1",
"typescript": "^4.8.4",
"underscore": "^1.9.2"

@@ -105,0 +117,0 @@ },

@@ -31,4 +31,4 @@ # PubNub JavaScript SDK (V4)

* or download one of our builds from our CDN:
* https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.5.js
* https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.5.min.js
* https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.js
* https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.min.js

@@ -35,0 +35,0 @@ 2. Configure your keys:

@@ -77,2 +77,5 @@ /* */

// configure retry policy configuration.
retryConfiguration;
// alert when a heartbeat works out.

@@ -144,3 +147,4 @@ announceSuccessfulHeartbeats;

useRandomIVs;
enableSubscribeBeta;
enableEventEngine;
maintainPresenceState;

@@ -188,4 +192,4 @@ /*

// flag for beta subscribe feature enablement
this.enableSubscribeBeta = setup.enableSubscribeBeta ?? false;
this.enableEventEngine = setup.enableEventEngine ?? false;
this.maintainPresenceState = setup.maintainPresenceState ?? true;

@@ -208,2 +212,6 @@ // if location config exist and we are in https, force secure to true.

if (setup.retryConfiguration) {
this._setRetryConfiguration(setup.retryConfiguration);
}
// set timeout to how long a transaction request will wait for the server (default 15 seconds)

@@ -357,5 +365,20 @@ this.setTransactionTimeout(setup.transactionalRequestTimeout || 15 * 1000);

getVersion() {
return '7.4.5';
return '7.5.0';
}
_setRetryConfiguration(configuration) {
if (configuration.minimumdelay < 2) {
throw new Error('Minimum delay can not be set less than 2 seconds for retry');
}
if (configuration.maximumDelay > 150) {
throw new Error('Maximum delay can not be set more than 150 seconds for retry');
}
if (configuration.maximumDelay && maximumRetry > 6) {
throw new Error('Maximum retry for exponential retry policy can not be more than 6');
} else if (configuration.maximumRetry > 10) {
throw new Error('Maximum retry for linear retry policy can not be more than 10');
}
this.retryConfiguration = configuration;
}
_addPnsdkSuffix(name, suffix) {

@@ -362,0 +385,0 @@ this._PNSDKSuffix[name] = suffix;

/* */
import Config from './config';
import { SubscribeMessage } from '../flow_interfaces';

@@ -6,0 +5,0 @@ const hashCode = (payload) => {

@@ -10,4 +10,7 @@ import categoryConstants from '../constants/categories';

addListener(newListeners) {
this._listeners.push(newListeners);
addListener(newListener) {
if (this._listeners.includes(newListener)) {
return;
}
this._listeners.push(newListener);
}

@@ -14,0 +17,0 @@

/* */
/* eslint max-classes-per-file: ["error", 5] */
import { APNS2Configuration, APNS2Target } from '../flow_interfaces';

@@ -5,0 +4,0 @@ class BaseNotificationPayload {

import TimeEndpoint from '../endpoints/time';
import { StatusAnnouncement } from '../flow_interfaces';

@@ -4,0 +3,0 @@ export default class {

@@ -30,2 +30,8 @@ /* */

PNRequestMessageCountExceededCategory: 'PNRequestMessageCountExceededCategory',
PNDisconnectedCategory: 'PNDisconnectedCategory',
PNConnectionErrorCategory: 'PNConnectionErrorCategory',
PNDisconnectedUnexpectedlyCategory: 'PNDisconnectedUnexpectedlyCategory',
};
/* */
import { AuditArguments, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@

/* */
import { GrantArguments, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@

/* */
import { AddMessageActionInput, AddMessageActionResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

/* */
import { GetMessageActionsInput, GetMessageActionsResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { RemoveMessageActionInput, RemoveMessageActionResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

/* */
import { AddChannelParams, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { DeleteGroupParams, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

/* */
import { ListChannelsParams, ListChannelsResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { ListAllGroupsResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@

/* */
import { RemoveChannelParams, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import {
FetchMessagesArguments,
FetchMessagesResponse,
MessageAnnouncement,
HistoryV3Response,
ModulesInject,
} from '../flow_interfaces';
import operationConstants from '../constants/operations';

@@ -11,0 +3,0 @@ import utils from '../utils';

/* */
import { FetchHistoryArguments, HistoryResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

/* */
import { FetchHistoryArguments, HistoryResponse, HistoryItem, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { GetStateArguments, GetStateResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

/* */
import { HeartbeatArguments, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -33,3 +32,3 @@ import utils from '../../utils';

export function prepareParams(modules, incomingParams) {
const { channelGroups = [], state = {} } = incomingParams;
const { channelGroups = [], state } = incomingParams;
const { config } = modules;

@@ -42,3 +41,5 @@ const params = {};

params.state = JSON.stringify(state);
if (state) {
params.state = JSON.stringify(state);
}
params.heartbeat = config.getPresenceTimeout();

@@ -45,0 +46,0 @@ return params;

/* */
import { HereNowArguments, ModulesInject, StatusAnnouncement } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { LeaveArguments, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../../utils';

@@ -45,3 +45,2 @@ import operationConstants from '../../constants/operations';

}
return params;

@@ -48,0 +47,0 @@ }

/* */
import { WhereNowArguments, WhereNowResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../../utils';

/* */
import { PublishResponse, PublishArguments, ModulesInject } from '../flow_interfaces';
import operationConstants from '../constants/operations';

@@ -5,0 +3,0 @@ import utils from '../utils';

/* */
import { ModifyDeviceArgs, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@

/* */
import { ListChannelsArgs, ListChannelsResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +3,0 @@

/* */
import { RemoveDeviceArgs, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@

/* */
import { ModifyDeviceArgs, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

@@ -5,0 +4,0 @@

/* */
import { SignalResponse, SignalArguments, ModulesInject } from '../flow_interfaces';
import operationConstants from '../constants/operations';

@@ -5,0 +4,0 @@ import utils from '../utils';

/* */
import {
SubscribeArguments,
PublishMetaData,
SubscribeMetadata,
SubscribeMessage,
SubscribeEnvelope,
ModulesInject,
} from '../flow_interfaces';
import operationConstants from '../constants/operations';

@@ -12,0 +3,0 @@ import utils from '../utils';

@@ -28,2 +28,9 @@ import operationConstants from '../../constants/operations';

outParams.tt = 0;
if (params.state) {
outParams.state = JSON.stringify(params.state);
}
if (params.filterExpression && params.filterExpression.length > 0) {
outParams['filter-expr'] = params.filterExpression;
}
outParams.ee = '';
return outParams;

@@ -30,0 +37,0 @@ },

@@ -35,4 +35,8 @@ import operationConstants from '../../constants/operations';

}
if (params.filterExpression && params.filterExpression.length > 0) {
outParams['filter-expr'] = params.filterExpression;
}
outParams.tt = params.timetoken;
outParams.tr = params.region;
outParams.ee = '';
return outParams;

@@ -39,0 +43,0 @@ },

/* */
import { TimeResponse, ModulesInject } from '../flow_interfaces';
import operationConstants from '../constants/operations';

@@ -5,0 +3,0 @@

@@ -94,2 +94,5 @@ import Config from './components/config';

import { EventEngine } from '../event-engine';
import { PresenceEventEngine } from '../event-engine/presence/presence';
import { RetryPolicy } from '../event-engine/core/retryPolicy';
import EventEmitter from './components/eventEmitter';

@@ -275,3 +278,3 @@ export default class {

//
_eventEmitter;

@@ -343,8 +346,66 @@ constructor(setup) {

if (config.enableSubscribeBeta === true) {
const eventEngine = new EventEngine({ handshake: this.handshake, receiveEvents: this.receiveMessages });
if (config.enableEventEngine === true) {
this._eventEmitter = new EventEmitter({
modules: modules,
listenerManager: this._listenerManager,
getFileUrl: (params) => getFileUrlFunction(modules, params),
});
if (config.maintainPresenceState) {
this.presenceState = {};
this.setState = (args) => {
args.channels?.forEach((channel) => (this.presenceState[channel] = args.state));
args.channelGroups?.forEach((group) => (this.presenceState[group] = args.state));
return this.setPresenceState({
channels: args.channels,
channelGroups: args.channelGroups,
state: this.presenceState,
});
};
}
if (config.getHeartbeatInterval()) {
const presenceEventEngine = new PresenceEventEngine({
heartbeat: this.iAmHere,
leave: this.iAmAway,
heartbeatDelay: () =>
new Promise((resolve) => setTimeout(resolve, modules.config.getHeartbeatInterval() * 1000)),
retryDelay: (amount) => new Promise((resolve) => setTimeout(resolve, amount)),
config: modules.config,
presenceState: this.presenceState,
emitStatus: (status) => {
listenerManager.announceStatus(status);
},
});
this.presenceEventEngine = presenceEventEngine;
this.join = this.presenceEventEngine.join.bind(presenceEventEngine);
this.leave = this.presenceEventEngine.leave.bind(presenceEventEngine);
this.leaveAll = this.presenceEventEngine.leaveAll.bind(presenceEventEngine);
}
const eventEngine = new EventEngine({
handshake: this.handshake,
receiveMessages: this.receiveMessages,
delay: (amount) => new Promise((resolve) => setTimeout(resolve, amount)),
join: this.join,
leave: this.leave,
leaveAll: this.leaveAll,
presenceState: this.presenceState,
config: modules.config,
emitMessages: (events) => {
for (const event of events) {
this._eventEmitter.emitEvent(event);
}
},
emitStatus: (status) => {
listenerManager.announceStatus(status);
},
});
this.subscribe = eventEngine.subscribe.bind(eventEngine);
this.unsubscribe = eventEngine.unsubscribe.bind(eventEngine);
this.unsubscribeAll = eventEngine.unsubscribeAll.bind(eventEngine);
this.reconnect = eventEngine.reconnect.bind(eventEngine);
this.disconnect = eventEngine.disconnect.bind(eventEngine);
this.destroy = eventEngine.dispose.bind(eventEngine);
this.getSubscribedChannels = eventEngine.getSubscribedChannels.bind(eventEngine);
this.getSubscribedChannelGroups = eventEngine.getSubscribedChannelGroups.bind(eventEngine);
this.eventEngine = eventEngine;

@@ -718,3 +779,2 @@ } else {

this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config);
// this.setCipherKey = modules.config.setCipherKey.bind(modules.config);
this.setCipherKey = (key) => modules.config.setCipherKey(key, setup, modules);

@@ -766,2 +826,5 @@ this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config);

static CATEGORIES = CATEGORIES;
static LinearRetryPolicy = RetryPolicy.LinearRetryPolicy;
static ExponentialRetryPolicy = RetryPolicy.ExponentialRetryPolicy;
}

@@ -52,2 +52,9 @@ /* eslint-disable @typescript-eslint/no-explicit-any */

}
dispose() {
for (const [key, instance] of this.instances.entries()) {
instance.cancel();
this.instances.delete(key);
}
}
}

@@ -28,3 +28,6 @@ import { AbortSignal } from '../../core/components/abort_signal';

start() {
this.asyncFunction(this.payload, this.abortSignal, this.dependencies);
this.asyncFunction(this.payload, this.abortSignal, this.dependencies).catch((error) => {
// console.log('Unhandled error:', error);
// swallow the error
});
}

@@ -31,0 +34,0 @@

@@ -8,7 +8,13 @@ import { PubNubError } from '../core/components/endpoint';

handshake: any;
receiveEvents: any;
receiveMessages: any;
join: any;
leave: any;
leaveAll: any;
presenceState: any;
config: any;
getRetryDelay: (attempts: number) => number;
shouldRetry: (error: Error, attempts: number) => boolean;
delay: (milliseconds: number) => Promise<void>;
emitMessages: (events: any[]) => void;
emitStatus: (status: any) => void;
};

@@ -22,3 +28,3 @@

effects.handshake.type,
asyncHandler(async (payload, abortSignal, { handshake }) => {
asyncHandler(async (payload, abortSignal, { handshake, presenceState, config }) => {
abortSignal.throwIfAborted();

@@ -31,5 +37,6 @@

channelGroups: payload.groups,
filterExpression: config.filterExpression,
...(config.maintainPresenceState && { state: presenceState }),
});
engine.transition(events.handshakingSuccess(result));
return engine.transition(events.handshakeSuccess(result));
} catch (e) {

@@ -41,3 +48,3 @@ if (e instanceof Error && e.message === 'Aborted') {

if (e instanceof PubNubError) {
return engine.transition(events.handshakingFailure(e));
return engine.transition(events.handshakeFailure(e));
}

@@ -49,8 +56,7 @@ }

this.on(
effects.receiveEvents.type,
asyncHandler(async (payload, abortSignal, { receiveEvents }) => {
effects.receiveMessages.type,
asyncHandler(async (payload, abortSignal, { receiveMessages, config }) => {
abortSignal.throwIfAborted();
try {
const result = await receiveEvents({
const result = await receiveMessages({
abortSignal: abortSignal,

@@ -61,5 +67,6 @@ channels: payload.channels,

region: payload.cursor.region,
filterExpression: config.filterExpression,
});
engine.transition(events.receivingSuccess(result.metadata, result.messages));
engine.transition(events.receiveSuccess(result.metadata, result.messages));
} catch (error) {

@@ -70,4 +77,4 @@ if (error instanceof Error && error.message === 'Aborted') {

if (error instanceof PubNubError) {
return engine.transition(events.receivingFailure(error));
if (error instanceof PubNubError && !abortSignal.aborted) {
return engine.transition(events.receiveFailure(error));
}

@@ -79,6 +86,6 @@ }

this.on(
effects.emitEvents.type,
asyncHandler(async (payload, abortSignal, { receiveEvents }) => {
effects.emitMessages.type,
asyncHandler(async (payload, _, { emitMessages }) => {
if (payload.length > 0) {
console.log(payload);
emitMessages(payload);
}

@@ -89,32 +96,44 @@ }),

this.on(
effects.reconnect.type,
asyncHandler(async (payload, abortSignal, { receiveEvents, shouldRetry, getRetryDelay, delay }) => {
if (!shouldRetry(payload.reason, payload.attempts)) {
return engine.transition(events.reconnectingGiveup());
}
effects.emitStatus.type,
asyncHandler(async (payload, _, { emitStatus }) => {
emitStatus(payload);
}),
);
abortSignal.throwIfAborted();
this.on(
effects.receiveReconnect.type,
asyncHandler(async (payload, abortSignal, { receiveMessages, delay, config }) => {
if (config.retryConfiguration && config.retryConfiguration.shouldRetry(payload.reason, payload.attempts)) {
abortSignal.throwIfAborted();
await delay(getRetryDelay(payload.attempts));
await delay(config.retryConfiguration.getDelay(payload.attempts, payload.reason));
abortSignal.throwIfAborted();
abortSignal.throwIfAborted();
try {
const result = await receiveEvents({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
timetoken: payload.cursor.timetoken,
region: payload.cursor.region,
});
try {
const result = await receiveMessages({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
timetoken: payload.cursor.timetoken,
region: payload.cursor.region,
filterExpression: config.filterExpression,
});
return engine.transition(events.reconnectingSuccess(result.metadata, result.messages));
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
return;
}
return engine.transition(events.receiveReconnectSuccess(result.metadata, result.messages));
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
return;
}
if (error instanceof PubNubError) {
return engine.transition(events.reconnectingFailure(error));
if (error instanceof PubNubError) {
return engine.transition(events.receiveReconnectFailure(error));
}
}
} else {
return engine.transition(
events.receiveReconnectGiveup(
new PubNubError(config.retryConfiguration.getGiveupReason(payload.reason, payload.attempts)),
),
);
}

@@ -126,29 +145,35 @@ }),

effects.handshakeReconnect.type,
asyncHandler(async (payload, abortSignal, { handshake, shouldRetry, getRetryDelay, delay }) => {
if (!shouldRetry(payload.reason, payload.attempts)) {
return engine.transition(events.handshakingReconnectingGiveup());
}
asyncHandler(async (payload, abortSignal, { handshake, delay, presenceState, config }) => {
if (config.retryConfiguration && config.retryConfiguration.shouldRetry(payload.reason, payload.attempts)) {
abortSignal.throwIfAborted();
abortSignal.throwIfAborted();
await delay(config.retryConfiguration.getDelay(payload.attempts, payload.reason));
await delay(getRetryDelay(payload.attempts));
abortSignal.throwIfAborted();
abortSignal.throwIfAborted();
try {
const result = await handshake({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
filterExpression: config.filterExpression,
...(config.maintainPresenceState && { state: presenceState }),
});
try {
const result = await handshake({
abortSignal: abortSignal,
channels: payload.channels,
channelGroups: payload.groups,
});
return engine.transition(events.handshakeReconnectSuccess(result));
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
return;
}
return engine.transition(events.handshakingReconnectingSuccess(result.metadata));
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
return;
if (error instanceof PubNubError) {
return engine.transition(events.handshakeReconnectFailure(error));
}
}
if (error instanceof PubNubError) {
return engine.transition(events.handshakingReconnectingFailure(error));
}
} else {
return engine.transition(
events.handshakeReconnectGiveup(
new PubNubError(config.retryConfiguration.getGiveupReason(payload.reason, payload.attempts)),
),
);
}

@@ -155,0 +180,0 @@ }),

@@ -11,11 +11,16 @@ import { Cursor } from '../models/Cursor';

export const receiveEvents = createManagedEffect(
'RECEIVE_EVENTS',
export const receiveMessages = createManagedEffect(
'RECEIVE_MESSAGES',
(channels: string[], groups: string[], cursor: Cursor) => ({ channels, groups, cursor }),
);
export const emitEvents = createEffect('EMIT_EVENTS', (events: any[]) => events);
export const emitMessages = createEffect('EMIT_MESSAGES', (events: any[]) => events);
export const reconnect = createManagedEffect('RECONNECT', (context: ReceiveReconnectingStateContext) => context);
export const emitStatus = createEffect('EMIT_STATUS', (status: any) => status);
export const receiveReconnect = createManagedEffect(
'RECEIVE_RECONNECT',
(context: ReceiveReconnectingStateContext) => context,
);
export const handshakeReconnect = createManagedEffect(

@@ -27,3 +32,8 @@ 'HANDSHAKE_RECONNECT',

export type Effects = MapOf<
typeof receiveEvents | typeof handshake | typeof emitEvents | typeof reconnect | typeof handshakeReconnect
| typeof receiveMessages
| typeof handshake
| typeof emitMessages
| typeof receiveReconnect
| typeof handshakeReconnect
| typeof emitStatus
>;

@@ -5,3 +5,3 @@ import { PubNubError } from '../core/components/endpoint';

export const subscriptionChange = createEvent('SUBSCRIPTION_CHANGE', (channels: string[], groups: string[]) => ({
export const subscriptionChange = createEvent('SUBSCRIPTION_CHANGED', (channels: string[], groups: string[]) => ({
channels,

@@ -11,58 +11,61 @@ groups,

export const disconnect = createEvent('DISCONNECT', () => ({}));
export const reconnect = createEvent('RECONNECT', () => ({}));
export const restore = createEvent(
'RESTORE',
(channels: string[], groups: string[], timetoken?: string, region?: number) => ({
'SUBSCRIPTION_RESTORED',
(channels: string[], groups: string[], timetoken: string, region?: number) => ({
channels,
groups,
timetoken,
region,
cursor: {
timetoken: timetoken,
region: region ?? 0,
},
}),
);
export const handshakingSuccess = createEvent('HANDSHAKING_SUCCESS', (cursor: Cursor) => cursor);
export const handshakingFailure = createEvent('HANDSHAKING_FAILURE', (error: PubNubError) => error);
export const handshakeSuccess = createEvent('HANDSHAKE_SUCCESS', (cursor: Cursor) => cursor);
export const handshakeFailure = createEvent('HANDSHAKE_FAILURE', (error: PubNubError) => error);
export const handshakingReconnectingSuccess = createEvent('HANDSHAKING_RECONNECTING_SUCCESS', (cursor: Cursor) => ({
export const handshakeReconnectSuccess = createEvent('HANDSHAKE_RECONNECT_SUCCESS', (cursor: Cursor) => ({
cursor,
}));
export const handshakingReconnectingFailure = createEvent(
'HANDSHAKING_RECONNECTING_FAILURE',
(error: PubNubError) => error,
);
export const handshakingReconnectingGiveup = createEvent('HANDSHAKING_RECONNECTING_GIVEUP', () => ({}));
export const handshakingReconnectingRetry = createEvent('HANDSHAKING_RECONNECTING_RETRY', () => ({}));
export const handshakeReconnectFailure = createEvent('HANDSHAKE_RECONNECT_FAILURE', (error: PubNubError) => error);
export const handshakeReconnectGiveup = createEvent('HANDSHAKE_RECONNECT_GIVEUP', (error: PubNubError) => error);
export const receivingSuccess = createEvent('RECEIVING_SUCCESS', (cursor: Cursor, events: any[]) => ({
export const receiveSuccess = createEvent('RECEIVE_SUCCESS', (cursor: Cursor, events: any[]) => ({
cursor,
events,
}));
export const receivingFailure = createEvent('RECEIVING_FAILURE', (error: PubNubError) => error);
export const receiveFailure = createEvent('RECEIVE_FAILURE', (error: PubNubError) => error);
export const reconnectingSuccess = createEvent('RECONNECTING_SUCCESS', (cursor: Cursor, events: any[]) => ({
export const receiveReconnectSuccess = createEvent('RECEIVE_RECONNECT_SUCCESS', (cursor: Cursor, events: any[]) => ({
cursor,
events,
}));
export const reconnectingFailure = createEvent('RECONNECTING_FAILURE', (error: PubNubError) => error);
export const reconnectingGiveup = createEvent('RECONNECTING_GIVEUP', () => ({}));
export const reconnectingRetry = createEvent('RECONNECTING_RETRY', () => ({}));
export const receiveReconnectFailure = createEvent('RECEIVE_RECONNECT_FAILURE', (error: PubNubError) => error);
export const receiveReconnectGiveup = createEvent('RECEIVING_RECONNECT_GIVEUP', (error: PubNubError) => error);
export const disconnect = createEvent('DISCONNECT', () => ({}));
export const reconnect = createEvent('RECONNECT', (timetoken?: string, region?: number) => ({
cursor: {
timetoken: timetoken ?? '',
region: region ?? 0,
},
}));
export const unsubscribeAll = createEvent('UNSUBSCRIBE_ALL', () => ({}));
export type Events = MapOf<
| typeof subscriptionChange
| typeof restore
| typeof handshakeSuccess
| typeof handshakeFailure
| typeof handshakeReconnectSuccess
| typeof handshakeReconnectFailure
| typeof handshakeReconnectGiveup
| typeof receiveSuccess
| typeof receiveFailure
| typeof receiveReconnectSuccess
| typeof receiveReconnectFailure
| typeof receiveReconnectGiveup
| typeof disconnect
| typeof reconnect
| typeof restore
| typeof handshakingSuccess
| typeof handshakingFailure
| typeof handshakingReconnectingSuccess
| typeof handshakingReconnectingGiveup
| typeof handshakingReconnectingFailure
| typeof handshakingReconnectingRetry
| typeof receivingSuccess
| typeof receivingFailure
| typeof reconnectingSuccess
| typeof reconnectingFailure
| typeof reconnectingGiveup
| typeof reconnectingRetry
| typeof unsubscribeAll
>;

@@ -11,2 +11,3 @@ import { Dispatcher, Engine } from './core';

private dispatcher: Dispatcher<effects.Effects, Dependencies>;
private dependencies: any;

@@ -17,6 +18,9 @@ get _engine() {

private _unsubscribeEngine!: () => void;
constructor(dependencies: Dependencies) {
this.dependencies = dependencies;
this.dispatcher = new EventEngineDispatcher(this.engine, dependencies);
this.engine.subscribe((change) => {
this._unsubscribeEngine = this.engine.subscribe((change) => {
if (change.type === 'invocationDispatched') {

@@ -33,14 +37,52 @@ this.dispatcher.dispatch(change.invocation);

subscribe({ channels, groups }: { channels?: string[]; groups?: string[] }) {
subscribe({
channels,
channelGroups,
timetoken,
withPresence,
}: {
channels?: string[];
channelGroups?: string[];
timetoken?: string;
withPresence?: boolean;
}) {
this.channels = [...this.channels, ...(channels ?? [])];
this.groups = [...this.groups, ...(groups ?? [])];
this.engine.transition(events.subscriptionChange(this.channels, this.groups));
this.groups = [...this.groups, ...(channelGroups ?? [])];
if (withPresence) {
this.channels.map((c) => this.channels.push(`${c}-pnpres`));
this.groups.map((g) => this.groups.push(`${g}-pnpres`));
}
if (timetoken) {
this.engine.transition(events.restore(this.channels, this.groups, timetoken));
} else {
this.engine.transition(events.subscriptionChange(this.channels, this.groups));
}
if (this.dependencies.join) {
this.dependencies.join({
channels: this.channels.filter((c) => !c.endsWith('-pnpres')),
groups: this.groups.filter((g) => !g.endsWith('-pnpres')),
});
}
}
unsubscribe({ channels, groups }: { channels?: string[]; groups?: string[] }) {
this.channels = this.channels.filter((channel) => !channels?.includes(channel) ?? true);
this.groups = this.groups.filter((group) => !groups?.includes(group) ?? true);
const channlesWithPres: any = channels?.slice(0);
channels?.map((c) => channlesWithPres.push(`${c}-pnpres`));
this.channels = this.channels.filter((channel) => !channlesWithPres?.includes(channel));
const groupsWithPres: any = groups?.slice(0);
groups?.map((g) => groupsWithPres.push(`${g}-pnpres`));
this.groups = this.groups.filter((group) => !groupsWithPres?.includes(group));
if (this.dependencies.presenceState) {
channels?.forEach((c) => delete this.dependencies.presenceState[c]);
groups?.forEach((g) => delete this.dependencies.presenceState[g]);
}
this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0)));
if (this.dependencies.leave) {
this.dependencies.leave({
channels: channels,
groups: groups,
});
}
}

@@ -52,7 +94,13 @@

if (this.dependencies.presenceState) {
this.dependencies.presenceState = {};
}
this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0)));
if (this.dependencies.leaveAll) {
this.dependencies.leaveAll();
}
}
reconnect() {
this.engine.transition(events.reconnect());
reconnect({ timetoken, region }: { timetoken?: string; region?: number }) {
this.engine.transition(events.reconnect(timetoken, region));
}

@@ -62,3 +110,20 @@

this.engine.transition(events.disconnect());
if (this.dependencies.leaveAll) {
this.dependencies.leaveAll();
}
}
getSubscribedChannels() {
return this.channels.slice(0);
}
getSubscribedChannelGroups() {
return this.groups.slice(0);
}
dispose() {
this.disconnect();
this._unsubscribeEngine();
this.dispatcher.dispose();
}
}
import { PubNubError } from '../../core/components/endpoint';
import { State } from '../core/state';
import { Effects, emitEvents, handshakeReconnect, reconnect } from '../effects';
import { disconnect, Events, reconnectingFailure, reconnectingGiveup, reconnectingSuccess } from '../events';
import { HandshakeFailureState } from './handshake_failure';
import { Effects, emitStatus, handshakeReconnect } from '../effects';
import {
disconnect,
Events,
handshakeReconnectFailure,
handshakeReconnectGiveup,
handshakeReconnectSuccess,
restore,
subscriptionChange,
unsubscribeAll,
} from '../events';
import { HandshakeFailedState } from './handshake_failed';
import { HandshakeStoppedState } from './handshake_stopped';
import { HandshakingState } from './handshaking';
import { ReceivingState } from './receiving';
import { UnsubscribedState } from './unsubscribed';
import categoryConstants from '../../core/constants/categories';
import { Cursor } from '../../models/Cursor';

@@ -12,2 +25,3 @@ export type HandshakeReconnectingStateContext = {

groups: string[];
cursor?: Cursor;

@@ -23,25 +37,33 @@ attempts: number;

HandshakeReconnectingState.onEnter((context) => handshakeReconnect(context));
HandshakeReconnectingState.onExit(() => reconnect.cancel);
HandshakeReconnectingState.onExit(() => handshakeReconnect.cancel);
HandshakeReconnectingState.on(reconnectingSuccess.type, (context, event) =>
ReceivingState.with(
HandshakeReconnectingState.on(handshakeReconnectSuccess.type, (context, event) => {
const cursor = {
timetoken: !!context.cursor?.timetoken ? context.cursor?.timetoken : event.payload.cursor.timetoken,
region: event.payload.cursor.region,
};
return ReceivingState.with(
{
channels: context.channels,
groups: context.groups,
cursor: event.payload.cursor,
cursor: cursor,
},
[emitEvents(event.payload.events)],
),
);
[emitStatus({ category: categoryConstants.PNConnectedCategory })],
);
});
HandshakeReconnectingState.on(reconnectingFailure.type, (context, event) =>
HandshakeReconnectingState.on(handshakeReconnectFailure.type, (context, event) =>
HandshakeReconnectingState.with({ ...context, attempts: context.attempts + 1, reason: event.payload }),
);
HandshakeReconnectingState.on(reconnectingGiveup.type, (context) =>
HandshakeFailureState.with({
groups: context.groups,
channels: context.channels,
reason: context.reason,
}),
HandshakeReconnectingState.on(handshakeReconnectGiveup.type, (context, event) =>
HandshakeFailedState.with(
{
groups: context.groups,
channels: context.channels,
cursor: context.cursor,
reason: event.payload,
},
[emitStatus({ category: categoryConstants.PNConnectionErrorCategory, error: event.payload?.message })],
),
);

@@ -53,3 +75,25 @@

groups: context.groups,
cursor: context.cursor,
}),
);
HandshakeReconnectingState.on(subscriptionChange.type, (context, event) =>
HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
}),
);
HandshakeReconnectingState.on(restore.type, (context, event) =>
HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor?.region || context?.cursor?.region || 0,
},
}),
);
HandshakeReconnectingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with(undefined));

@@ -0,5 +1,7 @@

import { Cursor } from '../../models/Cursor';
import { State } from '../core/state';
import { Effects } from '../effects';
import { Events, reconnect, subscriptionChange } from '../events';
import { Events, reconnect, restore, subscriptionChange, unsubscribeAll } from '../events';
import { HandshakingState } from './handshaking';
import { UnsubscribedState } from './unsubscribed';

@@ -9,13 +11,33 @@ type HandshakeStoppedStateContext = {

groups: string[];
cursor?: Cursor;
};
export const HandshakeStoppedState = new State<HandshakeStoppedStateContext, Events, Effects>('STOPPED');
export const HandshakeStoppedState = new State<HandshakeStoppedStateContext, Events, Effects>('HANDSHAKE_STOPPED');
HandshakeStoppedState.on(subscriptionChange.type, (_context, event) =>
HandshakeStoppedState.on(subscriptionChange.type, (context, event) =>
HandshakeStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
}),
);
HandshakeStoppedState.on(reconnect.type, (context) => HandshakingState.with({ ...context }));
HandshakeStoppedState.on(reconnect.type, (context, event) =>
HandshakingState.with({
...context,
cursor: event.payload.cursor || context.cursor,
}),
);
HandshakeStoppedState.on(restore.type, (context, event) =>
HandshakeStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context?.cursor?.region || 0,
},
}),
);
HandshakeStoppedState.on(unsubscribeAll.type, (_) => UnsubscribedState.with());
import { State } from '../core/state';
import { Effects, handshake } from '../effects';
import { disconnect, Events, handshakingFailure, handshakingSuccess, subscriptionChange } from '../events';
import { Effects, handshake, emitStatus } from '../effects';
import {
disconnect,
restore,
Events,
handshakeFailure,
handshakeSuccess,
subscriptionChange,
unsubscribeAll,
} from '../events';
import { HandshakeReconnectingState } from './handshake_reconnecting';

@@ -8,2 +16,4 @@ import { HandshakeStoppedState } from './handshake_stopped';

import { UnsubscribedState } from './unsubscribed';
import categoryConstants from '../../core/constants/categories';
import { Cursor } from '../../models/Cursor';

@@ -13,2 +23,3 @@ export type HandshakingStateContext = {

groups: string[];
cursor?: Cursor;
};

@@ -26,20 +37,36 @@

return HandshakingState.with({ channels: event.payload.channels, groups: event.payload.groups });
return HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
});
});
HandshakingState.on(handshakingSuccess.type, (context, event) =>
ReceivingState.with({
HandshakingState.on(handshakeSuccess.type, (context, event) =>
ReceivingState.with(
{
channels: context.channels,
groups: context.groups,
cursor: {
timetoken: !!context?.cursor?.timetoken ? context?.cursor?.timetoken : event.payload.timetoken,
region: event.payload.region,
},
},
[
emitStatus({
category: categoryConstants.PNConnectedCategory,
}),
],
),
);
HandshakingState.on(handshakeFailure.type, (context, event) => {
return HandshakeReconnectingState.with({
channels: context.channels,
groups: context.groups,
cursor: event.payload,
}),
);
HandshakingState.on(handshakingFailure.type, (context, event) =>
HandshakeReconnectingState.with({
...context,
cursor: context.cursor,
attempts: 0,
reason: event.payload,
}),
);
});
});

@@ -50,3 +77,17 @@ HandshakingState.on(disconnect.type, (context) =>

groups: context.groups,
cursor: context.cursor,
}),
);
HandshakingState.on(restore.type, (context, event) =>
HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context?.cursor?.region || 0,
},
}),
);
HandshakingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with());
import { PubNubError } from '../../core/components/endpoint';
import { Cursor } from '../../models/Cursor';
import { State } from '../core/state';
import { Effects, emitEvents, reconnect } from '../effects';
import { disconnect, Events, reconnectingFailure, reconnectingGiveup, reconnectingSuccess } from '../events';
import { Effects, emitMessages, receiveReconnect, emitStatus } from '../effects';
import {
disconnect,
Events,
receiveReconnectFailure,
receiveReconnectGiveup,
receiveReconnectSuccess,
restore,
subscriptionChange,
unsubscribeAll,
} from '../events';
import { ReceivingState } from './receiving';
import { ReceiveFailureState } from './receive_failure';
import { ReceiveFailedState } from './receive_failed';
import { ReceiveStoppedState } from './receive_stopped';
import { UnsubscribedState } from './unsubscribed';
import categoryConstants from '../../core/constants/categories';

@@ -23,6 +34,6 @@ export type ReceiveReconnectingStateContext = {

ReceiveReconnectingState.onEnter((context) => reconnect(context));
ReceiveReconnectingState.onExit(() => reconnect.cancel);
ReceiveReconnectingState.onEnter((context) => receiveReconnect(context));
ReceiveReconnectingState.onExit(() => receiveReconnect.cancel);
ReceiveReconnectingState.on(reconnectingSuccess.type, (context, event) =>
ReceiveReconnectingState.on(receiveReconnectSuccess.type, (context, event) =>
ReceivingState.with(

@@ -34,25 +45,54 @@ {

},
[emitEvents(event.payload.events)],
[emitMessages(event.payload.events)],
),
);
ReceiveReconnectingState.on(reconnectingFailure.type, (context, event) =>
ReceiveReconnectingState.on(receiveReconnectFailure.type, (context, event) =>
ReceiveReconnectingState.with({ ...context, attempts: context.attempts + 1, reason: event.payload }),
);
ReceiveReconnectingState.on(reconnectingGiveup.type, (context) =>
ReceiveFailureState.with({
groups: context.groups,
channels: context.channels,
cursor: context.cursor,
reason: context.reason,
ReceiveReconnectingState.on(receiveReconnectGiveup.type, (context, event) =>
ReceiveFailedState.with(
{
groups: context.groups,
channels: context.channels,
cursor: context.cursor,
reason: event.payload,
},
[emitStatus({ category: categoryConstants.PNDisconnectedUnexpectedlyCategory, error: event.payload?.message })],
),
);
ReceiveReconnectingState.on(disconnect.type, (context) =>
ReceiveStoppedState.with(
{
channels: context.channels,
groups: context.groups,
cursor: context.cursor,
},
[emitStatus({ category: categoryConstants.PNDisconnectedCategory })],
),
);
ReceiveReconnectingState.on(restore.type, (context, event) =>
ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
}),
);
ReceiveReconnectingState.on(disconnect.type, (context) =>
ReceiveStoppedState.with({
channels: context.channels,
groups: context.groups,
ReceiveReconnectingState.on(subscriptionChange.type, (context, event) =>
ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: context.cursor,
}),
);
ReceiveReconnectingState.on(unsubscribeAll.type, (_) =>
UnsubscribedState.with(undefined, [emitStatus({ category: categoryConstants.PNDisconnectedCategory })]),
);
import { Cursor } from '../../models/Cursor';
import { State } from '../core/state';
import { Effects } from '../effects';
import { Events, reconnect, subscriptionChange } from '../events';
import { ReceivingState } from './receiving';
import { Events, reconnect, restore, subscriptionChange, unsubscribeAll } from '../events';
import { HandshakingState } from './handshaking';
import { UnsubscribedState } from './unsubscribed';

@@ -13,3 +14,3 @@ type ReceiveStoppedStateContext = {

export const ReceiveStoppedState = new State<ReceiveStoppedStateContext, Events, Effects>('STOPPED');
export const ReceiveStoppedState = new State<ReceiveStoppedStateContext, Events, Effects>('RECEIVE_STOPPED');

@@ -24,2 +25,24 @@ ReceiveStoppedState.on(subscriptionChange.type, (context, event) =>

ReceiveStoppedState.on(reconnect.type, (context) => ReceivingState.with({ ...context }));
ReceiveStoppedState.on(restore.type, (context, event) =>
ReceiveStoppedState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
}),
);
ReceiveStoppedState.on(reconnect.type, (context, event) =>
HandshakingState.with({
channels: context.channels,
groups: context.groups,
cursor: {
timetoken: !!event.payload.cursor.timetoken ? event.payload.cursor?.timetoken : context.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
}),
);
ReceiveStoppedState.on(unsubscribeAll.type, () => UnsubscribedState.with(undefined));
import { State } from '../core/state';
import { Cursor } from '../../models/Cursor';
import { Effects, emitEvents, receiveEvents } from '../effects';
import { disconnect, Events, receivingFailure, receivingSuccess, subscriptionChange } from '../events';
import { Effects, emitMessages, emitStatus, receiveMessages } from '../effects';
import {
disconnect,
Events,
receiveFailure,
receiveSuccess,
restore,
subscriptionChange,
unsubscribeAll,
} from '../events';
import { UnsubscribedState } from './unsubscribed';
import { ReceiveReconnectingState } from './receive_reconnecting';
import { ReceiveStoppedState } from './receive_stopped';
import categoryConstants from '../../core/constants/categories';

@@ -17,7 +26,9 @@ export type ReceivingStateContext = {

ReceivingState.onEnter((context) => receiveEvents(context.channels, context.groups, context.cursor));
ReceivingState.onExit(() => receiveEvents.cancel);
ReceivingState.onEnter((context) => receiveMessages(context.channels, context.groups, context.cursor));
ReceivingState.onExit(() => receiveMessages.cancel);
ReceivingState.on(receivingSuccess.type, (context, event) => {
return ReceivingState.with({ ...context, cursor: event.payload.cursor }, [emitEvents(event.payload.events)]);
ReceivingState.on(receiveSuccess.type, (context, event) => {
return ReceivingState.with({ channels: context.channels, groups: context.groups, cursor: event.payload.cursor }, [
emitMessages(event.payload.events),
]);
});

@@ -30,6 +41,25 @@

return ReceivingState.with({ ...context, channels: event.payload.channels, groups: event.payload.groups });
return ReceivingState.with({
cursor: context.cursor,
channels: event.payload.channels,
groups: event.payload.groups,
});
});
ReceivingState.on(receivingFailure.type, (context, event) => {
ReceivingState.on(restore.type, (context, event) => {
if (event.payload.channels.length === 0 && event.payload.groups.length === 0) {
return UnsubscribedState.with(undefined);
}
return ReceivingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: {
timetoken: event.payload.cursor.timetoken,
region: event.payload.cursor.region || context.cursor.region,
},
});
});
ReceivingState.on(receiveFailure.type, (context, event) => {
return ReceiveReconnectingState.with({

@@ -42,8 +72,15 @@ ...context,

ReceivingState.on(disconnect.type, (context) =>
ReceiveStoppedState.with({
channels: context.channels,
groups: context.groups,
cursor: context.cursor,
}),
ReceivingState.on(disconnect.type, (context) => {
return ReceiveStoppedState.with(
{
channels: context.channels,
groups: context.groups,
cursor: context.cursor,
},
[emitStatus({ category: categoryConstants.PNDisconnectedCategory })],
);
});
ReceivingState.on(unsubscribeAll.type, (_) =>
UnsubscribedState.with(undefined, [emitStatus({ category: categoryConstants.PNDisconnectedCategory })]),
);
import { State } from '../core/state';
import { Effects } from '../effects';
import { Events, subscriptionChange } from '../events';
import { Events, subscriptionChange, restore } from '../events';
import { HandshakingState } from './handshaking';

@@ -9,3 +9,14 @@

UnsubscribedState.on(subscriptionChange.type, (_, event) =>
HandshakingState.with({ channels: event.payload.channels, groups: event.payload.groups }),
HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
}),
);
UnsubscribedState.on(restore.type, (_, event) => {
return HandshakingState.with({
channels: event.payload.channels,
groups: event.payload.groups,
cursor: event.payload.cursor,
});
});

@@ -7,3 +7,2 @@ /* */

import { del, get, post, patch } from '../networking/modules/nativescript';
import { InternalSetupStruct } from '../core/flow_interfaces';

@@ -10,0 +9,0 @@ export default class extends PubNubCore {

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

import { EndpointDefinition, NetworkingModules } from '../core/flow_interfaces';
export default class {

@@ -10,0 +8,0 @@ _modules;

/* */
import { request as HttpRequest } from 'http';
import { EndpointDefinition, StatusAnnouncement } from '../../core/flow_interfaces';
import { buildUrl } from '../utils';

@@ -6,0 +5,0 @@

/* */
/* global XMLHttpRequest, Ti */
import { EndpointDefinition, StatusAnnouncement } from '../../core/flow_interfaces';
import { buildUrl } from '../utils';

@@ -6,0 +5,0 @@

@@ -172,2 +172,3 @@ import { Given, When, Then, Before } from '@cucumber/cucumber';

const actualFileBuffer = fs.readFileSync(tempFilePath);
//@ts-ignore
expect(actualFileBuffer).to.equalBytes(this.fileDataBuffer);

@@ -174,0 +175,0 @@ fs.unlink(tempFilePath, () => {});

{
"extends": "@tsconfig/node12/tsconfig.json",
"compilerOptions": {
"preserveConstEnums": true,
"noImplicitAny": false,
"outDir": "../../dist/cucumber/"
},
"include": ["**/*"],
"exclude": ["node_modules"]
}
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"experimentalDecorators": true,
"target": "es5",
"sourceMap": true,
"esModuleInterop": true,
"strict": true,
"allowJs": true,
"noEmit": true
},
"exclude": ["../../lib"]
}

@@ -25,3 +25,3 @@ import nock from 'nock';

uuid: 'test-js',
enableSubscribeBeta: true,
enableEventEngine: true,
});

@@ -109,3 +109,3 @@

await forEvent('HANDSHAKING_SUCCESS', 1000);
await forEvent('HANDSHAKE_SUCCESS', 1000);

@@ -117,10 +117,11 @@ pubnub.unsubscribe({ channels: ['test'] });

it('should retry correctly', async () => {
utils.createNock().get('/v2/subscribe/demo/test/0').query(true).reply(200, '{"t":{"t":"12345","r":1}, "m": []}');
utils.createNock().get('/v2/subscribe/demo/test/0').query(true).reply(500, '{"error": true}');
// TODO: retry with configuration
// it('should retry correctly', async () => {
// utils.createNock().get('/v2/subscribe/demo/test/0').query(true).reply(200, '{"t":{"t":"12345","r":1}, "m": []}');
// utils.createNock().get('/v2/subscribe/demo/test/0').query(true).reply(500, '{"error": true}');
pubnub.subscribe({ channels: ['test'] });
// pubnub.subscribe({ channels: ['test'] });
await forState('RECEIVE_RECONNECTING', 1000);
});
// await forState('RECEIVE_RECONNECTING', 1000);
// });
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc