source: trip-planner-front/node_modules/socket.io/dist/socket.js

Last change on this file was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago

primeNG components

  • Property mode set to 100644
File size: 16.4 KB
RevLine 
[6a3a178]1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.Socket = exports.RESERVED_EVENTS = void 0;
7const socket_io_parser_1 = require("socket.io-parser");
8const debug_1 = __importDefault(require("debug"));
[e29cc2e]9const typed_events_1 = require("./typed-events");
[6a3a178]10const base64id_1 = __importDefault(require("base64id"));
[e29cc2e]11const broadcast_operator_1 = require("./broadcast-operator");
12const debug = (0, debug_1.default)("socket.io:socket");
[6a3a178]13exports.RESERVED_EVENTS = new Set([
14 "connect",
15 "connect_error",
16 "disconnect",
17 "disconnecting",
18 "newListener",
19 "removeListener",
20]);
[e29cc2e]21class Socket extends typed_events_1.StrictEventEmitter {
[6a3a178]22 /**
23 * Interface to a `Client` for a given `Namespace`.
24 *
25 * @param {Namespace} nsp
26 * @param {Client} client
27 * @param {Object} auth
28 * @package
29 */
30 constructor(nsp, client, auth) {
31 super();
32 this.nsp = nsp;
33 this.client = client;
[e29cc2e]34 /**
35 * Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
36 */
37 this.data = {};
38 this.connected = false;
[6a3a178]39 this.acks = new Map();
40 this.fns = [];
41 this.flags = {};
42 this.server = nsp.server;
43 this.adapter = this.nsp.adapter;
44 if (client.conn.protocol === 3) {
45 // @ts-ignore
46 this.id = nsp.name !== "/" ? nsp.name + "#" + client.id : client.id;
47 }
48 else {
49 this.id = base64id_1.default.generateId(); // don't reuse the Engine.IO id because it's sensitive information
50 }
51 this.handshake = this.buildHandshake(auth);
52 }
53 /**
54 * Builds the `handshake` BC object
55 *
56 * @private
57 */
58 buildHandshake(auth) {
59 return {
60 headers: this.request.headers,
61 time: new Date() + "",
62 address: this.conn.remoteAddress,
63 xdomain: !!this.request.headers.origin,
64 // @ts-ignore
65 secure: !!this.request.connection.encrypted,
66 issued: +new Date(),
67 url: this.request.url,
[e29cc2e]68 // @ts-ignore
69 query: this.request._query,
[6a3a178]70 auth,
71 };
72 }
73 /**
74 * Emits to this client.
75 *
76 * @return Always returns `true`.
77 * @public
78 */
79 emit(ev, ...args) {
80 if (exports.RESERVED_EVENTS.has(ev)) {
81 throw new Error(`"${ev}" is a reserved event name`);
82 }
[e29cc2e]83 const data = [ev, ...args];
[6a3a178]84 const packet = {
85 type: socket_io_parser_1.PacketType.EVENT,
[e29cc2e]86 data: data,
[6a3a178]87 };
88 // access last argument to see if it's an ACK callback
[e29cc2e]89 if (typeof data[data.length - 1] === "function") {
90 const id = this.nsp._ids++;
91 debug("emitting packet with ack id %d", id);
92 this.registerAckCallback(id, data.pop());
93 packet.id = id;
[6a3a178]94 }
95 const flags = Object.assign({}, this.flags);
96 this.flags = {};
[e29cc2e]97 this.packet(packet, flags);
[6a3a178]98 return true;
99 }
[e29cc2e]100 /**
101 * @private
102 */
103 registerAckCallback(id, ack) {
104 const timeout = this.flags.timeout;
105 if (timeout === undefined) {
106 this.acks.set(id, ack);
107 return;
108 }
109 const timer = setTimeout(() => {
110 debug("event with ack id %d has timed out after %d ms", id, timeout);
111 this.acks.delete(id);
112 ack.call(this, new Error("operation has timed out"));
113 }, timeout);
114 this.acks.set(id, (...args) => {
115 clearTimeout(timer);
116 ack.apply(this, [null, ...args]);
117 });
118 }
[6a3a178]119 /**
120 * Targets a room when broadcasting.
121 *
[e29cc2e]122 * @param room
[6a3a178]123 * @return self
124 * @public
125 */
[e29cc2e]126 to(room) {
127 return this.newBroadcastOperator().to(room);
[6a3a178]128 }
129 /**
130 * Targets a room when broadcasting.
131 *
[e29cc2e]132 * @param room
[6a3a178]133 * @return self
134 * @public
135 */
[e29cc2e]136 in(room) {
137 return this.newBroadcastOperator().in(room);
138 }
139 /**
140 * Excludes a room when broadcasting.
141 *
142 * @param room
143 * @return self
144 * @public
145 */
146 except(room) {
147 return this.newBroadcastOperator().except(room);
[6a3a178]148 }
149 /**
150 * Sends a `message` event.
151 *
152 * @return self
153 * @public
154 */
155 send(...args) {
156 this.emit("message", ...args);
157 return this;
158 }
159 /**
160 * Sends a `message` event.
161 *
162 * @return self
163 * @public
164 */
165 write(...args) {
166 this.emit("message", ...args);
167 return this;
168 }
169 /**
170 * Writes a packet.
171 *
172 * @param {Object} packet - packet object
173 * @param {Object} opts - options
174 * @private
175 */
176 packet(packet, opts = {}) {
177 packet.nsp = this.nsp.name;
178 opts.compress = false !== opts.compress;
179 this.client._packet(packet, opts);
180 }
181 /**
182 * Joins a room.
183 *
184 * @param {String|Array} rooms - room or array of rooms
185 * @return a Promise or nothing, depending on the adapter
186 * @public
187 */
188 join(rooms) {
189 debug("join room %s", rooms);
190 return this.adapter.addAll(this.id, new Set(Array.isArray(rooms) ? rooms : [rooms]));
191 }
192 /**
193 * Leaves a room.
194 *
195 * @param {String} room
196 * @return a Promise or nothing, depending on the adapter
197 * @public
198 */
199 leave(room) {
200 debug("leave room %s", room);
201 return this.adapter.del(this.id, room);
202 }
203 /**
204 * Leave all rooms.
205 *
206 * @private
207 */
208 leaveAll() {
209 this.adapter.delAll(this.id);
210 }
211 /**
212 * Called by `Namespace` upon successful
213 * middleware execution (ie: authorization).
214 * Socket is added to namespace array before
215 * call to join, so adapters can access it.
216 *
217 * @private
218 */
219 _onconnect() {
220 debug("socket connected - writing packet");
[e29cc2e]221 this.connected = true;
[6a3a178]222 this.join(this.id);
223 if (this.conn.protocol === 3) {
224 this.packet({ type: socket_io_parser_1.PacketType.CONNECT });
225 }
226 else {
227 this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: { sid: this.id } });
228 }
229 }
230 /**
231 * Called with each packet. Called by `Client`.
232 *
233 * @param {Object} packet
234 * @private
235 */
236 _onpacket(packet) {
237 debug("got packet %j", packet);
238 switch (packet.type) {
239 case socket_io_parser_1.PacketType.EVENT:
240 this.onevent(packet);
241 break;
242 case socket_io_parser_1.PacketType.BINARY_EVENT:
243 this.onevent(packet);
244 break;
245 case socket_io_parser_1.PacketType.ACK:
246 this.onack(packet);
247 break;
248 case socket_io_parser_1.PacketType.BINARY_ACK:
249 this.onack(packet);
250 break;
251 case socket_io_parser_1.PacketType.DISCONNECT:
252 this.ondisconnect();
253 break;
254 case socket_io_parser_1.PacketType.CONNECT_ERROR:
255 this._onerror(new Error(packet.data));
256 }
257 }
258 /**
259 * Called upon event packet.
260 *
261 * @param {Packet} packet - packet object
262 * @private
263 */
264 onevent(packet) {
265 const args = packet.data || [];
266 debug("emitting event %j", args);
267 if (null != packet.id) {
268 debug("attaching ack callback to event");
269 args.push(this.ack(packet.id));
270 }
271 if (this._anyListeners && this._anyListeners.length) {
272 const listeners = this._anyListeners.slice();
273 for (const listener of listeners) {
274 listener.apply(this, args);
275 }
276 }
277 this.dispatch(args);
278 }
279 /**
280 * Produces an ack callback to emit with an event.
281 *
282 * @param {Number} id - packet id
283 * @private
284 */
285 ack(id) {
286 const self = this;
287 let sent = false;
288 return function () {
289 // prevent double callbacks
290 if (sent)
291 return;
292 const args = Array.prototype.slice.call(arguments);
293 debug("sending ack %j", args);
294 self.packet({
295 id: id,
296 type: socket_io_parser_1.PacketType.ACK,
297 data: args,
298 });
299 sent = true;
300 };
301 }
302 /**
303 * Called upon ack packet.
304 *
305 * @private
306 */
307 onack(packet) {
308 const ack = this.acks.get(packet.id);
309 if ("function" == typeof ack) {
310 debug("calling ack %s with %j", packet.id, packet.data);
311 ack.apply(this, packet.data);
312 this.acks.delete(packet.id);
313 }
314 else {
315 debug("bad ack %s", packet.id);
316 }
317 }
318 /**
319 * Called upon client disconnect packet.
320 *
321 * @private
322 */
323 ondisconnect() {
324 debug("got disconnect packet");
325 this._onclose("client namespace disconnect");
326 }
327 /**
328 * Handles a client error.
329 *
330 * @private
331 */
332 _onerror(err) {
333 if (this.listeners("error").length) {
[e29cc2e]334 this.emitReserved("error", err);
[6a3a178]335 }
336 else {
337 console.error("Missing error handler on `socket`.");
338 console.error(err.stack);
339 }
340 }
341 /**
342 * Called upon closing. Called by `Client`.
343 *
344 * @param {String} reason
345 * @throw {Error} optional error object
346 *
347 * @private
348 */
349 _onclose(reason) {
350 if (!this.connected)
351 return this;
352 debug("closing socket - reason %s", reason);
[e29cc2e]353 this.emitReserved("disconnecting", reason);
[6a3a178]354 this.leaveAll();
355 this.nsp._remove(this);
356 this.client._remove(this);
357 this.connected = false;
[e29cc2e]358 this.emitReserved("disconnect", reason);
[6a3a178]359 return;
360 }
361 /**
362 * Produces an `error` packet.
363 *
364 * @param {Object} err - error object
365 *
366 * @private
367 */
368 _error(err) {
369 this.packet({ type: socket_io_parser_1.PacketType.CONNECT_ERROR, data: err });
370 }
371 /**
372 * Disconnects this client.
373 *
374 * @param {Boolean} close - if `true`, closes the underlying connection
375 * @return {Socket} self
376 *
377 * @public
378 */
379 disconnect(close = false) {
380 if (!this.connected)
381 return this;
382 if (close) {
383 this.client._disconnect();
384 }
385 else {
386 this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
387 this._onclose("server namespace disconnect");
388 }
389 return this;
390 }
391 /**
392 * Sets the compress flag.
393 *
394 * @param {Boolean} compress - if `true`, compresses the sending data
395 * @return {Socket} self
396 * @public
397 */
398 compress(compress) {
399 this.flags.compress = compress;
400 return this;
401 }
402 /**
403 * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
404 * receive messages (because of network slowness or other issues, or because they’re connected through long polling
405 * and is in the middle of a request-response cycle).
406 *
407 * @return {Socket} self
408 * @public
409 */
410 get volatile() {
411 this.flags.volatile = true;
412 return this;
413 }
414 /**
415 * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
416 * sender.
417 *
418 * @return {Socket} self
419 * @public
420 */
421 get broadcast() {
[e29cc2e]422 return this.newBroadcastOperator();
[6a3a178]423 }
424 /**
425 * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
426 *
427 * @return {Socket} self
428 * @public
429 */
430 get local() {
[e29cc2e]431 return this.newBroadcastOperator().local;
432 }
433 /**
434 * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
435 * given number of milliseconds have elapsed without an acknowledgement from the client:
436 *
437 * ```
438 * socket.timeout(5000).emit("my-event", (err) => {
439 * if (err) {
440 * // the client did not acknowledge the event in the given delay
441 * }
442 * });
443 * ```
444 *
445 * @returns self
446 * @public
447 */
448 timeout(timeout) {
449 this.flags.timeout = timeout;
[6a3a178]450 return this;
451 }
452 /**
453 * Dispatch incoming event to socket listeners.
454 *
455 * @param {Array} event - event that will get emitted
456 * @private
457 */
458 dispatch(event) {
459 debug("dispatching an event %j", event);
460 this.run(event, (err) => {
461 process.nextTick(() => {
462 if (err) {
463 return this._onerror(err);
464 }
465 if (this.connected) {
[e29cc2e]466 super.emitUntyped.apply(this, event);
[6a3a178]467 }
468 else {
469 debug("ignore packet received after disconnection");
470 }
471 });
472 });
473 }
474 /**
475 * Sets up socket middleware.
476 *
477 * @param {Function} fn - middleware function (event, next)
478 * @return {Socket} self
479 * @public
480 */
481 use(fn) {
482 this.fns.push(fn);
483 return this;
484 }
485 /**
486 * Executes the middleware for an incoming event.
487 *
488 * @param {Array} event - event that will get emitted
489 * @param {Function} fn - last fn call in the middleware
490 * @private
491 */
492 run(event, fn) {
493 const fns = this.fns.slice(0);
494 if (!fns.length)
495 return fn(null);
496 function run(i) {
497 fns[i](event, function (err) {
498 // upon error, short-circuit
499 if (err)
500 return fn(err);
501 // if no middleware left, summon callback
502 if (!fns[i + 1])
503 return fn(null);
504 // go on to next
505 run(i + 1);
506 });
507 }
508 run(0);
509 }
[e29cc2e]510 /**
511 * Whether the socket is currently disconnected
512 */
513 get disconnected() {
514 return !this.connected;
515 }
[6a3a178]516 /**
517 * A reference to the request that originated the underlying Engine.IO Socket.
518 *
519 * @public
520 */
521 get request() {
522 return this.client.request;
523 }
524 /**
525 * A reference to the underlying Client transport connection (Engine.IO Socket object).
526 *
527 * @public
528 */
529 get conn() {
530 return this.client.conn;
531 }
532 /**
533 * @public
534 */
535 get rooms() {
536 return this.adapter.socketRooms(this.id) || new Set();
537 }
538 /**
539 * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
540 * callback.
541 *
542 * @param listener
543 * @public
544 */
545 onAny(listener) {
546 this._anyListeners = this._anyListeners || [];
547 this._anyListeners.push(listener);
548 return this;
549 }
550 /**
551 * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
552 * callback. The listener is added to the beginning of the listeners array.
553 *
554 * @param listener
555 * @public
556 */
557 prependAny(listener) {
558 this._anyListeners = this._anyListeners || [];
559 this._anyListeners.unshift(listener);
560 return this;
561 }
562 /**
563 * Removes the listener that will be fired when any event is emitted.
564 *
565 * @param listener
566 * @public
567 */
568 offAny(listener) {
569 if (!this._anyListeners) {
570 return this;
571 }
572 if (listener) {
573 const listeners = this._anyListeners;
574 for (let i = 0; i < listeners.length; i++) {
575 if (listener === listeners[i]) {
576 listeners.splice(i, 1);
577 return this;
578 }
579 }
580 }
581 else {
582 this._anyListeners = [];
583 }
584 return this;
585 }
586 /**
587 * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
588 * e.g. to remove listeners.
589 *
590 * @public
591 */
592 listenersAny() {
593 return this._anyListeners || [];
594 }
[e29cc2e]595 newBroadcastOperator() {
596 const flags = Object.assign({}, this.flags);
597 this.flags = {};
598 return new broadcast_operator_1.BroadcastOperator(this.adapter, new Set(), new Set([this.id]), flags);
599 }
[6a3a178]600}
601exports.Socket = Socket;
Note: See TracBrowser for help on using the repository browser.