@folklore/socket 0.4.11 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cjs.js +649 -823
  2. package/dist/es.js +649 -813
  3. package/package.json +6 -6
package/dist/es.js CHANGED
@@ -1,825 +1,687 @@
1
- import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
2
- import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
3
- import _defineProperty from '@babel/runtime/helpers/defineProperty';
4
- import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
5
- import _createClass from '@babel/runtime/helpers/createClass';
6
- import _assertThisInitialized from '@babel/runtime/helpers/assertThisInitialized';
7
- import _inherits from '@babel/runtime/helpers/inherits';
8
- import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
9
- import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
10
1
  import createDebug from 'debug';
11
2
  import EventEmitter from 'wolfy87-eventemitter';
12
3
  import invariant from 'invariant';
13
4
  import isFunction from 'lodash/isFunction';
14
5
  import isArray from 'lodash/isArray';
15
6
  import React, { useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
16
- import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
17
7
  import PropTypes from 'prop-types';
18
8
  import { jsx } from 'react/jsx-runtime';
19
9
  import isString from 'lodash/isString';
20
10
 
21
- function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
11
+ const debug$2 = createDebug('folklore:socket:pubnub');
22
12
 
23
- function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
24
-
25
- function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
26
-
27
- function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
28
- var debug$2 = createDebug('folklore:socket:pubnub');
29
-
30
- var PubNubSocket = /*#__PURE__*/function (_EventEmitter) {
31
- _inherits(PubNubSocket, _EventEmitter);
32
-
33
- var _super = _createSuper$2(PubNubSocket);
34
-
35
- function PubNubSocket(opts) {
36
- var _this;
37
-
38
- _classCallCheck(this, PubNubSocket);
39
-
40
- _this = _super.call(this);
41
- _this.options = _objectSpread$4({
13
+ class PubNubSocket extends EventEmitter {
14
+ constructor(opts) {
15
+ super();
16
+ this.options = {
42
17
  uuid: null,
43
18
  publishKey: null,
44
19
  subscribeKey: null,
45
- secretKey: null
46
- }, opts);
47
- _this.onReady = _this.onReady.bind(_assertThisInitialized(_this));
48
- _this.onStatus = _this.onStatus.bind(_assertThisInitialized(_this));
49
- _this.onMessage = _this.onMessage.bind(_assertThisInitialized(_this));
50
- _this.ready = false;
51
- _this.shouldStart = false;
52
- _this.started = false;
53
- _this.starting = false;
54
- _this.PubNub = null;
55
- _this.pubnub = null;
56
- _this.pubnubListener = null;
57
- _this.channels = [];
58
-
59
- _this.init();
60
-
61
- return _this;
20
+ secretKey: null,
21
+ ...opts
22
+ };
23
+ this.onReady = this.onReady.bind(this);
24
+ this.onStatus = this.onStatus.bind(this);
25
+ this.onMessage = this.onMessage.bind(this);
26
+ this.destroyed = false;
27
+ this.ready = false;
28
+ this.shouldStart = false;
29
+ this.started = false;
30
+ this.starting = false;
31
+ this.PubNub = null;
32
+ this.pubnub = null;
33
+ this.pubnubListener = null;
34
+ this.channels = [];
35
+ this.init();
62
36
  }
63
37
 
64
- _createClass(PubNubSocket, [{
65
- key: "onReady",
66
- value: function onReady() {
67
- this.ready = true;
68
- this.emit('ready');
69
- }
70
- }, {
71
- key: "onStatus",
72
- value: function onStatus(statusEvent) {
73
- if (statusEvent.category === 'PNConnectedCategory' && !this.started) {
74
- this.started = true;
75
- this.starting = false;
76
- this.emit('started');
77
- }
78
- }
79
- }, {
80
- key: "onMessage",
81
- value: function onMessage(_ref) {
82
- var message = _ref.message;
83
- this.emit('message', message);
84
-
85
- if (typeof message.event !== 'undefined') {
86
- this.emit(message.event, message.data || message);
87
- }
38
+ onReady() {
39
+ if (this.destroyed) {
40
+ return;
88
41
  }
89
- }, {
90
- key: "updateChannels",
91
- value: function updateChannels(channels) {
92
- debug$2("Updating channels: ".concat(channels.join(', ')));
93
- var shouldStart = this.shouldStart,
94
- started = this.started,
95
- starting = this.starting;
96
-
97
- if (started || starting) {
98
- this.stop();
99
- }
100
42
 
101
- this.channels = channels;
43
+ this.ready = true;
44
+ this.emit('ready');
45
+ }
102
46
 
103
- if (started || starting || shouldStart) {
104
- this.shouldStart = false;
105
- this.start();
106
- }
107
- }
108
- }, {
109
- key: "init",
110
- value: function init() {
111
- var _this2 = this;
112
-
113
- import('pubnub').then(function (_ref2) {
114
- var PubNub = _ref2.default;
115
- _this2.PubNub = PubNub;
116
- }).then(function () {
117
- return _this2.createPubNub();
118
- }).then(function () {
119
- return _this2.onReady();
120
- });
47
+ onStatus(statusEvent) {
48
+ if (statusEvent.category === 'PNConnectedCategory' && !this.started) {
49
+ this.started = true;
50
+ this.starting = false;
51
+ this.emit('started');
121
52
  }
122
- }, {
123
- key: "createPubNub",
124
- value: function createPubNub() {
125
- var PubNub = this.PubNub;
126
- var pubnubOptions = {
127
- publishKey: this.options.publishKey,
128
- subscribeKey: this.options.subscribeKey
129
- };
130
-
131
- if (this.options.uuid !== null) {
132
- pubnubOptions.uuid = this.options.uuid;
133
- }
53
+ }
134
54
 
135
- if (this.options.secretKey !== null) {
136
- pubnubOptions.secretKey = this.options.secretKey;
137
- }
55
+ onMessage(_ref) {
56
+ let {
57
+ message
58
+ } = _ref;
59
+ this.emit('message', message);
138
60
 
139
- this.pubnub = new PubNub(pubnubOptions);
140
- this.pubnubListener = {
141
- status: this.onStatus,
142
- message: this.onMessage
143
- };
144
- this.pubnub.addListener(this.pubnubListener);
61
+ if (typeof message.event !== 'undefined') {
62
+ this.emit(message.event, message.data || message);
145
63
  }
146
- }, {
147
- key: "destroy",
148
- value: function destroy() {
64
+ }
65
+
66
+ updateChannels(channels) {
67
+ debug$2("Updating channels: ".concat(channels.join(', ')));
68
+ const {
69
+ shouldStart,
70
+ started,
71
+ starting
72
+ } = this;
73
+
74
+ if (started || starting) {
149
75
  this.stop();
76
+ }
150
77
 
151
- if (this.pubnubListener) {
152
- this.pubnub.removeListener(this.pubnubListener);
153
- this.pubnubListener = null;
154
- }
78
+ this.channels = channels;
79
+
80
+ if (started || starting || shouldStart) {
81
+ this.shouldStart = false;
82
+ this.start();
83
+ }
84
+ }
155
85
 
156
- this.ready = false;
157
- debug$2('Destroyed.');
86
+ init() {
87
+ if (this.pubnub !== null) {
88
+ return;
158
89
  }
159
- }, {
160
- key: "start",
161
- value: function start() {
162
- if (this.started) {
163
- debug$2('Skipping start: Already started.');
164
- return;
165
- }
166
90
 
167
- if (this.starting) {
168
- debug$2('Skipping start: Already starting.');
169
- return;
170
- }
91
+ debug$2('Init');
92
+ this.destroyed = false;
93
+ const loadPubnub = this.PubNub !== null ? Promise.resolve() : this.loadPubNub();
94
+ loadPubnub.then(() => this.createPubNub()).then(() => this.onReady());
95
+ }
171
96
 
172
- if (this.channels.length === 0) {
173
- debug$2('Skipping start: No channels.');
174
- this.shouldStart = true;
175
- return;
176
- }
97
+ loadPubNub() {
98
+ debug$2('Load PubNub');
99
+ return import('pubnub').then(_ref2 => {
100
+ let {
101
+ default: PubNub
102
+ } = _ref2;
103
+ this.PubNub = PubNub;
104
+ });
105
+ }
177
106
 
178
- this.shouldStart = false;
179
- this.starting = true;
180
- this.pubnub.subscribe({
181
- channels: this.channels
182
- });
183
- this.emit('start');
107
+ createPubNub() {
108
+ if (this.destroyed) {
109
+ return;
184
110
  }
185
- }, {
186
- key: "stop",
187
- value: function stop() {
188
- if (!this.started && !this.starting) {
189
- return;
190
- }
191
111
 
192
- debug$2('Stopping...');
193
- this.shouldStart = false;
194
- this.started = false;
195
- this.starting = false;
196
- this.pubnub.unsubscribe({
197
- channels: this.channels
198
- });
199
- this.emit('stop');
112
+ const {
113
+ PubNub
114
+ } = this;
115
+ const pubnubOptions = {
116
+ publishKey: this.options.publishKey,
117
+ subscribeKey: this.options.subscribeKey
118
+ };
119
+
120
+ if (this.options.uuid !== null) {
121
+ pubnubOptions.uuid = this.options.uuid;
200
122
  }
201
- }, {
202
- key: "send",
203
- value: function send(data) {
204
- var _this3 = this;
205
-
206
- debug$2('Sending', data);
207
- return new Promise(function (resolve, reject) {
208
- _this3.pubnub.publish(data, function (status, response) {
209
- if (status.error) {
210
- reject(new Error("Error operation:".concat(status.operation, " status:").concat(status.statusCode)));
211
- } else {
212
- resolve({
213
- status: status,
214
- response: response,
215
- data: data
216
- });
217
- }
218
- });
219
- });
123
+
124
+ if (this.options.secretKey !== null) {
125
+ pubnubOptions.secretKey = this.options.secretKey;
220
126
  }
221
- }]);
222
127
 
223
- return PubNubSocket;
224
- }(EventEmitter);
128
+ this.pubnub = new PubNub(pubnubOptions);
129
+ this.pubnubListener = {
130
+ status: this.onStatus,
131
+ message: this.onMessage
132
+ };
133
+ this.pubnub.addListener(this.pubnubListener);
134
+ }
225
135
 
226
- var _excluded$1 = ["host"];
136
+ destroy() {
137
+ this.destroyed = true;
138
+ this.stop();
227
139
 
228
- function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
140
+ if (this.pubnubListener) {
141
+ this.pubnub.removeListener(this.pubnubListener);
142
+ this.pubnubListener = null;
143
+ }
229
144
 
230
- function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
145
+ this.pubnub = null;
146
+ this.ready = false;
147
+ debug$2('Destroyed.');
148
+ }
231
149
 
232
- function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
150
+ start() {
151
+ if (this.started) {
152
+ debug$2('Skipping start: Already started.');
153
+ return;
154
+ }
233
155
 
234
- function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
235
- var debug$1 = createDebug('folklore:socket:socketio');
156
+ if (this.starting) {
157
+ debug$2('Skipping start: Already starting.');
158
+ return;
159
+ }
236
160
 
237
- var SocketIOSocket = /*#__PURE__*/function (_EventEmitter) {
238
- _inherits(SocketIOSocket, _EventEmitter);
161
+ if (this.channels.length === 0) {
162
+ debug$2('Skipping start: No channels.');
163
+ this.shouldStart = true;
164
+ return;
165
+ }
239
166
 
240
- var _super = _createSuper$1(SocketIOSocket);
167
+ this.shouldStart = false;
168
+ this.starting = true;
169
+ this.pubnub.subscribe({
170
+ channels: this.channels
171
+ });
172
+ this.emit('start');
173
+ }
241
174
 
242
- function SocketIOSocket(opts) {
243
- var _this;
175
+ stop() {
176
+ if (!this.started && !this.starting) {
177
+ return;
178
+ }
244
179
 
245
- _classCallCheck(this, SocketIOSocket);
180
+ debug$2('Stopping...');
181
+ this.shouldStart = false;
182
+ this.started = false;
183
+ this.starting = false;
184
+ this.pubnub.unsubscribe({
185
+ channels: this.channels
186
+ });
187
+ this.emit('stop');
188
+ }
246
189
 
247
- _this = _super.call(this);
248
- _this.options = _objectSpread$3({
190
+ send(data) {
191
+ debug$2('Sending', data);
192
+ return new Promise((resolve, reject) => {
193
+ this.pubnub.publish(data, (status, response) => {
194
+ if (status.error) {
195
+ reject(new Error("Error operation:".concat(status.operation, " status:").concat(status.statusCode)));
196
+ } else {
197
+ resolve({
198
+ status,
199
+ response,
200
+ data
201
+ });
202
+ }
203
+ });
204
+ });
205
+ }
206
+
207
+ }
208
+
209
+ const debug$1 = createDebug('folklore:socket:socketio');
210
+
211
+ class SocketIOSocket extends EventEmitter {
212
+ constructor(opts) {
213
+ super();
214
+ this.options = {
249
215
  uuid: null,
250
216
  host: 'http://127.0.0.1',
251
217
  path: null,
252
- query: null
253
- }, opts);
254
- _this.onReady = _this.onReady.bind(_assertThisInitialized(_this));
255
- _this.onConnect = _this.onConnect.bind(_assertThisInitialized(_this));
256
- _this.onMessage = _this.onMessage.bind(_assertThisInitialized(_this));
257
- _this.ready = false;
258
- _this.shouldStart = false;
259
- _this.started = false;
260
- _this.starting = false;
261
- _this.Manager = null;
262
- _this.io = null;
263
- _this.sockets = {};
264
- _this.channels = [];
265
-
266
- _this.init();
267
-
268
- return _this;
218
+ query: null,
219
+ ...opts
220
+ };
221
+ this.onReady = this.onReady.bind(this);
222
+ this.onConnect = this.onConnect.bind(this);
223
+ this.onMessage = this.onMessage.bind(this);
224
+ this.ready = false;
225
+ this.shouldStart = false;
226
+ this.started = false;
227
+ this.starting = false;
228
+ this.Manager = null;
229
+ this.io = null;
230
+ this.sockets = {};
231
+ this.channels = [];
232
+ this.init();
269
233
  }
270
234
 
271
- _createClass(SocketIOSocket, [{
272
- key: "onReady",
273
- value: function onReady() {
274
- this.ready = true;
275
- this.emit('ready');
276
- }
277
- }, {
278
- key: "onConnect",
279
- value: function onConnect(channel) {
280
- debug$1('Socket connected on %s', channel);
281
-
282
- if (!this.started) {
283
- this.started = true;
284
- this.starting = false;
285
- this.emit('started');
286
- }
287
- }
288
- }, {
289
- key: "onMessage",
290
- value: function onMessage(message, channel) {
291
- debug$1('Message received on %s %o', channel, message);
292
- this.emit('message', message, channel);
293
- }
294
- }, {
295
- key: "init",
296
- value: function init() {
297
- var _this2 = this;
298
-
299
- import('socket.io-client').then(function (_ref) {
300
- var IO = _ref.default;
301
- _this2.Manager = IO.Manager;
302
- }).then(function () {
303
- return _this2.createManager();
304
- }).then(function () {
305
- return _this2.onReady();
306
- }).then(function () {
307
- if (_this2.shouldStart) {
308
- _this2.start();
309
- }
310
- });
311
- }
312
- }, {
313
- key: "createManager",
314
- value: function createManager() {
315
- var Manager = this.Manager;
316
-
317
- var _this$options = this.options,
318
- host = _this$options.host,
319
- opts = _objectWithoutProperties(_this$options, _excluded$1);
320
-
321
- this.io = new Manager(host, _objectSpread$3({
322
- autoConnect: false
323
- }, opts));
235
+ onReady() {
236
+ this.ready = true;
237
+ this.emit('ready');
238
+ }
239
+
240
+ onConnect(channel) {
241
+ debug$1('Socket connected on %s', channel);
242
+
243
+ if (!this.started) {
244
+ this.started = true;
245
+ this.starting = false;
246
+ this.emit('started');
324
247
  }
325
- }, {
326
- key: "updateChannels",
327
- value: function updateChannels(channels) {
328
- debug$1("Updating channels: ".concat(channels.join(', ')));
329
- var shouldStart = this.shouldStart,
330
- started = this.started,
331
- starting = this.starting;
332
-
333
- if (started || starting) {
334
- this.stop();
335
- }
248
+ }
336
249
 
337
- this.channels = channels;
250
+ onMessage(message, channel) {
251
+ debug$1('Message received on %s %o', channel, message);
252
+ this.emit('message', message, channel);
253
+ }
338
254
 
339
- if (started || starting || shouldStart) {
255
+ init() {
256
+ import('socket.io-client').then(_ref => {
257
+ let {
258
+ default: IO
259
+ } = _ref;
260
+ this.Manager = IO.Manager;
261
+ }).then(() => this.createManager()).then(() => this.onReady()).then(() => {
262
+ if (this.shouldStart) {
340
263
  this.start();
341
264
  }
342
- }
343
- }, {
344
- key: "start",
345
- value: function start() {
346
- var _this3 = this;
347
-
348
- if (this.started) {
349
- debug$1('Skipping start: Already started.');
350
- return;
351
- }
265
+ });
266
+ }
352
267
 
353
- if (this.starting) {
354
- debug$1('Skipping start: Already starting.');
355
- return;
356
- }
268
+ createManager() {
269
+ const {
270
+ Manager
271
+ } = this;
272
+ const {
273
+ host,
274
+ ...opts
275
+ } = this.options;
276
+ this.io = new Manager(host, {
277
+ autoConnect: false,
278
+ ...opts
279
+ });
280
+ }
357
281
 
358
- if (this.io === null) {
359
- debug$1('Socket.io not ready.');
360
- this.shouldStart = true;
361
- return;
362
- }
282
+ updateChannels(channels) {
283
+ debug$1("Updating channels: ".concat(channels.join(', ')));
284
+ const {
285
+ shouldStart,
286
+ started,
287
+ starting
288
+ } = this;
363
289
 
364
- if (this.channels.length === 0) {
365
- debug$1('Skipping start: No channels.');
366
- this.shouldStart = true;
367
- return;
368
- }
290
+ if (started || starting) {
291
+ this.stop();
292
+ }
369
293
 
370
- this.shouldStart = false;
371
- this.starting = true;
372
- this.sockets = this.channels.reduce(function (map, channel) {
373
- return _objectSpread$3(_objectSpread$3({}, map), {}, _defineProperty({}, channel, _this3.createSocket(channel)));
374
- }, {});
375
- this.emit('start');
294
+ this.channels = channels;
295
+
296
+ if (started || starting || shouldStart) {
297
+ this.start();
376
298
  }
377
- }, {
378
- key: "stop",
379
- value: function stop() {
380
- var _this4 = this;
299
+ }
381
300
 
382
- if (!this.started && !this.starting) {
383
- return;
384
- }
301
+ start() {
302
+ if (this.started) {
303
+ debug$1('Skipping start: Already started.');
304
+ return;
305
+ }
385
306
 
386
- debug$1('Stopping...');
387
- this.shouldStart = false;
388
- this.started = false;
389
- this.starting = false;
390
- Object.values(this.sockets).forEach(function (socket) {
391
- return _this4.stopSocket(socket);
392
- });
393
- this.emit('stop');
307
+ if (this.starting) {
308
+ debug$1('Skipping start: Already starting.');
309
+ return;
394
310
  }
395
- }, {
396
- key: "createSocket",
397
- value: function createSocket(channel) {
398
- var _this5 = this;
399
-
400
- var socket = this.io.socket("/".concat(channel.replace(/^\//, '')));
401
- socket.on('message', function (message) {
402
- return _this5.onMessage(message, channel);
403
- });
404
- socket.on('connect', function () {
405
- return _this5.onConnect(channel);
406
- });
407
- socket.open();
408
- return socket;
409
- } // eslint-disable-next-line class-methods-use-this
410
-
411
- }, {
412
- key: "stopSocket",
413
- value: function stopSocket(socket) {
414
- socket.off('connect');
415
- socket.off('message');
416
- socket.close();
417
- return socket;
311
+
312
+ if (this.io === null) {
313
+ debug$1('Socket.io not ready.');
314
+ this.shouldStart = true;
315
+ return;
418
316
  }
419
- }, {
420
- key: "destroy",
421
- value: function destroy() {
422
- this.stop();
423
- this.sockets = {};
424
317
 
425
- if (this.io !== null) {
426
- this.io.close();
427
- this.io = null;
428
- }
318
+ if (this.channels.length === 0) {
319
+ debug$1('Skipping start: No channels.');
320
+ this.shouldStart = true;
321
+ return;
429
322
  }
430
- }, {
431
- key: "send",
432
- value: function send(data) {
433
- var _this6 = this;
434
-
435
- var channel = data.channel,
436
- message = data.message;
437
- var channels = !isArray(channel) ? [channel] : channel;
438
- channels.forEach(function (ch) {
439
- _this6.sockets[ch].send(message);
440
- });
441
- return Promise.resolve();
323
+
324
+ this.shouldStart = false;
325
+ this.starting = true;
326
+ this.sockets = this.channels.reduce((map, channel) => ({ ...map,
327
+ [channel]: this.createSocket(channel)
328
+ }), {});
329
+ this.emit('start');
330
+ }
331
+
332
+ stop() {
333
+ if (!this.started && !this.starting) {
334
+ return;
442
335
  }
443
- }]);
444
336
 
445
- return SocketIOSocket;
446
- }(EventEmitter);
337
+ debug$1('Stopping...');
338
+ this.shouldStart = false;
339
+ this.started = false;
340
+ this.starting = false;
341
+ Object.values(this.sockets).forEach(socket => this.stopSocket(socket));
342
+ this.emit('stop');
343
+ }
447
344
 
448
- var SocketAdapters = {
449
- PubNub: PubNubSocket,
450
- SocketIO: SocketIOSocket
451
- };
345
+ createSocket(channel) {
346
+ const socket = this.io.socket("/".concat(channel.replace(/^\//, '')));
347
+ socket.on('message', message => this.onMessage(message, channel));
348
+ socket.on('connect', () => this.onConnect(channel));
349
+ socket.open();
350
+ return socket;
351
+ } // eslint-disable-next-line class-methods-use-this
452
352
 
453
- var _excluded = ["adapter", "channels"];
454
353
 
455
- function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
354
+ stopSocket(socket) {
355
+ socket.off('connect');
356
+ socket.off('message');
357
+ socket.close();
358
+ return socket;
359
+ }
456
360
 
457
- function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
361
+ destroy() {
362
+ this.stop();
363
+ this.sockets = {};
458
364
 
459
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
365
+ if (this.io !== null) {
366
+ this.io.close();
367
+ this.io = null;
368
+ }
369
+ }
460
370
 
461
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
371
+ send(data) {
372
+ const {
373
+ channel,
374
+ message
375
+ } = data;
376
+ const channels = !isArray(channel) ? [channel] : channel;
377
+ channels.forEach(ch => {
378
+ this.sockets[ch].send(message);
379
+ });
380
+ return Promise.resolve();
381
+ }
462
382
 
463
- var normalize = function normalize(str) {
464
- return str.replace(/[^a-z0-9]+/gi, '').toLowerCase();
383
+ }
384
+
385
+ var SocketAdapters = {
386
+ PubNub: PubNubSocket,
387
+ SocketIO: SocketIOSocket
465
388
  };
466
389
 
467
- var debug = createDebug('folklore:socket');
390
+ const normalize = str => str.replace(/[^a-z0-9]+/gi, '').toLowerCase();
391
+
392
+ const debug = createDebug('folklore:socket');
393
+
394
+ class Socket extends EventEmitter {
395
+ static getAdapters() {
396
+ return Socket.adapters;
397
+ }
398
+
399
+ static getAdapter(adapter) {
400
+ // prettier-ignore
401
+ const adapterKey = Object.keys(Socket.adapters).find(key => normalize(key) === normalize(adapter)) || null;
468
402
 
469
- var Socket = /*#__PURE__*/function (_EventEmitter) {
470
- _inherits(Socket, _EventEmitter);
403
+ if (adapterKey === null) {
404
+ throw new Error("Adapter ".concat(adapter, " not found"));
405
+ }
471
406
 
472
- var _super = _createSuper(Socket);
407
+ return Socket.adapters[adapterKey];
408
+ }
473
409
 
474
- function Socket(opts) {
475
- var _this;
410
+ static addAdapter(name, adapter) {
411
+ Socket.adapters = { ...Socket.adapters,
412
+ [name]: adapter
413
+ };
414
+ return Socket;
415
+ }
476
416
 
477
- _classCallCheck(this, Socket);
417
+ static setAdapters(adapters) {
418
+ Socket.adapters = adapters;
419
+ return Socket;
420
+ }
478
421
 
479
- _this = _super.call(this);
480
- _this.options = _objectSpread$2({
422
+ constructor(opts) {
423
+ super();
424
+ this.options = {
481
425
  adapter: 'pubnub',
482
426
  namespace: null,
483
427
  uuid: null,
484
428
  publishKey: null,
485
429
  subscribeKey: null,
486
430
  secretKey: null,
487
- channels: []
488
- }, opts);
489
- _this.onAdapterReady = _this.onAdapterReady.bind(_assertThisInitialized(_this));
490
- _this.onAdapterStart = _this.onAdapterStart.bind(_assertThisInitialized(_this));
491
- _this.onAdapterStarted = _this.onAdapterStarted.bind(_assertThisInitialized(_this));
492
- _this.onAdapterMessage = _this.onAdapterMessage.bind(_assertThisInitialized(_this));
493
- _this.onAdapterStop = _this.onAdapterStop.bind(_assertThisInitialized(_this));
494
- _this.shouldStart = false;
495
- _this.started = false;
496
- _this.starting = false;
497
- _this.ready = false;
498
- _this.adapter = null;
499
- _this.channels = [];
500
-
501
- _this.init();
502
-
503
- if (_this.options.channels.length) {
504
- _this.setChannels(_this.options.channels);
431
+ channels: [],
432
+ ...opts
433
+ };
434
+ this.onAdapterReady = this.onAdapterReady.bind(this);
435
+ this.onAdapterStart = this.onAdapterStart.bind(this);
436
+ this.onAdapterStarted = this.onAdapterStarted.bind(this);
437
+ this.onAdapterMessage = this.onAdapterMessage.bind(this);
438
+ this.onAdapterStop = this.onAdapterStop.bind(this);
439
+ this.shouldStart = false;
440
+ this.started = false;
441
+ this.starting = false;
442
+ this.ready = false;
443
+ this.adapter = null;
444
+ this.channels = [];
445
+ this.init();
446
+
447
+ if (this.options.channels.length) {
448
+ this.setChannels(this.options.channels);
505
449
  }
506
-
507
- return _this;
508
450
  }
509
451
 
510
- _createClass(Socket, [{
511
- key: "onAdapterReady",
512
- value: function onAdapterReady() {
513
- debug('Adapter ready');
514
- this.ready = true;
515
- this.emit('ready');
452
+ onAdapterReady() {
453
+ debug('Adapter ready');
454
+ this.ready = true;
455
+ this.emit('ready');
516
456
 
517
- if (this.shouldStart) {
518
- this.shouldStart = false;
519
- this.start();
520
- }
521
- }
522
- }, {
523
- key: "onAdapterStart",
524
- value: function onAdapterStart() {
525
- debug('Adapter starting...');
526
- this.starting = true;
527
- this.started = false;
528
- this.emit('start');
529
- }
530
- }, {
531
- key: "onAdapterStarted",
532
- value: function onAdapterStarted() {
533
- debug('Adapter started');
534
- this.starting = false;
535
- this.started = true;
536
- this.emit('started');
537
- }
538
- }, {
539
- key: "onAdapterStop",
540
- value: function onAdapterStop() {
541
- debug('Adapter stopped');
542
- this.starting = false;
543
- this.started = false;
544
- this.emit('stop');
545
- }
546
- }, {
547
- key: "onAdapterMessage",
548
- value: function onAdapterMessage(message) {
549
- debug('Adapter message', message);
550
- this.emit('message', message);
457
+ if (this.shouldStart) {
458
+ this.shouldStart = false;
459
+ this.start();
551
460
  }
552
- }, {
553
- key: "getChannelWithoutNamespace",
554
- value: function getChannelWithoutNamespace(name) {
555
- if (this.options.namespace === null) {
556
- return name;
557
- }
461
+ }
558
462
 
559
- var regExp = new RegExp("^".concat(this.options.namespace, ":"));
560
- return name.replace(regExp, '');
561
- }
562
- }, {
563
- key: "getChannelWithNamespace",
564
- value: function getChannelWithNamespace(name) {
565
- var parts = [];
463
+ onAdapterStart() {
464
+ debug('Adapter starting...');
465
+ this.starting = true;
466
+ this.started = false;
467
+ this.emit('start');
468
+ }
566
469
 
567
- if (this.options.namespace !== null) {
568
- parts.push(this.options.namespace);
569
- }
470
+ onAdapterStarted() {
471
+ debug('Adapter started');
472
+ this.starting = false;
473
+ this.started = true;
474
+ this.emit('started');
475
+ }
476
+
477
+ onAdapterStop() {
478
+ debug('Adapter stopped');
479
+ this.starting = false;
480
+ this.started = false;
481
+ this.emit('stop');
482
+ }
570
483
 
571
- parts.push(name);
572
- return parts.join(':');
484
+ onAdapterMessage(message) {
485
+ debug('Adapter message', message);
486
+ this.emit('message', message);
487
+ }
488
+
489
+ getChannelWithoutNamespace(name) {
490
+ if (this.options.namespace === null) {
491
+ return name;
573
492
  }
574
- }, {
575
- key: "setChannels",
576
- value: function setChannels(channels) {
577
- var _this2 = this;
578
493
 
579
- var namespacedChannels = channels.map(function (channel) {
580
- return _this2.getChannelWithNamespace(channel);
581
- }).sort();
494
+ const regExp = new RegExp("^".concat(this.options.namespace, ":"));
495
+ return name.replace(regExp, '');
496
+ }
582
497
 
583
- if (this.channels.join(',') === namespacedChannels.join(',')) {
584
- return;
585
- }
498
+ getChannelWithNamespace(name) {
499
+ const parts = [];
586
500
 
587
- debug("Set channels: ".concat(namespacedChannels.join(', ')));
588
- this.updateChannels(namespacedChannels);
501
+ if (this.options.namespace !== null) {
502
+ parts.push(this.options.namespace);
589
503
  }
590
- }, {
591
- key: "addChannel",
592
- value: function addChannel(channel) {
593
- var namespacedChannel = this.getChannelWithNamespace(channel);
594
504
 
595
- if (this.channels.indexOf(namespacedChannel) !== -1) {
596
- return;
597
- }
505
+ parts.push(name);
506
+ return parts.join(':');
507
+ }
598
508
 
599
- debug("Adding channel: ".concat(channel));
600
- this.updateChannels([].concat(_toConsumableArray(this.channels), [namespacedChannel]));
601
- }
602
- }, {
603
- key: "addChannels",
604
- value: function addChannels(channels) {
605
- var _this3 = this;
606
-
607
- var namespacedChannels = channels.map(function (channel) {
608
- return _this3.getChannelWithNamespace(channel);
609
- }).sort();
610
- debug("Adding channels: ".concat(channels.join(',')));
611
- this.updateChannels([].concat(_toConsumableArray(this.channels), _toConsumableArray(namespacedChannels.filter(function (it) {
612
- return _this3.channels.indexOf(it) === -1;
613
- }))));
509
+ setChannels(channels) {
510
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
511
+
512
+ if (this.channels.join(',') === namespacedChannels.join(',')) {
513
+ return;
614
514
  }
615
- }, {
616
- key: "removeChannel",
617
- value: function removeChannel(channel) {
618
- var namespacedChannel = this.getChannelWithNamespace(channel);
619
515
 
620
- if (this.channels.indexOf(namespacedChannel) === -1) {
621
- return;
622
- }
516
+ debug("Set channels: ".concat(namespacedChannels.join(', ')));
517
+ this.updateChannels(namespacedChannels);
518
+ }
623
519
 
624
- debug("Removing channel: ".concat(channel));
625
- this.updateChannels(this.channels.filter(function (ch) {
626
- return ch !== namespacedChannel;
627
- }));
628
- }
629
- }, {
630
- key: "removeChannels",
631
- value: function removeChannels(channels) {
632
- var _this4 = this;
633
-
634
- var namespacedChannels = channels.map(function (channel) {
635
- return _this4.getChannelWithNamespace(channel);
636
- }).sort();
637
- debug("Removing channels: ".concat(channels.join(',')));
638
- this.updateChannels(this.channels.filter(function (it) {
639
- return namespacedChannels.indexOf(it) === -1;
640
- }));
641
- }
642
- }, {
643
- key: "updateChannels",
644
- value: function updateChannels(channels) {
645
- var sortedChannels = channels.sort();
646
- debug("Updating channels: ".concat(sortedChannels.join(', ')));
647
- this.channels = _toConsumableArray(sortedChannels);
648
-
649
- if (this.adapter !== null) {
650
- this.adapter.updateChannels(sortedChannels);
651
- }
652
- }
653
- }, {
654
- key: "hasChannel",
655
- value: function hasChannel(channel) {
656
- var namespacedChannel = this.getChannelWithNamespace(channel);
657
- return this.channels.reduce(function (found, it) {
658
- return found || it === namespacedChannel;
659
- }, false);
660
- }
661
- }, {
662
- key: "getChannels",
663
- value: function getChannels() {
664
- var _this5 = this;
520
+ addChannel(channel) {
521
+ const namespacedChannel = this.getChannelWithNamespace(channel);
665
522
 
666
- return this.channels.map(function (channel) {
667
- return _this5.getChannelWithoutNamespace(channel);
668
- });
523
+ if (this.channels.indexOf(namespacedChannel) !== -1) {
524
+ return;
669
525
  }
670
- }, {
671
- key: "init",
672
- value: function init() {
673
- var _this6 = this;
674
-
675
- var _this$options = this.options,
676
- adapterKey = _this$options.adapter;
677
- _this$options.channels;
678
- var adapterOptions = _objectWithoutProperties(_this$options, _excluded);
679
-
680
- var SocketAdapter = Socket.getAdapter(adapterKey);
681
- this.adapter = new SocketAdapter(adapterOptions);
682
- var methods = ['start', 'stop', 'destroy', 'updateChannels', 'send'];
683
- methods.forEach(function (method) {
684
- invariant(isFunction(_this6.adapter[method] || null), "Socket adapter should implement method ".concat(method));
685
- });
686
- this.adapter.on('ready', this.onAdapterReady);
687
- this.adapter.on('start', this.onAdapterStart);
688
- this.adapter.on('started', this.onAdapterStarted);
689
- this.adapter.on('message', this.onAdapterMessage);
690
- this.adapter.on('stop', this.onAdapterStop);
691
- }
692
- }, {
693
- key: "destroy",
694
- value: function destroy() {
695
- if (this.adapter !== null) {
696
- this.adapter.removeAllListeners();
697
- this.adapter.destroy();
698
- this.adapter = null;
699
- }
700
526
 
701
- this.started = false;
702
- this.starting = false;
703
- this.ready = false;
704
- debug('Destroyed.');
705
- }
706
- }, {
707
- key: "restart",
708
- value: function restart() {
709
- this.stop();
710
- this.start();
527
+ debug("Adding channel: ".concat(channel));
528
+ this.updateChannels([...this.channels, namespacedChannel]);
529
+ }
530
+
531
+ addChannels(channels) {
532
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
533
+ debug("Adding channels: ".concat(channels.join(',')));
534
+ this.updateChannels([...this.channels, ...namespacedChannels.filter(it => this.channels.indexOf(it) === -1)]);
535
+ }
536
+
537
+ removeChannel(channel) {
538
+ const namespacedChannel = this.getChannelWithNamespace(channel);
539
+
540
+ if (this.channels.indexOf(namespacedChannel) === -1) {
541
+ return;
711
542
  }
712
- }, {
713
- key: "start",
714
- value: function start() {
715
- var _this7 = this;
716
-
717
- if (this.started) {
718
- debug('Skipping start: Already started.');
719
- return;
720
- }
721
543
 
722
- if (this.starting) {
723
- debug('Skipping start: Already starting.');
724
- return;
725
- }
544
+ debug("Removing channel: ".concat(channel));
545
+ this.updateChannels(this.channels.filter(ch => ch !== namespacedChannel));
546
+ }
726
547
 
727
- if (!this.ready) {
728
- debug('Skipping start: No ready.');
729
- this.shouldStart = true;
730
- return;
731
- }
548
+ removeChannels(channels) {
549
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
550
+ debug("Removing channels: ".concat(channels.join(',')));
551
+ this.updateChannels(this.channels.filter(it => namespacedChannels.indexOf(it) === -1));
552
+ }
732
553
 
733
- this.shouldStart = false;
734
- debug('Starting on channels:');
735
- this.channels.forEach(function (channel) {
736
- debug("- ".concat(_this7.getChannelWithoutNamespace(channel)));
737
- });
738
- this.adapter.start();
554
+ updateChannels(channels) {
555
+ const sortedChannels = channels.sort();
556
+ debug("Updating channels: ".concat(sortedChannels.join(', ')));
557
+ this.channels = [...sortedChannels];
558
+
559
+ if (this.adapter !== null) {
560
+ this.adapter.updateChannels(sortedChannels);
739
561
  }
740
- }, {
741
- key: "stop",
742
- value: function stop() {
743
- this.shouldStart = false;
562
+ }
744
563
 
745
- if (!this.started && !this.starting) {
746
- return;
747
- }
564
+ hasChannel(channel) {
565
+ const namespacedChannel = this.getChannelWithNamespace(channel);
566
+ return this.channels.reduce((found, it) => found || it === namespacedChannel, false);
567
+ }
748
568
 
749
- debug('Stopping...');
569
+ getChannels() {
570
+ return this.channels.map(channel => this.getChannelWithoutNamespace(channel));
571
+ }
750
572
 
751
- if (this.adapter !== null) {
752
- this.adapter.stop();
753
- }
573
+ init() {
574
+ if (this.adapter !== null) {
575
+ debug('Already initialized');
576
+ return;
577
+ }
578
+
579
+ debug('Init');
580
+ const {
581
+ adapter: adapterKey,
582
+ channels,
583
+ ...adapterOptions
584
+ } = this.options;
585
+ const SocketAdapter = Socket.getAdapter(adapterKey);
586
+ this.adapter = new SocketAdapter(adapterOptions);
587
+ const methods = ['start', 'stop', 'destroy', 'updateChannels', 'send'];
588
+ methods.forEach(method => {
589
+ invariant(isFunction(this.adapter[method] || null), "Socket adapter should implement method ".concat(method));
590
+ });
591
+ this.adapter.on('ready', this.onAdapterReady);
592
+ this.adapter.on('start', this.onAdapterStart);
593
+ this.adapter.on('started', this.onAdapterStarted);
594
+ this.adapter.on('message', this.onAdapterMessage);
595
+ this.adapter.on('stop', this.onAdapterStop);
596
+ }
597
+
598
+ destroy() {
599
+ if (this.adapter !== null) {
600
+ this.adapter.removeAllListeners();
601
+ this.adapter.destroy();
602
+ this.adapter = null;
754
603
  }
755
- }, {
756
- key: "send",
757
- value: function send(data, channel) {
758
- if (!this.started) {
759
- debug('Abort sending data: Not started');
760
- return Promise.reject();
761
- }
762
604
 
763
- var publishData = typeof data.channel !== 'undefined' && typeof data.message !== 'undefined' ? data : {
764
- channel: typeof channel !== 'undefined' ? this.getChannelWithNamespace(channel) : this.channels,
765
- message: data
766
- };
767
- debug('Sending', publishData);
768
- return this.adapter.send(publishData);
605
+ this.started = false;
606
+ this.starting = false;
607
+ this.ready = false;
608
+ debug('Destroyed.');
609
+ }
610
+
611
+ restart() {
612
+ this.stop();
613
+ this.start();
614
+ }
615
+
616
+ start() {
617
+ if (this.started) {
618
+ debug('Skipping start: Already started.');
619
+ return;
769
620
  }
770
- }, {
771
- key: "isStarted",
772
- value: function isStarted() {
773
- return this.started;
621
+
622
+ if (this.starting) {
623
+ debug('Skipping start: Already starting.');
624
+ return;
774
625
  }
775
- }], [{
776
- key: "getAdapters",
777
- value: function getAdapters() {
778
- return Socket.adapters;
626
+
627
+ if (!this.ready) {
628
+ debug('Skipping start: No ready.');
629
+ this.shouldStart = true;
630
+ return;
779
631
  }
780
- }, {
781
- key: "getAdapter",
782
- value: function getAdapter(adapter) {
783
- // prettier-ignore
784
- var adapterKey = Object.keys(Socket.adapters).find(function (key) {
785
- return normalize(key) === normalize(adapter);
786
- }) || null;
787
-
788
- if (adapterKey === null) {
789
- throw new Error("Adapter ".concat(adapter, " not found"));
790
- }
791
632
 
792
- return Socket.adapters[adapterKey];
633
+ this.shouldStart = false;
634
+ debug('Starting on channels:');
635
+ this.channels.forEach(channel => {
636
+ debug("- ".concat(this.getChannelWithoutNamespace(channel)));
637
+ });
638
+ this.adapter.start();
639
+ }
640
+
641
+ stop() {
642
+ this.shouldStart = false;
643
+
644
+ if (!this.started && !this.starting) {
645
+ return;
793
646
  }
794
- }, {
795
- key: "addAdapter",
796
- value: function addAdapter(name, adapter) {
797
- Socket.adapters = _objectSpread$2(_objectSpread$2({}, Socket.adapters), {}, _defineProperty({}, name, adapter));
798
- return Socket;
647
+
648
+ debug('Stopping...');
649
+
650
+ if (this.adapter !== null) {
651
+ this.adapter.stop();
799
652
  }
800
- }, {
801
- key: "setAdapters",
802
- value: function setAdapters(adapters) {
803
- Socket.adapters = adapters;
804
- return Socket;
653
+ }
654
+
655
+ send(data, channel) {
656
+ if (!this.started) {
657
+ debug('Abort sending data: Not started');
658
+ return Promise.reject();
805
659
  }
806
- }]);
807
660
 
808
- return Socket;
809
- }(EventEmitter);
661
+ const publishData = typeof data.channel !== 'undefined' && typeof data.message !== 'undefined' ? data : {
662
+ channel: typeof channel !== 'undefined' ? this.getChannelWithNamespace(channel) : this.channels,
663
+ message: data
664
+ };
665
+ debug('Sending', publishData);
666
+ return this.adapter.send(publishData);
667
+ }
668
+
669
+ isStarted() {
670
+ return this.started;
671
+ }
672
+
673
+ }
810
674
 
811
- Socket.adapters = _objectSpread$2({}, SocketAdapters);
675
+ Socket.adapters = { ...SocketAdapters
676
+ };
812
677
 
813
- var SocketContext = /*#__PURE__*/React.createContext({
678
+ const SocketContext = /*#__PURE__*/React.createContext({
814
679
  socket: null,
815
- subscribe: function subscribe() {},
816
- unsubscribe: function unsubscribe() {}
680
+ subscribe: () => {},
681
+ unsubscribe: () => {}
817
682
  });
818
683
 
819
- function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
820
-
821
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
822
- var propTypes = {
684
+ const propTypes = {
823
685
  socket: PropTypes.instanceOf(Socket),
824
686
  adapter: PropTypes.string,
825
687
  host: PropTypes.string,
@@ -832,7 +694,7 @@ var propTypes = {
832
694
  autoStart: PropTypes.bool,
833
695
  children: PropTypes.node
834
696
  };
835
- var defaultProps = {
697
+ const defaultProps = {
836
698
  socket: null,
837
699
  adapter: 'pubnub',
838
700
  host: null,
@@ -846,82 +708,73 @@ var defaultProps = {
846
708
  children: null
847
709
  };
848
710
 
849
- var SocketContainer = function SocketContainer(_ref) {
850
- var children = _ref.children,
851
- socket = _ref.socket,
852
- autoStart = _ref.autoStart,
853
- adapter = _ref.adapter,
854
- host = _ref.host,
855
- namespace = _ref.namespace,
856
- uuid = _ref.uuid,
857
- publishKey = _ref.publishKey,
858
- subscribeKey = _ref.subscribeKey,
859
- secretKey = _ref.secretKey,
860
- initialChannels = _ref.channels;
861
- var finalSocket = useMemo(function () {
862
- return socket || new Socket({
863
- adapter: adapter,
864
- host: host,
865
- namespace: namespace,
866
- uuid: uuid,
867
- publishKey: publishKey,
868
- subscribeKey: subscribeKey,
869
- secretKey: secretKey
870
- });
871
- }, [socket, host, adapter, namespace, uuid, publishKey, subscribeKey, secretKey]);
872
-
873
- var _useState = useState([]),
874
- _useState2 = _slicedToArray(_useState, 2),
875
- channels = _useState2[0],
876
- setChannels = _useState2[1];
877
-
878
- var channelsCountRef = useRef({});
879
- var updateChannels = useCallback(function (newChannels) {
711
+ const SocketContainer = function (_ref) {
712
+ let {
713
+ children,
714
+ socket,
715
+ autoStart,
716
+ adapter,
717
+ host,
718
+ namespace,
719
+ uuid,
720
+ publishKey,
721
+ subscribeKey,
722
+ secretKey,
723
+ channels: initialChannels
724
+ } = _ref;
725
+ const finalSocket = useMemo(() => socket || new Socket({
726
+ adapter,
727
+ host,
728
+ namespace,
729
+ uuid,
730
+ publishKey,
731
+ subscribeKey,
732
+ secretKey
733
+ }), [socket, host, adapter, namespace, uuid, publishKey, subscribeKey, secretKey]);
734
+ const [channels, setChannels] = useState([]);
735
+ const channelsCountRef = useRef({});
736
+ const updateChannels = useCallback(newChannels => {
880
737
  finalSocket.setChannels(newChannels);
881
738
  setChannels(newChannels);
882
739
  }, [finalSocket, setChannels]);
883
- var addToChannelsCount = useCallback(function (newChannels) {
884
- channelsCountRef.current = newChannels.reduce(function (map, channel) {
885
- return _objectSpread$1(_objectSpread$1({}, map), {}, _defineProperty({}, channel, (map[channel] || 0) + 1));
886
- }, channelsCountRef.current);
740
+ const addToChannelsCount = useCallback(newChannels => {
741
+ channelsCountRef.current = newChannels.reduce((map, channel) => ({ ...map,
742
+ [channel]: (map[channel] || 0) + 1
743
+ }), channelsCountRef.current);
887
744
  updateChannels(Object.keys(channelsCountRef.current));
888
745
  }, [updateChannels]);
889
- var removeToChannelsCount = useCallback(function (newChannels) {
890
- channelsCountRef.current = newChannels.reduce(function (map, channel) {
891
- var newCount = (map[channel] || 0) - 1;
892
- return newCount > 0 ? _objectSpread$1(_objectSpread$1({}, map), {}, _defineProperty({}, channel, newCount)) : map;
746
+ const removeToChannelsCount = useCallback(newChannels => {
747
+ channelsCountRef.current = newChannels.reduce((map, channel) => {
748
+ const newCount = (map[channel] || 0) - 1;
749
+ return newCount > 0 ? { ...map,
750
+ [channel]: newCount
751
+ } : map;
893
752
  }, channelsCountRef.current);
894
753
  updateChannels(Object.keys(channelsCountRef.current));
895
754
  }, [updateChannels]);
896
- var subscribe = useCallback(function (channelsToAdd) {
897
- return addToChannelsCount(channelsToAdd);
898
- }, [addToChannelsCount]);
899
- var unsubscribe = useCallback(function (channelsToRemove) {
900
- return removeToChannelsCount(channelsToRemove);
901
- }, [removeToChannelsCount]);
902
- useEffect(function () {
755
+ const subscribe = useCallback(channelsToAdd => addToChannelsCount(channelsToAdd), [addToChannelsCount]);
756
+ const unsubscribe = useCallback(channelsToRemove => removeToChannelsCount(channelsToRemove), [removeToChannelsCount]);
757
+ useEffect(() => {
903
758
  subscribe(initialChannels);
904
- return function () {
759
+ return () => {
905
760
  unsubscribe(initialChannels);
906
761
  };
907
762
  }, [initialChannels, subscribe, unsubscribe]);
908
- useEffect(function () {
763
+ useEffect(() => {
909
764
  if (autoStart) {
910
765
  finalSocket.start();
911
766
  }
912
767
 
913
- return function () {
768
+ return () => {
914
769
  finalSocket.destroy();
915
770
  };
916
771
  }, [autoStart, finalSocket]);
917
- var value = useMemo(function () {
918
- return {
919
- socket: finalSocket,
920
- subscribe: subscribe,
921
- unsubscribe: unsubscribe,
922
- channels: channels
923
- };
924
- }, [finalSocket, subscribe]);
772
+ const value = useMemo(() => ({
773
+ socket: finalSocket,
774
+ subscribe,
775
+ unsubscribe,
776
+ channels
777
+ }), [finalSocket, subscribe]);
925
778
  return /*#__PURE__*/jsx(SocketContext.Provider, {
926
779
  value: value,
927
780
  children: children
@@ -931,75 +784,58 @@ var SocketContainer = function SocketContainer(_ref) {
931
784
  SocketContainer.propTypes = propTypes;
932
785
  SocketContainer.defaultProps = defaultProps;
933
786
 
934
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
935
-
936
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
937
-
938
- var getDisplayName = function getDisplayName(WrappedComponent) {
939
- return WrappedComponent.displayName || WrappedComponent.name || 'Component';
940
- };
941
-
942
- var withSocket = function withSocket(WrappedComponent) {
943
- var WithSocketComponent = function WithSocketComponent(props) {
944
- return /*#__PURE__*/jsx(SocketContext.Consumer, {
945
- children: function children(_ref) {
946
- var socket = _ref.socket,
947
- subscribe = _ref.subscribe,
948
- unsubscribe = _ref.unsubscribe;
949
- return /*#__PURE__*/jsx(WrappedComponent, _objectSpread({
950
- socket: socket,
951
- socketSubscribe: subscribe,
952
- socketUnsubscribe: unsubscribe
953
- }, props));
954
- }
955
- });
956
- };
787
+ const getDisplayName = WrappedComponent => WrappedComponent.displayName || WrappedComponent.name || 'Component';
788
+
789
+ const withSocket = WrappedComponent => {
790
+ const WithSocketComponent = props => /*#__PURE__*/jsx(SocketContext.Consumer, {
791
+ children: _ref => {
792
+ let {
793
+ socket,
794
+ subscribe,
795
+ unsubscribe
796
+ } = _ref;
797
+ return /*#__PURE__*/jsx(WrappedComponent, {
798
+ socket: socket,
799
+ socketSubscribe: subscribe,
800
+ socketUnsubscribe: unsubscribe,
801
+ ...props
802
+ });
803
+ }
804
+ });
957
805
 
958
806
  WithSocketComponent.displayName = "WithSocket(".concat(getDisplayName(WrappedComponent), ")");
959
807
  return WithSocketComponent;
960
808
  };
961
809
 
962
- var useSocket = function useSocket() {
963
- var channelNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
964
-
965
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
966
- _ref$socket = _ref.socket,
967
- customSocket = _ref$socket === void 0 ? null : _ref$socket,
968
- _ref$onMessage = _ref.onMessage,
969
- customOnMessage = _ref$onMessage === void 0 ? null : _ref$onMessage;
970
-
971
- var _useContext = useContext(SocketContext),
972
- contextSocket = _useContext.socket,
973
- subscribe = _useContext.subscribe,
974
- unsubscribe = _useContext.unsubscribe;
975
-
976
- var socket = customSocket || contextSocket || null;
977
-
978
- var _useState = useState(socket !== null ? socket.isStarted() : false),
979
- _useState2 = _slicedToArray(_useState, 2),
980
- started = _useState2[0],
981
- setStarted = _useState2[1];
982
-
983
- var channels = isString(channelNames) ? [channelNames] : channelNames;
984
- var channelsKey = (channels || []).sort().join(',');
985
- useEffect(function () {
810
+ const useSocket = function () {
811
+ let channelNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
812
+ let {
813
+ socket: customSocket = null,
814
+ onMessage: customOnMessage = null
815
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
816
+ const {
817
+ socket: contextSocket,
818
+ subscribe,
819
+ unsubscribe
820
+ } = useContext(SocketContext);
821
+ const socket = customSocket || contextSocket || null;
822
+ const [started, setStarted] = useState(socket !== null ? socket.isStarted() : false);
823
+ const channels = isString(channelNames) ? [channelNames] : channelNames;
824
+ const channelsKey = (channels || []).sort().join(',');
825
+ useEffect(() => {
986
826
  if (socket === null) {
987
827
  if (process.env.NODE_ENV !== 'production') {
988
828
  console.warn('Socket context is empty.');
989
829
  }
990
830
 
991
- return function () {};
831
+ return () => {};
992
832
  }
993
833
 
994
- var wasStarted = socket.isStarted();
834
+ const wasStarted = socket.isStarted();
995
835
 
996
- var onStarted = function onStarted() {
997
- return setStarted(true);
998
- };
836
+ const onStarted = () => setStarted(true);
999
837
 
1000
- var onStop = function onStop() {
1001
- return setStarted(false);
1002
- };
838
+ const onStop = () => setStarted(false);
1003
839
 
1004
840
  socket.on('stop', onStop);
1005
841
  socket.on('started', onStarted);
@@ -1012,7 +848,7 @@ var useSocket = function useSocket() {
1012
848
  socket.start();
1013
849
  }
1014
850
 
1015
- return function () {
851
+ return () => {
1016
852
  socket.off('stop', onStop);
1017
853
  socket.off('started', onStarted);
1018
854
 
@@ -1025,27 +861,27 @@ var useSocket = function useSocket() {
1025
861
  }
1026
862
  };
1027
863
  }, [channelsKey, customSocket]);
1028
- useEffect(function () {
864
+ useEffect(() => {
1029
865
  if (socket === null) {
1030
- return function () {};
866
+ return () => {};
1031
867
  }
1032
868
 
1033
- var onMessage = function onMessage() {
869
+ const onMessage = function () {
1034
870
  if (customOnMessage !== null) {
1035
- customOnMessage.apply(void 0, arguments);
871
+ customOnMessage(...arguments);
1036
872
  }
1037
873
  };
1038
874
 
1039
875
  socket.on('message', onMessage);
1040
- return function () {
876
+ return () => {
1041
877
  socket.off('message', onMessage);
1042
878
  };
1043
879
  }, [customOnMessage]);
1044
880
  return {
1045
- socket: socket,
1046
- started: started,
1047
- subscribe: subscribe,
1048
- unsubscribe: unsubscribe
881
+ socket,
882
+ started,
883
+ subscribe,
884
+ unsubscribe
1049
885
  };
1050
886
  };
1051
887