-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
524 lines (462 loc) · 12.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import EventEmitter from 'eventemitter3';
import ShareJS from './vendor/share';
const ABNORMAL = 1006;
const NORMAL = 1000;
const NOT_FOUND = 4040;
const UNAUTHORIZED = 4010;
const LOCAL_TIMEOUT = 4011;
/**
* A two-element array consisting of a length of text to retain and a string to
* insert
*
* @example
* [10, "Foo"]
*
* @typedef {Array<(number|string)>} ShareJSWrapper~Insert
*/
/**
* A two-element array consisting of a length of text to retain and a length of
* text to remove
*
* @example
* [10, 12]
*
* @typedef {Array<number>} ShareJSWrapper~Remove
*/
/**
* @class ShareJSWrapper
* @classdesc A wrapper around a
* [ShareJS](https://github.com/share/ShareJS/tree/v0.7.40) client, providing
* easier use for a single document per connection
*
* @param {Object} config An object of configuration options for this client
* @param {string} config.accessToken A Canvas API authentication token
* @param {string} config.canvasID An ID of a Canvas to connect to
* @param {string} config.realtimeURL The URL of the realtime server
* @param {string} config.orgID The ID of the org the canvas belongs to
* @param {string} config.debug Whether to ignore or log internal log calls
*/
export default class ShareJSWrapper {
constructor(config) { // eslint-disable-line require-jsdoc
this.config = config;
this.eventEmitter = new EventEmitter();
}
/**
* A callback called on successful connection after a `connect` call
*
* @callback ShareJSWrapper~connectCallback
*/
/**
* Tell the wrapper client to connect to the configured ShareJS server.
*
* @example
* share.connect(function onConnected() {
* console.log(share.content);
* });
*
* @param {ShareJSWrapper~connectCallback} callback A callback to call once
* connected
* @param {Boolean} isReconnect Whether this connect call is a reconnect,
* meaning ShareJS event handlers need not be re-bound and the context
* already exists
*/
connect(callback, isReconnect) {
const { canvasID, orgID, realtimeURL } = this.config;
this.socket = new WebSocket(realtimeURL);
this.connection = this.getShareJSConnection();
if (isReconnect) {
return;
}
this.bindConnectionEvents();
this.document = this.connection.get(orgID, canvasID);
this.document.subscribe();
this.document.whenReady(_ => {
this.debug('whenReady');
if (!this.document.type) {
this.document.create('text');
}
this.context = this.getDocumentContext();
this.context.onInsert = bind(this, 'onRemoteOperation');
this.context.onRemove = bind(this, 'onRemoteOperation');
/**
* The current content of the ShareJS document
*
* @type {string}
*/
this.content = this.context.get();
if (callback) {
callback();
}
});
}
/**
* Tell the wrapper client to close the ShareJS connection and socket.
*
* @example
* share.disconnect();
*/
disconnect() {
this.socket.close();
}
/**
* Send an insert operation from this client to the server.
*
* @example
* share.insert(10, 'Foo');
*
* @param {number} offset The offset at which to start the insert operation
* @param {string} text The text to be inserted
*/
insert(offset, text) {
this.debug(_ => {
return ['insert', {
content: this.context.get(),
op: [offset, text]
}];
});
this.context.insert(offset, text);
this.content = this.context.get();
}
/**
* Add a listener to an event.
*
* @example
* share.on('connect', function onConnect() {
* // ...
* });
*
* @param {string} event The name of the event
* @param {function} fn The function to call when the event occurs
* @param {*} context The context on which to call the function
* @return {ShareJSWrapper} This same instance
*/
on(event, fn, context) {
this.eventEmitter.on(event, fn, context);
return this;
}
/**
* Add a listener to an event which will fire once.
*
* @example
* share.once('connect', function onConnect() {
* // ...
* });
*
* @param {string} event The name of the event
* @param {function} fn The function to call when the event occurs
* @param {*} context The context on which to call the function
* @return {ShareJSWrapper} This same instance
*/
once(event, fn, context) {
this.eventEmitter.once(event, fn, context);
return this;
}
/**
* Send a remove operation from this client to the server.
*
* @example
* share.remove(0, 3);
*
* @param {number} start The position at which to start the remove
* @param {number} length The number of characters to remove
*/
remove(start, length) {
this.debug(_ => {
return ['remove', {
content: this.context.get(),
op: [start, length]
}];
});
this.context.remove(start, length);
this.content = this.context.get();
}
/**
* Remove all listeners or only for the specified event.
*
* @example
* share.removeAllListeners();
*
* @param {string} [event] The event to remove all listeners for
* @return {ShareJSWrapper} This same instance
*/
removeAllListeners(event) {
this.eventEmitter.removeAllListeners(event);
return this;
}
/**
* Remove a listener from an event.
*
* @example
* share.removeListener('connect', connectHandler, this, true);
*
* @param {string} event The event to remove listener(s) from
* @param {function} [fn] The listener to remove
* @param {*} [context] Only match listeners matching this context
* @param {boolean} once Only remove "once" listeners
* @return {ShareJSWrapper} This same instance
*/
removeListener(event, fn, context, once) {
this.eventEmitter.removeListener(event, fn, context, once);
return this;
}
/**
* Bind to events on the connection and handle them.
*
* @private
*/
bindConnectionEvents() {
this.connection.on('connected', bind(this, 'onConnectionConnected'));
this.connection.on('disconnected', bind(this, 'onConnectionDisconnected'));
}
/**
* Get an editing context for the ShareJS document.
*
* @private
* @return {ShareJS.Context} A ShareJS editing context
*/
getDocumentContext() {
const context = this.document.createContext();
if (!context.provides.text) {
throw new Error('Cannot attach to a non-text document');
}
context.detach = null;
return context;
}
/**
* Get a new ShareJS connection for this wrapper client.
*
* @private
* @return {ShareJS.Connection} A ShareJS connection object
*/
getShareJSConnection() {
let connection = this.connection;
if (connection) {
connection.bindToSocket(this.socket);
} else {
connection = new ShareJS.Connection(this.socket);
}
this.setupSocketAuthentication();
this.setupSocketPing();
this.setupSocketOnMessage();
return connection;
}
/**
* Handle the ShareJS connection connecting successfully.
*
* @private
*/
onConnectionConnected() {
this.debug('connectionConnected');
this.reconnectAttempts = 0;
this.connected = true;
}
/**
* Handle the ShareJS connection disconnecting by matching error codes.
*
* @private
* @param {Event} event A disconnection event
* @emits ShareJSWrapper#disconnect
*/
onConnectionDisconnected(event) {
this.debug('connectionDisconnected', ...arguments, event.code);
this.connected = false;
clearTimeout(this.pongWait);
let error;
switch (event.code) {
case ABNORMAL:
case LOCAL_TIMEOUT:
if (this.reconnectAttempts > 5) {
const reason = event.code === ABNORMAL ?
'abnormal' : 'no_pong';
error = new Error(reason);
} else {
this.reconnect();
}
break;
case UNAUTHORIZED:
error = new Error('forbidden');
break;
case NOT_FOUND:
error = new Error('not_found');
break;
default:
if (event.code !== NORMAL) {
error = new Error('unexpected');
}
}
if (error) {
/**
* An event emitted when the client has fatally disconnected and will no
* longer attempt reconnects.
*
* Check `err.message` for "abnormal", "no_pong", "forbidden",
* "not_found", or "unexpected".
*
* @event ShareJSWrapper#disconnect
* @type {Error}
*/
this.eventEmitter.emit('disconnect', error);
}
}
/**
* Handle a remote operation from the server to this client.
*
* @private
* @param {number} retain The number of characters to retain before
* insert/remove
* @param {(number|string)} value The value of the operation—a string for an
* insert or a number for a remove
* @emits ShareJSWrapper#insert
* @emits ShareJSWrapper#remove
*/
onRemoteOperation(retain, value) {
this.content = this.context.get();
let type = 'remove';
if (typeof value === 'string') {
type = 'insert';
}
/**
* An event emitted when the client receives an insert operation. Emits an
* event with an exploded {@link ShareJSWrapper~Insert Insert} operation.
*
* @event ShareJSWrapper#insert
* @param {number} retain The length being retained in the insert
* @param {string} value The value being inserted
*/
/**
* An event emitted when the client receives a remove operation. Emits an
* exploded {@link ShareJSWrapper~Remove Remove} operation.
*
* @event ShareJSWrapper#remove
* @param {number} retain The length being retained in the insert
* @param {number} value The length being removed
*/
this.eventEmitter.emit(type, retain, value);
}
/**
* Handle a pong by waiting a few seconds and sending another ping.
*
* @private
*/
onSocketPong() {
this.receivedPong = true;
setTimeout(_ => {
this.sendPing();
}, 5000);
}
/**
* Attempt to reconnect to the server, using a backoff algorithm.
*
* @private
*/
reconnect() {
this.reconnectAttempts = this.reconnectAttempts || 0;
const attempts = this.reconnectAttempts;
const time = getInterval();
setTimeout(_ => {
this.reconnectAttempts = this.reconnectAttempts + 1;
this.connect(null, true);
}, time);
function getInterval() { // eslint-disable-line require-jsdoc
let max = (Math.pow(2, attempts) - 1) * 1000;
if (max > 5 * 1000) {
max = 5 * 1000;
}
return Math.random() * max;
}
}
/**
* Send a ping over the WebSocket, and await pong.
*
* @private
*/
sendPing() {
if (this.config.noPing) {
return;
}
const { socket } = this;
if (socket.readyState === socket.OPEN) {
this.receivedPong = false;
socket.send('ping');
this.pongWait = setTimeout(_ => {
if (!this.receivedPong) {
this.socket.close(LOCAL_TIMEOUT);
}
}, 1000);
}
}
/**
* Set up the authentication step.
*
* ShareJS immediately sets `socket.onopen` so we override that and ensure
* that an authentication message is sent to the realtime server as early as
* possible.
*
* @private
*/
setupSocketAuthentication() {
const { accessToken } = this.config;
const { socket } = this;
const _onopen = bind(socket, 'onopen');
socket.onopen = _ => {
this.debug('sending auth token');
socket.send(`auth-token:${accessToken}`);
_onopen(...arguments);
};
}
/**
* Set up the message handler for the socket.
*
* ShareJS immediately sets `socket.onmessage`, so we override that and ensure
* it does not try to parse messages like "pong".
*
* @private
*/
setupSocketOnMessage() {
const { socket } = this;
const _onmessage = bind(socket, 'onmessage');
socket.onmessage = function onMessage({ data }) {
if (data === 'pong') {
this.onSocketPong();
return null;
}
return _onmessage(...arguments);
}.bind(this);
}
/**
* Set up a ping/pong cycle for this socket.
*
* @private
*/
setupSocketPing() {
const { socket } = this;
const _onopen = bind(socket, 'onopen');
socket.onopen = function onOpen() {
this.sendPing();
_onopen(...arguments);
}.bind(this);
}
/**
* Conditionally log a debug statement.
*
* @private
*/
debug() {
if (this.config.debug) {
if (arguments.length === 1 && typeof arguments[0] === 'function') {
console.log(...arguments[0]());
} else {
console.log(...arguments);
}
}
}
}
/**
* @private
* @param {*} target The target of the method call
* @param {string} method The name of the method to call
* @return {*} The return value of the method call
*/
function bind(target, method) {
return target[method].bind(target);
}