· 6 years ago · Dec 26, 2019, 10:54 PM
1var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2
3var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
4
5function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6
7var app =
8/******/function (modules) {
9 // webpackBootstrap
10 /******/ // The module cache
11 /******/var installedModules = {};
12
13 /******/ // The require function
14 /******/function __webpack_require__(moduleId) {
15
16 /******/ // Check if module is in cache
17 /******/if (installedModules[moduleId])
18 /******/return installedModules[moduleId].exports;
19
20 /******/ // Create a new module (and put it into the cache)
21 /******/var module = installedModules[moduleId] = {
22 /******/exports: {},
23 /******/id: moduleId,
24 /******/loaded: false
25 /******/ };
26
27 /******/ // Execute the module function
28 /******/modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
29
30 /******/ // Flag the module as loaded
31 /******/module.loaded = true;
32
33 /******/ // Return the exports of the module
34 /******/return module.exports;
35 /******/
36 }
37
38 /******/ // expose the modules object (__webpack_modules__)
39 /******/__webpack_require__.m = modules;
40
41 /******/ // expose the module cache
42 /******/__webpack_require__.c = installedModules;
43
44 /******/ // __webpack_public_path__
45 /******/__webpack_require__.p = "";
46
47 /******/ // Load entry module and return exports
48 /******/return __webpack_require__(0);
49 /******/
50}(
51/************************************************************************/
52/******/[
53/* 0 */
54/***/function (module, exports, __webpack_require__) {
55
56 var io = __webpack_require__(1);
57 var ChatClient = __webpack_require__(54);
58 var Canvas = __webpack_require__(56);
59 var global = __webpack_require__(55);
60
61 var playerNameInput = document.getElementById('playerNameInput');
62 var socket;
63 var reason;
64
65 var debug = function debug(args) {
66 if (console && console.log) {
67 console.log(args);
68 }
69 };
70
71 if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
72 global.mobile = true;
73 }
74
75 function startGame(type) {
76 global.playerName = playerNameInput.value.replace(/(<([^>]+)>)/ig, '').substring(0, 25);
77 global.playerType = type;
78
79 global.screenWidth = window.innerWidth;
80 global.screenHeight = window.innerHeight;
81
82 document.getElementById('startMenuWrapper').style.maxHeight = '0px';
83 document.getElementById('gameAreaWrapper').style.opacity = 1;
84 if (!socket) {
85 socket = io({ query: "type=" + type });
86 setupSocket(socket);
87 }
88 if (!global.animLoopHandle) animloop();
89 socket.emit('respawn');
90 window.chat.socket = socket;
91 window.chat.registerFunctions();
92 window.canvas.socket = socket;
93 global.socket = socket;
94 }
95
96 // Checks if the nick chosen contains valid alphanumeric characters (and underscores).
97 function validNick() {
98 var regex = /^\w*$/;
99 debug('Regex Test', regex.exec(playerNameInput.value));
100 return regex.exec(playerNameInput.value) !== null;
101 }
102
103 window.onload = function () {
104
105 var btn = document.getElementById('startButton'),
106 btnS = document.getElementById('spectateButton'),
107 nickErrorText = document.querySelector('#startMenu .input-error');
108
109 btnS.onclick = function () {
110 startGame('spectate');
111 };
112
113 btn.onclick = function () {
114
115 // Checks if the nick is valid.
116 if (validNick()) {
117 nickErrorText.style.opacity = 0;
118 startGame('player');
119 } else {
120 nickErrorText.style.opacity = 1;
121 }
122 };
123
124 var settingsMenu = document.getElementById('settingsButton');
125 var settings = document.getElementById('settings');
126 var instructions = document.getElementById('instructions');
127
128 settingsMenu.onclick = function () {
129 if (settings.style.maxHeight == '300px') {
130 settings.style.maxHeight = '0px';
131 } else {
132 settings.style.maxHeight = '300px';
133 }
134 };
135
136 playerNameInput.addEventListener('keypress', function (e) {
137 var key = e.which || e.keyCode;
138
139 if (key === global.KEY_ENTER) {
140 if (validNick()) {
141 nickErrorText.style.opacity = 0;
142 startGame('player');
143 } else {
144 nickErrorText.style.opacity = 1;
145 }
146 }
147 });
148 };
149
150 // TODO: Break out into GameControls.
151
152 var foodConfig = {
153 border: 0
154 };
155
156 var playerConfig = {
157 border: 6,
158 textColor: '#FFFFFF',
159 textBorder: '#000000',
160 textBorderSize: 3,
161 defaultSize: 3000
162 };
163
164 var player = {
165 id: -1,
166 x: global.screenWidth / 2,
167 y: global.screenHeight / 2,
168 screenWidth: global.screenWidth,
169 screenHeight: global.screenHeight,
170 target: { x: global.screenWidth / 2, y: global.screenHeight / 2 }
171 };
172 global.player = player;
173
174 var foods = [];
175 var viruses = [];
176 var fireFood = [];
177 var users = [];
178 var leaderboard = [];
179 var target = { x: player.x, y: player.y };
180 global.target = target;
181
182 window.canvas = new Canvas();
183 window.chat = new ChatClient();
184
185 var c = window.canvas.cv;
186 var graph = c.getContext('2d');
187
188 $("#feed").click(function () {
189 socket.emit('1');
190 window.canvas.reenviar = false;
191 });
192
193 $("#split").click(function () {
194 socket.emit('2');
195 window.canvas.reenviar = false;
196 });
197
198 // socket stuff.
199 function setupSocket(socket) {
200 // Handle ping.
201 socket.on('pongcheck', function () {
202 var latency = Date.now() - global.startPingTime;
203 debug('Latency: ' + latency + 'ms');
204 window.chat.addSystemLine('Ping: ' + latency + 'ms');
205 });
206
207 // Handle error.
208 socket.on('connect_failed', function () {
209 socket.close();
210 global.disconnected = true;
211 });
212
213 socket.on('disconnect', function () {
214 socket.close();
215 global.disconnected = true;
216 });
217
218 // Handle connection.
219 socket.on('welcome', function (playerSettings) {
220 player = playerSettings;
221 player.name = global.playerName;
222 player.screenWidth = global.screenWidth;
223 player.screenHeight = global.screenHeight;
224 player.target = window.canvas.target;
225 global.player = player;
226 window.chat.player = player;
227 socket.emit('gotit', player);
228 global.gameStart = true;
229 debug('Game started at: ' + global.gameStart);
230 window.chat.addSystemLine('Connected to the game!');
231 window.chat.addSystemLine('Type <b>-help</b> for a list of commands.');
232 if (global.mobile) {
233 document.getElementById('gameAreaWrapper').removeChild(document.getElementById('chatbox'));
234 }
235 c.focus();
236 });
237
238 socket.on('gameSetup', function (data) {
239 global.gameWidth = data.gameWidth;
240 global.gameHeight = data.gameHeight;
241 resize();
242 });
243
244 socket.on('playerDied', function (data) {
245 window.chat.addSystemLine('[SERVER] <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> was eaten.');
246 });
247
248 socket.on('playerDisconnect', function (data) {
249 window.chat.addSystemLine('[SERVER] <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> disconnected.');
250 });
251
252 socket.on('playerJoin', function (data) {
253 window.chat.addSystemLine('[SERVER] <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> joined.');
254 });
255
256 socket.on('leaderboard', function (data) {
257 leaderboard = data.leaderboard;
258 var status = '<span class="title">排行榜</span>';
259 for (var i = 0; i < leaderboard.length; i++) {
260 status += '<br />';
261 if (leaderboard[i].id == player.id) {
262 if (leaderboard[i].name.length !== 0) status += '<span class="me">' + (i + 1) + '. ' + leaderboard[i].name + "</span>";else status += '<span class="me">' + (i + 1) + ". An unnamed cell</span>";
263 } else {
264 if (leaderboard[i].name.length !== 0) status += i + 1 + '. ' + leaderboard[i].name;else status += i + 1 + '. An unnamed cell';
265 }
266 }
267 //status += '<br />Players: ' + data.players;
268 document.getElementById('status').innerHTML = status;
269 });
270
271 socket.on('serverMSG', function (data) {
272 window.chat.addSystemLine(data);
273 });
274
275 // Chat.
276 socket.on('serverSendPlayerChat', function (data) {
277 window.chat.addChatLine(data.sender, data.message, false);
278 });
279
280 // Handle movement.
281 socket.on('serverTellPlayerMove', function (userData, foodsList, massList, virusList) {
282 var playerData;
283 for (var i = 0; i < userData.length; i++) {
284 if (typeof userData[i].id == "undefined") {
285 playerData = userData[i];
286 i = userData.length;
287 }
288 }
289 if (global.playerType == 'player') {
290 var xoffset = player.x - playerData.x;
291 var yoffset = player.y - playerData.y;
292
293 player.x = playerData.x;
294 player.y = playerData.y;
295 player.hue = playerData.hue;
296 player.massTotal = playerData.massTotal;
297 player.cells = playerData.cells;
298 player.xoffset = isNaN(xoffset) ? 0 : xoffset;
299 player.yoffset = isNaN(yoffset) ? 0 : yoffset;
300 }
301 users = userData;
302 foods = foodsList;
303 viruses = virusList;
304 fireFood = massList;
305 });
306
307 // Death.
308 socket.on('RIP', function () {
309 global.gameStart = false;
310 global.died = true;
311 window.setTimeout(function () {
312 document.getElementById('gameAreaWrapper').style.opacity = 0;
313 document.getElementById('startMenuWrapper').style.maxHeight = '1000px';
314 global.died = false;
315 if (global.animLoopHandle) {
316 window.cancelAnimationFrame(global.animLoopHandle);
317 global.animLoopHandle = undefined;
318 }
319 }, 2500);
320 });
321
322 socket.on('kick', function (data) {
323 global.gameStart = false;
324 reason = data;
325 global.kicked = true;
326 socket.close();
327 });
328
329 socket.on('virusSplit', function (virusCell) {
330 socket.emit('2', virusCell);
331 reenviar = false;
332 });
333 }
334
335 function drawCircle(centerX, centerY, radius, sides) {
336 var theta = 0;
337 var x = 0;
338 var y = 0;
339
340 graph.beginPath();
341
342 for (var i = 0; i < sides; i++) {
343 theta = i / sides * 2 * Math.PI;
344 x = centerX + radius * Math.sin(theta);
345 y = centerY + radius * Math.cos(theta);
346 graph.lineTo(x, y);
347 }
348
349 graph.closePath();
350 graph.stroke();
351 graph.fill();
352 }
353
354 function drawFood(food) {
355 graph.strokeStyle = 'hsl(' + food.hue + ', 100%, 45%)';
356 graph.fillStyle = 'hsl(' + food.hue + ', 100%, 50%)';
357 graph.lineWidth = foodConfig.border;
358 drawCircle(food.x - player.x + global.screenWidth / 2, food.y - player.y + global.screenHeight / 2, food.radius, global.foodSides);
359 }
360
361 function drawVirus(virus) {
362 graph.strokeStyle = virus.stroke;
363 graph.fillStyle = virus.fill;
364 graph.lineWidth = virus.strokeWidth;
365 drawCircle(virus.x - player.x + global.screenWidth / 2, virus.y - player.y + global.screenHeight / 2, virus.radius, global.virusSides);
366 }
367
368 function drawFireFood(mass) {
369 graph.strokeStyle = 'hsl(' + mass.hue + ', 100%, 45%)';
370 graph.fillStyle = 'hsl(' + mass.hue + ', 100%, 50%)';
371 graph.lineWidth = playerConfig.border + 10;
372 drawCircle(mass.x - player.x + global.screenWidth / 2, mass.y - player.y + global.screenHeight / 2, mass.radius - 5, 18 + ~~(mass.masa / 5));
373 }
374
375 function drawPlayers(order) {
376 var start = {
377 x: player.x - global.screenWidth / 2,
378 y: player.y - global.screenHeight / 2
379 };
380
381 for (var z = 0; z < order.length; z++) {
382 var userCurrent = users[order[z].nCell];
383 var cellCurrent = users[order[z].nCell].cells[order[z].nDiv];
384
385 var x = 0;
386 var y = 0;
387
388 var points = 30 + ~~(cellCurrent.mass / 5);
389 var increase = Math.PI * 2 / points;
390
391 graph.strokeStyle = 'hsl(' + userCurrent.hue + ', 100%, 45%)';
392 graph.fillStyle = 'hsl(' + userCurrent.hue + ', 100%, 50%)';
393 graph.lineWidth = playerConfig.border;
394
395 var xstore = [];
396 var ystore = [];
397
398 global.spin += 0.0;
399
400 var circle = {
401 x: cellCurrent.x - start.x,
402 y: cellCurrent.y - start.y
403 };
404
405 for (var i = 0; i < points; i++) {
406
407 x = cellCurrent.radius * Math.cos(global.spin) + circle.x;
408 y = cellCurrent.radius * Math.sin(global.spin) + circle.y;
409 if (typeof userCurrent.id == "undefined") {
410 x = valueInRange(-userCurrent.x + global.screenWidth / 2, global.gameWidth - userCurrent.x + global.screenWidth / 2, x);
411 y = valueInRange(-userCurrent.y + global.screenHeight / 2, global.gameHeight - userCurrent.y + global.screenHeight / 2, y);
412 } else {
413 x = valueInRange(-cellCurrent.x - player.x + global.screenWidth / 2 + cellCurrent.radius / 3, global.gameWidth - cellCurrent.x + global.gameWidth - player.x + global.screenWidth / 2 - cellCurrent.radius / 3, x);
414 y = valueInRange(-cellCurrent.y - player.y + global.screenHeight / 2 + cellCurrent.radius / 3, global.gameHeight - cellCurrent.y + global.gameHeight - player.y + global.screenHeight / 2 - cellCurrent.radius / 3, y);
415 }
416 global.spin += increase;
417 xstore[i] = x;
418 ystore[i] = y;
419 }
420 /*if (wiggle >= player.radius/ 3) inc = -1;
421 *if (wiggle <= player.radius / -3) inc = +1;
422 *wiggle += inc;
423 */
424 for (i = 0; i < points; ++i) {
425 if (i === 0) {
426 graph.beginPath();
427 graph.moveTo(xstore[i], ystore[i]);
428 } else if (i > 0 && i < points - 1) {
429 graph.lineTo(xstore[i], ystore[i]);
430 } else {
431 graph.lineTo(xstore[i], ystore[i]);
432 graph.lineTo(xstore[0], ystore[0]);
433 }
434 }
435 graph.lineJoin = 'round';
436 graph.lineCap = 'round';
437 graph.fill();
438 graph.stroke();
439 var nameCell = "";
440 if (typeof userCurrent.id == "undefined") nameCell = player.name;else nameCell = userCurrent.name;
441
442 var fontSize = Math.max(cellCurrent.radius / 3, 12);
443 graph.lineWidth = playerConfig.textBorderSize;
444 graph.fillStyle = playerConfig.textColor;
445 graph.strokeStyle = playerConfig.textBorder;
446 graph.miterLimit = 1;
447 graph.lineJoin = 'round';
448 graph.textAlign = 'center';
449 graph.textBaseline = 'middle';
450 graph.font = 'bold ' + fontSize + 'px sans-serif';
451
452 if (global.toggleMassState === 0) {
453 graph.strokeText(nameCell, circle.x, circle.y);
454 graph.fillText(nameCell, circle.x, circle.y);
455 } else {
456 graph.strokeText(nameCell, circle.x, circle.y);
457 graph.fillText(nameCell, circle.x, circle.y);
458 graph.font = 'bold ' + Math.max(fontSize / 3 * 2, 10) + 'px sans-serif';
459 if (nameCell.length === 0) fontSize = 0;
460 graph.strokeText(Math.round(cellCurrent.mass), circle.x, circle.y + fontSize);
461 graph.fillText(Math.round(cellCurrent.mass), circle.x, circle.y + fontSize);
462 }
463 }
464 }
465
466 function valueInRange(min, max, value) {
467 return Math.min(max, Math.max(min, value));
468 }
469
470 function drawgrid() {
471 graph.lineWidth = 1;
472 graph.strokeStyle = global.lineColor;
473 graph.globalAlpha = 0.15;
474 graph.beginPath();
475
476 for (var x = global.xoffset - player.x; x < global.screenWidth; x += global.screenHeight / 18) {
477 graph.moveTo(x, 0);
478 graph.lineTo(x, global.screenHeight);
479 }
480
481 for (var y = global.yoffset - player.y; y < global.screenHeight; y += global.screenHeight / 18) {
482 graph.moveTo(0, y);
483 graph.lineTo(global.screenWidth, y);
484 }
485
486 graph.stroke();
487 graph.globalAlpha = 1;
488 }
489
490 function drawborder() {
491 graph.lineWidth = 1;
492 graph.strokeStyle = playerConfig.borderColor;
493
494 // Left-vertical.
495 if (player.x <= global.screenWidth / 2) {
496 graph.beginPath();
497 graph.moveTo(global.screenWidth / 2 - player.x, 0 ? player.y > global.screenHeight / 2 : global.screenHeight / 2 - player.y);
498 graph.lineTo(global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y);
499 graph.strokeStyle = global.lineColor;
500 graph.stroke();
501 }
502
503 // Top-horizontal.
504 if (player.y <= global.screenHeight / 2) {
505 graph.beginPath();
506 graph.moveTo(0 ? player.x > global.screenWidth / 2 : global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y);
507 graph.lineTo(global.gameWidth + global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y);
508 graph.strokeStyle = global.lineColor;
509 graph.stroke();
510 }
511
512 // Right-vertical.
513 if (global.gameWidth - player.x <= global.screenWidth / 2) {
514 graph.beginPath();
515 graph.moveTo(global.gameWidth + global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y);
516 graph.lineTo(global.gameWidth + global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y);
517 graph.strokeStyle = global.lineColor;
518 graph.stroke();
519 }
520
521 // Bottom-horizontal.
522 if (global.gameHeight - player.y <= global.screenHeight / 2) {
523 graph.beginPath();
524 graph.moveTo(global.gameWidth + global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y);
525 graph.lineTo(global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y);
526 graph.strokeStyle = global.lineColor;
527 graph.stroke();
528 }
529 }
530
531 window.requestAnimFrame = function () {
532 return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
533 window.setTimeout(callback, 1000 / 60);
534 };
535 }();
536
537 window.cancelAnimFrame = function (handle) {
538 return window.cancelAnimationFrame || window.mozCancelAnimationFrame;
539 }();
540
541 function animloop() {
542 global.animLoopHandle = window.requestAnimFrame(animloop);
543 gameLoop();
544 }
545
546 function gameLoop() {
547 if (global.died) {
548 graph.fillStyle = '#333333';
549 graph.fillRect(0, 0, global.screenWidth, global.screenHeight);
550
551 graph.textAlign = 'center';
552 graph.fillStyle = '#FFFFFF';
553 graph.font = 'bold 30px sans-serif';
554 graph.fillText('You died!', global.screenWidth / 2, global.screenHeight / 2);
555 } else if (!global.disconnected) {
556 if (global.gameStart) {
557 graph.fillStyle = global.backgroundColor;
558 graph.fillRect(0, 0, global.screenWidth, global.screenHeight);
559
560 drawgrid();
561 foods.forEach(drawFood);
562 fireFood.forEach(drawFireFood);
563 viruses.forEach(drawVirus);
564
565 if (global.borderDraw) {
566 drawborder();
567 }
568 var orderMass = [];
569 for (var i = 0; i < users.length; i++) {
570 for (var j = 0; j < users[i].cells.length; j++) {
571 orderMass.push({
572 nCell: i,
573 nDiv: j,
574 mass: users[i].cells[j].mass
575 });
576 }
577 }
578 orderMass.sort(function (obj1, obj2) {
579 return obj1.mass - obj2.mass;
580 });
581
582 drawPlayers(orderMass);
583 socket.emit('0', window.canvas.target); // playerSendTarget "Heartbeat".
584 } else {
585 graph.fillStyle = '#333333';
586 graph.fillRect(0, 0, global.screenWidth, global.screenHeight);
587
588 graph.textAlign = 'center';
589 graph.fillStyle = '#FFFFFF';
590 graph.font = 'bold 30px sans-serif';
591 graph.fillText('Game Over!', global.screenWidth / 2, global.screenHeight / 2);
592 }
593 } else {
594 graph.fillStyle = '#333333';
595 graph.fillRect(0, 0, global.screenWidth, global.screenHeight);
596
597 graph.textAlign = 'center';
598 graph.fillStyle = '#FFFFFF';
599 graph.font = 'bold 30px sans-serif';
600 if (global.kicked) {
601 if (reason !== '') {
602 graph.fillText('You were kicked for:', global.screenWidth / 2, global.screenHeight / 2 - 20);
603 graph.fillText(reason, global.screenWidth / 2, global.screenHeight / 2 + 20);
604 } else {
605 graph.fillText('You were kicked!', global.screenWidth / 2, global.screenHeight / 2);
606 }
607 } else {
608 graph.fillText('Disconnected!', global.screenWidth / 2, global.screenHeight / 2);
609 }
610 }
611 }
612
613 window.addEventListener('resize', resize);
614
615 function resize() {
616 if (!socket) return;
617
618 player.screenWidth = c.width = global.screenWidth = global.playerType == 'player' ? window.innerWidth : global.gameWidth;
619 player.screenHeight = c.height = global.screenHeight = global.playerType == 'player' ? window.innerHeight : global.gameHeight;
620
621 if (global.playerType == 'spectate') {
622 player.x = global.gameWidth / 2;
623 player.y = global.gameHeight / 2;
624 }
625
626 socket.emit('windowResized', { screenWidth: global.screenWidth, screenHeight: global.screenHeight });
627 }
628
629 /***/
630},
631/* 1 */
632/***/function (module, exports, __webpack_require__) {
633
634 /**
635 * Module dependencies.
636 */
637
638 var url = __webpack_require__(2);
639 var parser = __webpack_require__(8);
640 var Manager = __webpack_require__(19);
641 var debug = __webpack_require__(4)('socket.io-client');
642
643 /**
644 * Module exports.
645 */
646
647 module.exports = exports = lookup;
648
649 /**
650 * Managers cache.
651 */
652
653 var cache = exports.managers = {};
654
655 /**
656 * Looks up an existing `Manager` for multiplexing.
657 * If the user summons:
658 *
659 * `io('http://localhost/a');`
660 * `io('http://localhost/b');`
661 *
662 * We reuse the existing instance based on same scheme/port/host,
663 * and we initialize sockets for each namespace.
664 *
665 * @api public
666 */
667
668 function lookup(uri, opts) {
669 if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') {
670 opts = uri;
671 uri = undefined;
672 }
673
674 opts = opts || {};
675
676 var parsed = url(uri);
677 var source = parsed.source;
678 var id = parsed.id;
679 var path = parsed.path;
680 var sameNamespace = cache[id] && path in cache[id].nsps;
681 var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace;
682
683 var io;
684
685 if (newConnection) {
686 debug('ignoring socket cache for %s', source);
687 io = Manager(source, opts);
688 } else {
689 if (!cache[id]) {
690 debug('new io instance for %s', source);
691 cache[id] = Manager(source, opts);
692 }
693 io = cache[id];
694 }
695 if (parsed.query && !opts.query) {
696 opts.query = parsed.query;
697 } else if (opts && 'object' === _typeof(opts.query)) {
698 opts.query = encodeQueryString(opts.query);
699 }
700 return io.socket(parsed.path, opts);
701 }
702 /**
703 * Helper method to parse query objects to string.
704 * @param {object} query
705 * @returns {string}
706 */
707 function encodeQueryString(obj) {
708 var str = [];
709 for (var p in obj) {
710 if (obj.hasOwnProperty(p)) {
711 str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
712 }
713 }
714 return str.join('&');
715 }
716 /**
717 * Protocol version.
718 *
719 * @api public
720 */
721
722 exports.protocol = parser.protocol;
723
724 /**
725 * `connect`.
726 *
727 * @param {String} uri
728 * @api public
729 */
730
731 exports.connect = lookup;
732
733 /**
734 * Expose constructors for standalone build.
735 *
736 * @api public
737 */
738
739 exports.Manager = __webpack_require__(19);
740 exports.Socket = __webpack_require__(49);
741
742 /***/
743},
744/* 2 */
745/***/function (module, exports, __webpack_require__) {
746
747 /* WEBPACK VAR INJECTION */(function (global) {
748 /**
749 * Module dependencies.
750 */
751
752 var parseuri = __webpack_require__(3);
753 var debug = __webpack_require__(4)('socket.io-client:url');
754
755 /**
756 * Module exports.
757 */
758
759 module.exports = url;
760
761 /**
762 * URL parser.
763 *
764 * @param {String} url
765 * @param {Object} An object meant to mimic window.location.
766 * Defaults to window.location.
767 * @api public
768 */
769
770 function url(uri, loc) {
771 var obj = uri;
772
773 // default to window.location
774 loc = loc || global.location;
775 if (null == uri) uri = loc.protocol + '//' + loc.host;
776
777 // relative path support
778 if ('string' === typeof uri) {
779 if ('/' === uri.charAt(0)) {
780 if ('/' === uri.charAt(1)) {
781 uri = loc.protocol + uri;
782 } else {
783 uri = loc.host + uri;
784 }
785 }
786
787 if (!/^(https?|wss?):\/\//.test(uri)) {
788 debug('protocol-less url %s', uri);
789 if ('undefined' !== typeof loc) {
790 uri = loc.protocol + '//' + uri;
791 } else {
792 uri = 'https://' + uri;
793 }
794 }
795
796 // parse
797 debug('parse %s', uri);
798 obj = parseuri(uri);
799 }
800
801 // make sure we treat `localhost:80` and `localhost` equally
802 if (!obj.port) {
803 if (/^(http|ws)$/.test(obj.protocol)) {
804 obj.port = '80';
805 } else if (/^(http|ws)s$/.test(obj.protocol)) {
806 obj.port = '443';
807 }
808 }
809
810 obj.path = obj.path || '/';
811
812 var ipv6 = obj.host.indexOf(':') !== -1;
813 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
814
815 // define unique id
816 obj.id = obj.protocol + '://' + host + ':' + obj.port;
817 // define href
818 obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port);
819
820 return obj;
821 }
822
823 /* WEBPACK VAR INJECTION */
824 }).call(exports, function () {
825 return this;
826 }());
827
828 /***/
829},
830/* 3 */
831/***/function (module, exports) {
832
833 /**
834 * Parses an URI
835 *
836 * @author Steven Levithan <stevenlevithan.com> (MIT license)
837 * @api private
838 */
839
840 var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
841
842 var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
843
844 module.exports = function parseuri(str) {
845 var src = str,
846 b = str.indexOf('['),
847 e = str.indexOf(']');
848
849 if (b != -1 && e != -1) {
850 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
851 }
852
853 var m = re.exec(str || ''),
854 uri = {},
855 i = 14;
856
857 while (i--) {
858 uri[parts[i]] = m[i] || '';
859 }
860
861 if (b != -1 && e != -1) {
862 uri.source = src;
863 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
864 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
865 uri.ipv6uri = true;
866 }
867
868 return uri;
869 };
870
871 /***/
872},
873/* 4 */
874/***/function (module, exports, __webpack_require__) {
875
876 /* WEBPACK VAR INJECTION */(function (process) {
877 /**
878 * This is the web browser implementation of `debug()`.
879 *
880 * Expose `debug()` as the module.
881 */
882
883 exports = module.exports = __webpack_require__(6);
884 exports.log = log;
885 exports.formatArgs = formatArgs;
886 exports.save = save;
887 exports.load = load;
888 exports.useColors = useColors;
889 exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
890
891 /**
892 * Colors.
893 */
894
895 exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson'];
896
897 /**
898 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
899 * and the Firebug extension (any Firefox version) are known
900 * to support "%c" CSS customizations.
901 *
902 * TODO: add a `localStorage` variable to explicitly enable/disable colors
903 */
904
905 function useColors() {
906 // is webkit? http://stackoverflow.com/a/16459606/376773
907 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
908 return typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style ||
909 // is firebug? http://stackoverflow.com/a/398120/376773
910 window.console && (console.firebug || console.exception && console.table) ||
911 // is firefox >= v31?
912 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
913 navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31;
914 }
915
916 /**
917 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
918 */
919
920 exports.formatters.j = function (v) {
921 try {
922 return JSON.stringify(v);
923 } catch (err) {
924 return '[UnexpectedJSONParseError]: ' + err.message;
925 }
926 };
927
928 /**
929 * Colorize log arguments if enabled.
930 *
931 * @api public
932 */
933
934 function formatArgs() {
935 var args = arguments;
936 var useColors = this.useColors;
937
938 args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
939
940 if (!useColors) return args;
941
942 var c = 'color: ' + this.color;
943 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
944
945 // the final "%c" is somewhat tricky, because there could be other
946 // arguments passed either before or after the %c, so we need to
947 // figure out the correct index to insert the CSS into
948 var index = 0;
949 var lastC = 0;
950 args[0].replace(/%[a-z%]/g, function (match) {
951 if ('%%' === match) return;
952 index++;
953 if ('%c' === match) {
954 // we only are interested in the *last* %c
955 // (the user may have provided their own)
956 lastC = index;
957 }
958 });
959
960 args.splice(lastC, 0, c);
961 return args;
962 }
963
964 /**
965 * Invokes `console.log()` when available.
966 * No-op when `console.log` is not a "function".
967 *
968 * @api public
969 */
970
971 function log() {
972 // this hackery is required for IE8/9, where
973 // the `console.log` function doesn't have 'apply'
974 return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
975 }
976
977 /**
978 * Save `namespaces`.
979 *
980 * @param {String} namespaces
981 * @api private
982 */
983
984 function save(namespaces) {
985 try {
986 if (null == namespaces) {
987 exports.storage.removeItem('debug');
988 } else {
989 exports.storage.debug = namespaces;
990 }
991 } catch (e) {}
992 }
993
994 /**
995 * Load `namespaces`.
996 *
997 * @return {String} returns the previously persisted debug modes
998 * @api private
999 */
1000
1001 function load() {
1002 var r;
1003 try {
1004 return exports.storage.debug;
1005 } catch (e) {}
1006
1007 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
1008 if (typeof process !== 'undefined' && 'env' in process) {
1009 return process.env.DEBUG;
1010 }
1011 }
1012
1013 /**
1014 * Enable namespaces listed in `localStorage.debug` initially.
1015 */
1016
1017 exports.enable(load());
1018
1019 /**
1020 * Localstorage attempts to return the localstorage.
1021 *
1022 * This is necessary because safari throws
1023 * when a user disables cookies/localstorage
1024 * and you attempt to access it.
1025 *
1026 * @return {LocalStorage}
1027 * @api private
1028 */
1029
1030 function localstorage() {
1031 try {
1032 return window.localStorage;
1033 } catch (e) {}
1034 }
1035
1036 /* WEBPACK VAR INJECTION */
1037 }).call(exports, __webpack_require__(5));
1038
1039 /***/
1040},
1041/* 5 */
1042/***/function (module, exports) {
1043
1044 // shim for using process in browser
1045 var process = module.exports = {};
1046
1047 // cached from whatever global is present so that test runners that stub it
1048 // don't break things. But we need to wrap it in a try catch in case it is
1049 // wrapped in strict mode code which doesn't define any globals. It's inside a
1050 // function because try/catches deoptimize in certain engines.
1051
1052 var cachedSetTimeout;
1053 var cachedClearTimeout;
1054
1055 function defaultSetTimout() {
1056 throw new Error('setTimeout has not been defined');
1057 }
1058 function defaultClearTimeout() {
1059 throw new Error('clearTimeout has not been defined');
1060 }
1061 (function () {
1062 try {
1063 if (typeof setTimeout === 'function') {
1064 cachedSetTimeout = setTimeout;
1065 } else {
1066 cachedSetTimeout = defaultSetTimout;
1067 }
1068 } catch (e) {
1069 cachedSetTimeout = defaultSetTimout;
1070 }
1071 try {
1072 if (typeof clearTimeout === 'function') {
1073 cachedClearTimeout = clearTimeout;
1074 } else {
1075 cachedClearTimeout = defaultClearTimeout;
1076 }
1077 } catch (e) {
1078 cachedClearTimeout = defaultClearTimeout;
1079 }
1080 })();
1081 function runTimeout(fun) {
1082 if (cachedSetTimeout === setTimeout) {
1083 //normal enviroments in sane situations
1084 return setTimeout(fun, 0);
1085 }
1086 // if setTimeout wasn't available but was latter defined
1087 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1088 cachedSetTimeout = setTimeout;
1089 return setTimeout(fun, 0);
1090 }
1091 try {
1092 // when when somebody has screwed with setTimeout but no I.E. maddness
1093 return cachedSetTimeout(fun, 0);
1094 } catch (e) {
1095 try {
1096 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1097 return cachedSetTimeout.call(null, fun, 0);
1098 } catch (e) {
1099 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
1100 return cachedSetTimeout.call(this, fun, 0);
1101 }
1102 }
1103 }
1104 function runClearTimeout(marker) {
1105 if (cachedClearTimeout === clearTimeout) {
1106 //normal enviroments in sane situations
1107 return clearTimeout(marker);
1108 }
1109 // if clearTimeout wasn't available but was latter defined
1110 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1111 cachedClearTimeout = clearTimeout;
1112 return clearTimeout(marker);
1113 }
1114 try {
1115 // when when somebody has screwed with setTimeout but no I.E. maddness
1116 return cachedClearTimeout(marker);
1117 } catch (e) {
1118 try {
1119 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1120 return cachedClearTimeout.call(null, marker);
1121 } catch (e) {
1122 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
1123 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1124 return cachedClearTimeout.call(this, marker);
1125 }
1126 }
1127 }
1128 var queue = [];
1129 var draining = false;
1130 var currentQueue;
1131 var queueIndex = -1;
1132
1133 function cleanUpNextTick() {
1134 if (!draining || !currentQueue) {
1135 return;
1136 }
1137 draining = false;
1138 if (currentQueue.length) {
1139 queue = currentQueue.concat(queue);
1140 } else {
1141 queueIndex = -1;
1142 }
1143 if (queue.length) {
1144 drainQueue();
1145 }
1146 }
1147
1148 function drainQueue() {
1149 if (draining) {
1150 return;
1151 }
1152 var timeout = runTimeout(cleanUpNextTick);
1153 draining = true;
1154
1155 var len = queue.length;
1156 while (len) {
1157 currentQueue = queue;
1158 queue = [];
1159 while (++queueIndex < len) {
1160 if (currentQueue) {
1161 currentQueue[queueIndex].run();
1162 }
1163 }
1164 queueIndex = -1;
1165 len = queue.length;
1166 }
1167 currentQueue = null;
1168 draining = false;
1169 runClearTimeout(timeout);
1170 }
1171
1172 process.nextTick = function (fun) {
1173 var args = new Array(arguments.length - 1);
1174 if (arguments.length > 1) {
1175 for (var i = 1; i < arguments.length; i++) {
1176 args[i - 1] = arguments[i];
1177 }
1178 }
1179 queue.push(new Item(fun, args));
1180 if (queue.length === 1 && !draining) {
1181 runTimeout(drainQueue);
1182 }
1183 };
1184
1185 // v8 likes predictible objects
1186 function Item(fun, array) {
1187 this.fun = fun;
1188 this.array = array;
1189 }
1190 Item.prototype.run = function () {
1191 this.fun.apply(null, this.array);
1192 };
1193 process.title = 'browser';
1194 process.browser = true;
1195 process.env = {};
1196 process.argv = [];
1197 process.version = ''; // empty string to avoid regexp issues
1198 process.versions = {};
1199
1200 function noop() {}
1201
1202 process.on = noop;
1203 process.addListener = noop;
1204 process.once = noop;
1205 process.off = noop;
1206 process.removeListener = noop;
1207 process.removeAllListeners = noop;
1208 process.emit = noop;
1209 process.prependListener = noop;
1210 process.prependOnceListener = noop;
1211
1212 process.listeners = function (name) {
1213 return [];
1214 };
1215
1216 process.binding = function (name) {
1217 throw new Error('process.binding is not supported');
1218 };
1219
1220 process.cwd = function () {
1221 return '/';
1222 };
1223 process.chdir = function (dir) {
1224 throw new Error('process.chdir is not supported');
1225 };
1226 process.umask = function () {
1227 return 0;
1228 };
1229
1230 /***/
1231},
1232/* 6 */
1233/***/function (module, exports, __webpack_require__) {
1234
1235 /**
1236 * This is the common logic for both the Node.js and web browser
1237 * implementations of `debug()`.
1238 *
1239 * Expose `debug()` as the module.
1240 */
1241
1242 exports = module.exports = debug.debug = debug;
1243 exports.coerce = coerce;
1244 exports.disable = disable;
1245 exports.enable = enable;
1246 exports.enabled = enabled;
1247 exports.humanize = __webpack_require__(7);
1248
1249 /**
1250 * The currently active debug mode names, and names to skip.
1251 */
1252
1253 exports.names = [];
1254 exports.skips = [];
1255
1256 /**
1257 * Map of special "%n" handling functions, for the debug "format" argument.
1258 *
1259 * Valid key names are a single, lowercased letter, i.e. "n".
1260 */
1261
1262 exports.formatters = {};
1263
1264 /**
1265 * Previously assigned color.
1266 */
1267
1268 var prevColor = 0;
1269
1270 /**
1271 * Previous log timestamp.
1272 */
1273
1274 var prevTime;
1275
1276 /**
1277 * Select a color.
1278 *
1279 * @return {Number}
1280 * @api private
1281 */
1282
1283 function selectColor() {
1284 return exports.colors[prevColor++ % exports.colors.length];
1285 }
1286
1287 /**
1288 * Create a debugger with the given `namespace`.
1289 *
1290 * @param {String} namespace
1291 * @return {Function}
1292 * @api public
1293 */
1294
1295 function debug(namespace) {
1296
1297 // define the `disabled` version
1298 function disabled() {}
1299 disabled.enabled = false;
1300
1301 // define the `enabled` version
1302 function enabled() {
1303
1304 var self = enabled;
1305
1306 // set `diff` timestamp
1307 var curr = +new Date();
1308 var ms = curr - (prevTime || curr);
1309 self.diff = ms;
1310 self.prev = prevTime;
1311 self.curr = curr;
1312 prevTime = curr;
1313
1314 // add the `color` if not set
1315 if (null == self.useColors) self.useColors = exports.useColors();
1316 if (null == self.color && self.useColors) self.color = selectColor();
1317
1318 var args = new Array(arguments.length);
1319 for (var i = 0; i < args.length; i++) {
1320 args[i] = arguments[i];
1321 }
1322
1323 args[0] = exports.coerce(args[0]);
1324
1325 if ('string' !== typeof args[0]) {
1326 // anything else let's inspect with %o
1327 args = ['%o'].concat(args);
1328 }
1329
1330 // apply any `formatters` transformations
1331 var index = 0;
1332 args[0] = args[0].replace(/%([a-z%])/g, function (match, format) {
1333 // if we encounter an escaped % then don't increase the array index
1334 if (match === '%%') return match;
1335 index++;
1336 var formatter = exports.formatters[format];
1337 if ('function' === typeof formatter) {
1338 var val = args[index];
1339 match = formatter.call(self, val);
1340
1341 // now we need to remove `args[index]` since it's inlined in the `format`
1342 args.splice(index, 1);
1343 index--;
1344 }
1345 return match;
1346 });
1347
1348 // apply env-specific formatting
1349 args = exports.formatArgs.apply(self, args);
1350
1351 var logFn = enabled.log || exports.log || console.log.bind(console);
1352 logFn.apply(self, args);
1353 }
1354 enabled.enabled = true;
1355
1356 var fn = exports.enabled(namespace) ? enabled : disabled;
1357
1358 fn.namespace = namespace;
1359
1360 return fn;
1361 }
1362
1363 /**
1364 * Enables a debug mode by namespaces. This can include modes
1365 * separated by a colon and wildcards.
1366 *
1367 * @param {String} namespaces
1368 * @api public
1369 */
1370
1371 function enable(namespaces) {
1372 exports.save(namespaces);
1373
1374 var split = (namespaces || '').split(/[\s,]+/);
1375 var len = split.length;
1376
1377 for (var i = 0; i < len; i++) {
1378 if (!split[i]) continue; // ignore empty strings
1379 namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
1380 if (namespaces[0] === '-') {
1381 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
1382 } else {
1383 exports.names.push(new RegExp('^' + namespaces + '$'));
1384 }
1385 }
1386 }
1387
1388 /**
1389 * Disable debug output.
1390 *
1391 * @api public
1392 */
1393
1394 function disable() {
1395 exports.enable('');
1396 }
1397
1398 /**
1399 * Returns true if the given mode name is enabled, false otherwise.
1400 *
1401 * @param {String} name
1402 * @return {Boolean}
1403 * @api public
1404 */
1405
1406 function enabled(name) {
1407 var i, len;
1408 for (i = 0, len = exports.skips.length; i < len; i++) {
1409 if (exports.skips[i].test(name)) {
1410 return false;
1411 }
1412 }
1413 for (i = 0, len = exports.names.length; i < len; i++) {
1414 if (exports.names[i].test(name)) {
1415 return true;
1416 }
1417 }
1418 return false;
1419 }
1420
1421 /**
1422 * Coerce `val`.
1423 *
1424 * @param {Mixed} val
1425 * @return {Mixed}
1426 * @api private
1427 */
1428
1429 function coerce(val) {
1430 if (val instanceof Error) return val.stack || val.message;
1431 return val;
1432 }
1433
1434 /***/
1435},
1436/* 7 */
1437/***/function (module, exports) {
1438
1439 /**
1440 * Helpers.
1441 */
1442
1443 var s = 1000;
1444 var m = s * 60;
1445 var h = m * 60;
1446 var d = h * 24;
1447 var y = d * 365.25;
1448
1449 /**
1450 * Parse or format the given `val`.
1451 *
1452 * Options:
1453 *
1454 * - `long` verbose formatting [false]
1455 *
1456 * @param {String|Number} val
1457 * @param {Object} options
1458 * @throws {Error} throw an error if val is not a non-empty string or a number
1459 * @return {String|Number}
1460 * @api public
1461 */
1462
1463 module.exports = function (val, options) {
1464 options = options || {};
1465 var type = typeof val === 'undefined' ? 'undefined' : _typeof(val);
1466 if (type === 'string' && val.length > 0) {
1467 return parse(val);
1468 } else if (type === 'number' && isNaN(val) === false) {
1469 return options.long ? fmtLong(val) : fmtShort(val);
1470 }
1471 throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
1472 };
1473
1474 /**
1475 * Parse the given `str` and return milliseconds.
1476 *
1477 * @param {String} str
1478 * @return {Number}
1479 * @api private
1480 */
1481
1482 function parse(str) {
1483 str = String(str);
1484 if (str.length > 10000) {
1485 return;
1486 }
1487 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
1488 if (!match) {
1489 return;
1490 }
1491 var n = parseFloat(match[1]);
1492 var type = (match[2] || 'ms').toLowerCase();
1493 switch (type) {
1494 case 'years':
1495 case 'year':
1496 case 'yrs':
1497 case 'yr':
1498 case 'y':
1499 return n * y;
1500 case 'days':
1501 case 'day':
1502 case 'd':
1503 return n * d;
1504 case 'hours':
1505 case 'hour':
1506 case 'hrs':
1507 case 'hr':
1508 case 'h':
1509 return n * h;
1510 case 'minutes':
1511 case 'minute':
1512 case 'mins':
1513 case 'min':
1514 case 'm':
1515 return n * m;
1516 case 'seconds':
1517 case 'second':
1518 case 'secs':
1519 case 'sec':
1520 case 's':
1521 return n * s;
1522 case 'milliseconds':
1523 case 'millisecond':
1524 case 'msecs':
1525 case 'msec':
1526 case 'ms':
1527 return n;
1528 default:
1529 return undefined;
1530 }
1531 }
1532
1533 /**
1534 * Short format for `ms`.
1535 *
1536 * @param {Number} ms
1537 * @return {String}
1538 * @api private
1539 */
1540
1541 function fmtShort(ms) {
1542 if (ms >= d) {
1543 return Math.round(ms / d) + 'd';
1544 }
1545 if (ms >= h) {
1546 return Math.round(ms / h) + 'h';
1547 }
1548 if (ms >= m) {
1549 return Math.round(ms / m) + 'm';
1550 }
1551 if (ms >= s) {
1552 return Math.round(ms / s) + 's';
1553 }
1554 return ms + 'ms';
1555 }
1556
1557 /**
1558 * Long format for `ms`.
1559 *
1560 * @param {Number} ms
1561 * @return {String}
1562 * @api private
1563 */
1564
1565 function fmtLong(ms) {
1566 return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms';
1567 }
1568
1569 /**
1570 * Pluralization helper.
1571 */
1572
1573 function plural(ms, n, name) {
1574 if (ms < n) {
1575 return;
1576 }
1577 if (ms < n * 1.5) {
1578 return Math.floor(ms / n) + ' ' + name;
1579 }
1580 return Math.ceil(ms / n) + ' ' + name + 's';
1581 }
1582
1583 /***/
1584},
1585/* 8 */
1586/***/function (module, exports, __webpack_require__) {
1587
1588 /**
1589 * Module dependencies.
1590 */
1591
1592 var debug = __webpack_require__(9)('socket.io-parser');
1593 var json = __webpack_require__(12);
1594 var Emitter = __webpack_require__(15);
1595 var binary = __webpack_require__(16);
1596 var isBuf = __webpack_require__(18);
1597
1598 /**
1599 * Protocol version.
1600 *
1601 * @api public
1602 */
1603
1604 exports.protocol = 4;
1605
1606 /**
1607 * Packet types.
1608 *
1609 * @api public
1610 */
1611
1612 exports.types = ['CONNECT', 'DISCONNECT', 'EVENT', 'ACK', 'ERROR', 'BINARY_EVENT', 'BINARY_ACK'];
1613
1614 /**
1615 * Packet type `connect`.
1616 *
1617 * @api public
1618 */
1619
1620 exports.CONNECT = 0;
1621
1622 /**
1623 * Packet type `disconnect`.
1624 *
1625 * @api public
1626 */
1627
1628 exports.DISCONNECT = 1;
1629
1630 /**
1631 * Packet type `event`.
1632 *
1633 * @api public
1634 */
1635
1636 exports.EVENT = 2;
1637
1638 /**
1639 * Packet type `ack`.
1640 *
1641 * @api public
1642 */
1643
1644 exports.ACK = 3;
1645
1646 /**
1647 * Packet type `error`.
1648 *
1649 * @api public
1650 */
1651
1652 exports.ERROR = 4;
1653
1654 /**
1655 * Packet type 'binary event'
1656 *
1657 * @api public
1658 */
1659
1660 exports.BINARY_EVENT = 5;
1661
1662 /**
1663 * Packet type `binary ack`. For acks with binary arguments.
1664 *
1665 * @api public
1666 */
1667
1668 exports.BINARY_ACK = 6;
1669
1670 /**
1671 * Encoder constructor.
1672 *
1673 * @api public
1674 */
1675
1676 exports.Encoder = Encoder;
1677
1678 /**
1679 * Decoder constructor.
1680 *
1681 * @api public
1682 */
1683
1684 exports.Decoder = Decoder;
1685
1686 /**
1687 * A socket.io Encoder instance
1688 *
1689 * @api public
1690 */
1691
1692 function Encoder() {}
1693
1694 /**
1695 * Encode a packet as a single string if non-binary, or as a
1696 * buffer sequence, depending on packet type.
1697 *
1698 * @param {Object} obj - packet object
1699 * @param {Function} callback - function to handle encodings (likely engine.write)
1700 * @return Calls callback with Array of encodings
1701 * @api public
1702 */
1703
1704 Encoder.prototype.encode = function (obj, callback) {
1705 debug('encoding packet %j', obj);
1706
1707 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
1708 encodeAsBinary(obj, callback);
1709 } else {
1710 var encoding = encodeAsString(obj);
1711 callback([encoding]);
1712 }
1713 };
1714
1715 /**
1716 * Encode packet as string.
1717 *
1718 * @param {Object} packet
1719 * @return {String} encoded
1720 * @api private
1721 */
1722
1723 function encodeAsString(obj) {
1724 var str = '';
1725 var nsp = false;
1726
1727 // first is type
1728 str += obj.type;
1729
1730 // attachments if we have them
1731 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
1732 str += obj.attachments;
1733 str += '-';
1734 }
1735
1736 // if we have a namespace other than `/`
1737 // we append it followed by a comma `,`
1738 if (obj.nsp && '/' != obj.nsp) {
1739 nsp = true;
1740 str += obj.nsp;
1741 }
1742
1743 // immediately followed by the id
1744 if (null != obj.id) {
1745 if (nsp) {
1746 str += ',';
1747 nsp = false;
1748 }
1749 str += obj.id;
1750 }
1751
1752 // json data
1753 if (null != obj.data) {
1754 if (nsp) str += ',';
1755 str += json.stringify(obj.data);
1756 }
1757
1758 debug('encoded %j as %s', obj, str);
1759 return str;
1760 }
1761
1762 /**
1763 * Encode packet as 'buffer sequence' by removing blobs, and
1764 * deconstructing packet into object with placeholders and
1765 * a list of buffers.
1766 *
1767 * @param {Object} packet
1768 * @return {Buffer} encoded
1769 * @api private
1770 */
1771
1772 function encodeAsBinary(obj, callback) {
1773
1774 function writeEncoding(bloblessData) {
1775 var deconstruction = binary.deconstructPacket(bloblessData);
1776 var pack = encodeAsString(deconstruction.packet);
1777 var buffers = deconstruction.buffers;
1778
1779 buffers.unshift(pack); // add packet info to beginning of data list
1780 callback(buffers); // write all the buffers
1781 }
1782
1783 binary.removeBlobs(obj, writeEncoding);
1784 }
1785
1786 /**
1787 * A socket.io Decoder instance
1788 *
1789 * @return {Object} decoder
1790 * @api public
1791 */
1792
1793 function Decoder() {
1794 this.reconstructor = null;
1795 }
1796
1797 /**
1798 * Mix in `Emitter` with Decoder.
1799 */
1800
1801 Emitter(Decoder.prototype);
1802
1803 /**
1804 * Decodes an ecoded packet string into packet JSON.
1805 *
1806 * @param {String} obj - encoded packet
1807 * @return {Object} packet
1808 * @api public
1809 */
1810
1811 Decoder.prototype.add = function (obj) {
1812 var packet;
1813 if ('string' == typeof obj) {
1814 packet = decodeString(obj);
1815 if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) {
1816 // binary packet's json
1817 this.reconstructor = new BinaryReconstructor(packet);
1818
1819 // no attachments, labeled binary but no binary data to follow
1820 if (this.reconstructor.reconPack.attachments === 0) {
1821 this.emit('decoded', packet);
1822 }
1823 } else {
1824 // non-binary full packet
1825 this.emit('decoded', packet);
1826 }
1827 } else if (isBuf(obj) || obj.base64) {
1828 // raw binary data
1829 if (!this.reconstructor) {
1830 throw new Error('got binary data when not reconstructing a packet');
1831 } else {
1832 packet = this.reconstructor.takeBinaryData(obj);
1833 if (packet) {
1834 // received final buffer
1835 this.reconstructor = null;
1836 this.emit('decoded', packet);
1837 }
1838 }
1839 } else {
1840 throw new Error('Unknown type: ' + obj);
1841 }
1842 };
1843
1844 /**
1845 * Decode a packet String (JSON data)
1846 *
1847 * @param {String} str
1848 * @return {Object} packet
1849 * @api private
1850 */
1851
1852 function decodeString(str) {
1853 var p = {};
1854 var i = 0;
1855
1856 // look up type
1857 p.type = Number(str.charAt(0));
1858 if (null == exports.types[p.type]) return error();
1859
1860 // look up attachments if type binary
1861 if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
1862 var buf = '';
1863 while (str.charAt(++i) != '-') {
1864 buf += str.charAt(i);
1865 if (i == str.length) break;
1866 }
1867 if (buf != Number(buf) || str.charAt(i) != '-') {
1868 throw new Error('Illegal attachments');
1869 }
1870 p.attachments = Number(buf);
1871 }
1872
1873 // look up namespace (if any)
1874 if ('/' == str.charAt(i + 1)) {
1875 p.nsp = '';
1876 while (++i) {
1877 var c = str.charAt(i);
1878 if (',' == c) break;
1879 p.nsp += c;
1880 if (i == str.length) break;
1881 }
1882 } else {
1883 p.nsp = '/';
1884 }
1885
1886 // look up id
1887 var next = str.charAt(i + 1);
1888 if ('' !== next && Number(next) == next) {
1889 p.id = '';
1890 while (++i) {
1891 var c = str.charAt(i);
1892 if (null == c || Number(c) != c) {
1893 --i;
1894 break;
1895 }
1896 p.id += str.charAt(i);
1897 if (i == str.length) break;
1898 }
1899 p.id = Number(p.id);
1900 }
1901
1902 // look up json data
1903 if (str.charAt(++i)) {
1904 p = tryParse(p, str.substr(i));
1905 }
1906
1907 debug('decoded %s as %j', str, p);
1908 return p;
1909 }
1910
1911 function tryParse(p, str) {
1912 try {
1913 p.data = json.parse(str);
1914 } catch (e) {
1915 return error();
1916 }
1917 return p;
1918 };
1919
1920 /**
1921 * Deallocates a parser's resources
1922 *
1923 * @api public
1924 */
1925
1926 Decoder.prototype.destroy = function () {
1927 if (this.reconstructor) {
1928 this.reconstructor.finishedReconstruction();
1929 }
1930 };
1931
1932 /**
1933 * A manager of a binary event's 'buffer sequence'. Should
1934 * be constructed whenever a packet of type BINARY_EVENT is
1935 * decoded.
1936 *
1937 * @param {Object} packet
1938 * @return {BinaryReconstructor} initialized reconstructor
1939 * @api private
1940 */
1941
1942 function BinaryReconstructor(packet) {
1943 this.reconPack = packet;
1944 this.buffers = [];
1945 }
1946
1947 /**
1948 * Method to be called when binary data received from connection
1949 * after a BINARY_EVENT packet.
1950 *
1951 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
1952 * @return {null | Object} returns null if more binary data is expected or
1953 * a reconstructed packet object if all buffers have been received.
1954 * @api private
1955 */
1956
1957 BinaryReconstructor.prototype.takeBinaryData = function (binData) {
1958 this.buffers.push(binData);
1959 if (this.buffers.length == this.reconPack.attachments) {
1960 // done with buffer list
1961 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
1962 this.finishedReconstruction();
1963 return packet;
1964 }
1965 return null;
1966 };
1967
1968 /**
1969 * Cleans up binary packet reconstruction variables.
1970 *
1971 * @api private
1972 */
1973
1974 BinaryReconstructor.prototype.finishedReconstruction = function () {
1975 this.reconPack = null;
1976 this.buffers = [];
1977 };
1978
1979 function error(data) {
1980 return {
1981 type: exports.ERROR,
1982 data: 'parser error'
1983 };
1984 }
1985
1986 /***/
1987},
1988/* 9 */
1989/***/function (module, exports, __webpack_require__) {
1990
1991 /**
1992 * This is the web browser implementation of `debug()`.
1993 *
1994 * Expose `debug()` as the module.
1995 */
1996
1997 exports = module.exports = __webpack_require__(10);
1998 exports.log = log;
1999 exports.formatArgs = formatArgs;
2000 exports.save = save;
2001 exports.load = load;
2002 exports.useColors = useColors;
2003 exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
2004
2005 /**
2006 * Colors.
2007 */
2008
2009 exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson'];
2010
2011 /**
2012 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
2013 * and the Firebug extension (any Firefox version) are known
2014 * to support "%c" CSS customizations.
2015 *
2016 * TODO: add a `localStorage` variable to explicitly enable/disable colors
2017 */
2018
2019 function useColors() {
2020 // is webkit? http://stackoverflow.com/a/16459606/376773
2021 return 'WebkitAppearance' in document.documentElement.style ||
2022 // is firebug? http://stackoverflow.com/a/398120/376773
2023 window.console && (console.firebug || console.exception && console.table) ||
2024 // is firefox >= v31?
2025 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
2026 navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31;
2027 }
2028
2029 /**
2030 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
2031 */
2032
2033 exports.formatters.j = function (v) {
2034 return JSON.stringify(v);
2035 };
2036
2037 /**
2038 * Colorize log arguments if enabled.
2039 *
2040 * @api public
2041 */
2042
2043 function formatArgs() {
2044 var args = arguments;
2045 var useColors = this.useColors;
2046
2047 args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
2048
2049 if (!useColors) return args;
2050
2051 var c = 'color: ' + this.color;
2052 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
2053
2054 // the final "%c" is somewhat tricky, because there could be other
2055 // arguments passed either before or after the %c, so we need to
2056 // figure out the correct index to insert the CSS into
2057 var index = 0;
2058 var lastC = 0;
2059 args[0].replace(/%[a-z%]/g, function (match) {
2060 if ('%%' === match) return;
2061 index++;
2062 if ('%c' === match) {
2063 // we only are interested in the *last* %c
2064 // (the user may have provided their own)
2065 lastC = index;
2066 }
2067 });
2068
2069 args.splice(lastC, 0, c);
2070 return args;
2071 }
2072
2073 /**
2074 * Invokes `console.log()` when available.
2075 * No-op when `console.log` is not a "function".
2076 *
2077 * @api public
2078 */
2079
2080 function log() {
2081 // this hackery is required for IE8/9, where
2082 // the `console.log` function doesn't have 'apply'
2083 return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
2084 }
2085
2086 /**
2087 * Save `namespaces`.
2088 *
2089 * @param {String} namespaces
2090 * @api private
2091 */
2092
2093 function save(namespaces) {
2094 try {
2095 if (null == namespaces) {
2096 exports.storage.removeItem('debug');
2097 } else {
2098 exports.storage.debug = namespaces;
2099 }
2100 } catch (e) {}
2101 }
2102
2103 /**
2104 * Load `namespaces`.
2105 *
2106 * @return {String} returns the previously persisted debug modes
2107 * @api private
2108 */
2109
2110 function load() {
2111 var r;
2112 try {
2113 r = exports.storage.debug;
2114 } catch (e) {}
2115 return r;
2116 }
2117
2118 /**
2119 * Enable namespaces listed in `localStorage.debug` initially.
2120 */
2121
2122 exports.enable(load());
2123
2124 /**
2125 * Localstorage attempts to return the localstorage.
2126 *
2127 * This is necessary because safari throws
2128 * when a user disables cookies/localstorage
2129 * and you attempt to access it.
2130 *
2131 * @return {LocalStorage}
2132 * @api private
2133 */
2134
2135 function localstorage() {
2136 try {
2137 return window.localStorage;
2138 } catch (e) {}
2139 }
2140
2141 /***/
2142},
2143/* 10 */
2144/***/function (module, exports, __webpack_require__) {
2145
2146 /**
2147 * This is the common logic for both the Node.js and web browser
2148 * implementations of `debug()`.
2149 *
2150 * Expose `debug()` as the module.
2151 */
2152
2153 exports = module.exports = debug;
2154 exports.coerce = coerce;
2155 exports.disable = disable;
2156 exports.enable = enable;
2157 exports.enabled = enabled;
2158 exports.humanize = __webpack_require__(11);
2159
2160 /**
2161 * The currently active debug mode names, and names to skip.
2162 */
2163
2164 exports.names = [];
2165 exports.skips = [];
2166
2167 /**
2168 * Map of special "%n" handling functions, for the debug "format" argument.
2169 *
2170 * Valid key names are a single, lowercased letter, i.e. "n".
2171 */
2172
2173 exports.formatters = {};
2174
2175 /**
2176 * Previously assigned color.
2177 */
2178
2179 var prevColor = 0;
2180
2181 /**
2182 * Previous log timestamp.
2183 */
2184
2185 var prevTime;
2186
2187 /**
2188 * Select a color.
2189 *
2190 * @return {Number}
2191 * @api private
2192 */
2193
2194 function selectColor() {
2195 return exports.colors[prevColor++ % exports.colors.length];
2196 }
2197
2198 /**
2199 * Create a debugger with the given `namespace`.
2200 *
2201 * @param {String} namespace
2202 * @return {Function}
2203 * @api public
2204 */
2205
2206 function debug(namespace) {
2207
2208 // define the `disabled` version
2209 function disabled() {}
2210 disabled.enabled = false;
2211
2212 // define the `enabled` version
2213 function enabled() {
2214
2215 var self = enabled;
2216
2217 // set `diff` timestamp
2218 var curr = +new Date();
2219 var ms = curr - (prevTime || curr);
2220 self.diff = ms;
2221 self.prev = prevTime;
2222 self.curr = curr;
2223 prevTime = curr;
2224
2225 // add the `color` if not set
2226 if (null == self.useColors) self.useColors = exports.useColors();
2227 if (null == self.color && self.useColors) self.color = selectColor();
2228
2229 var args = Array.prototype.slice.call(arguments);
2230
2231 args[0] = exports.coerce(args[0]);
2232
2233 if ('string' !== typeof args[0]) {
2234 // anything else let's inspect with %o
2235 args = ['%o'].concat(args);
2236 }
2237
2238 // apply any `formatters` transformations
2239 var index = 0;
2240 args[0] = args[0].replace(/%([a-z%])/g, function (match, format) {
2241 // if we encounter an escaped % then don't increase the array index
2242 if (match === '%%') return match;
2243 index++;
2244 var formatter = exports.formatters[format];
2245 if ('function' === typeof formatter) {
2246 var val = args[index];
2247 match = formatter.call(self, val);
2248
2249 // now we need to remove `args[index]` since it's inlined in the `format`
2250 args.splice(index, 1);
2251 index--;
2252 }
2253 return match;
2254 });
2255
2256 if ('function' === typeof exports.formatArgs) {
2257 args = exports.formatArgs.apply(self, args);
2258 }
2259 var logFn = enabled.log || exports.log || console.log.bind(console);
2260 logFn.apply(self, args);
2261 }
2262 enabled.enabled = true;
2263
2264 var fn = exports.enabled(namespace) ? enabled : disabled;
2265
2266 fn.namespace = namespace;
2267
2268 return fn;
2269 }
2270
2271 /**
2272 * Enables a debug mode by namespaces. This can include modes
2273 * separated by a colon and wildcards.
2274 *
2275 * @param {String} namespaces
2276 * @api public
2277 */
2278
2279 function enable(namespaces) {
2280 exports.save(namespaces);
2281
2282 var split = (namespaces || '').split(/[\s,]+/);
2283 var len = split.length;
2284
2285 for (var i = 0; i < len; i++) {
2286 if (!split[i]) continue; // ignore empty strings
2287 namespaces = split[i].replace(/\*/g, '.*?');
2288 if (namespaces[0] === '-') {
2289 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
2290 } else {
2291 exports.names.push(new RegExp('^' + namespaces + '$'));
2292 }
2293 }
2294 }
2295
2296 /**
2297 * Disable debug output.
2298 *
2299 * @api public
2300 */
2301
2302 function disable() {
2303 exports.enable('');
2304 }
2305
2306 /**
2307 * Returns true if the given mode name is enabled, false otherwise.
2308 *
2309 * @param {String} name
2310 * @return {Boolean}
2311 * @api public
2312 */
2313
2314 function enabled(name) {
2315 var i, len;
2316 for (i = 0, len = exports.skips.length; i < len; i++) {
2317 if (exports.skips[i].test(name)) {
2318 return false;
2319 }
2320 }
2321 for (i = 0, len = exports.names.length; i < len; i++) {
2322 if (exports.names[i].test(name)) {
2323 return true;
2324 }
2325 }
2326 return false;
2327 }
2328
2329 /**
2330 * Coerce `val`.
2331 *
2332 * @param {Mixed} val
2333 * @return {Mixed}
2334 * @api private
2335 */
2336
2337 function coerce(val) {
2338 if (val instanceof Error) return val.stack || val.message;
2339 return val;
2340 }
2341
2342 /***/
2343},
2344/* 11 */
2345/***/function (module, exports) {
2346
2347 /**
2348 * Helpers.
2349 */
2350
2351 var s = 1000;
2352 var m = s * 60;
2353 var h = m * 60;
2354 var d = h * 24;
2355 var y = d * 365.25;
2356
2357 /**
2358 * Parse or format the given `val`.
2359 *
2360 * Options:
2361 *
2362 * - `long` verbose formatting [false]
2363 *
2364 * @param {String|Number} val
2365 * @param {Object} options
2366 * @return {String|Number}
2367 * @api public
2368 */
2369
2370 module.exports = function (val, options) {
2371 options = options || {};
2372 if ('string' == typeof val) return parse(val);
2373 return options.long ? long(val) : short(val);
2374 };
2375
2376 /**
2377 * Parse the given `str` and return milliseconds.
2378 *
2379 * @param {String} str
2380 * @return {Number}
2381 * @api private
2382 */
2383
2384 function parse(str) {
2385 str = '' + str;
2386 if (str.length > 10000) return;
2387 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
2388 if (!match) return;
2389 var n = parseFloat(match[1]);
2390 var type = (match[2] || 'ms').toLowerCase();
2391 switch (type) {
2392 case 'years':
2393 case 'year':
2394 case 'yrs':
2395 case 'yr':
2396 case 'y':
2397 return n * y;
2398 case 'days':
2399 case 'day':
2400 case 'd':
2401 return n * d;
2402 case 'hours':
2403 case 'hour':
2404 case 'hrs':
2405 case 'hr':
2406 case 'h':
2407 return n * h;
2408 case 'minutes':
2409 case 'minute':
2410 case 'mins':
2411 case 'min':
2412 case 'm':
2413 return n * m;
2414 case 'seconds':
2415 case 'second':
2416 case 'secs':
2417 case 'sec':
2418 case 's':
2419 return n * s;
2420 case 'milliseconds':
2421 case 'millisecond':
2422 case 'msecs':
2423 case 'msec':
2424 case 'ms':
2425 return n;
2426 }
2427 }
2428
2429 /**
2430 * Short format for `ms`.
2431 *
2432 * @param {Number} ms
2433 * @return {String}
2434 * @api private
2435 */
2436
2437 function short(ms) {
2438 if (ms >= d) return Math.round(ms / d) + 'd';
2439 if (ms >= h) return Math.round(ms / h) + 'h';
2440 if (ms >= m) return Math.round(ms / m) + 'm';
2441 if (ms >= s) return Math.round(ms / s) + 's';
2442 return ms + 'ms';
2443 }
2444
2445 /**
2446 * Long format for `ms`.
2447 *
2448 * @param {Number} ms
2449 * @return {String}
2450 * @api private
2451 */
2452
2453 function long(ms) {
2454 return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms';
2455 }
2456
2457 /**
2458 * Pluralization helper.
2459 */
2460
2461 function plural(ms, n, name) {
2462 if (ms < n) return;
2463 if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
2464 return Math.ceil(ms / n) + ' ' + name + 's';
2465 }
2466
2467 /***/
2468},
2469/* 12 */
2470/***/function (module, exports, __webpack_require__) {
2471
2472 var __WEBPACK_AMD_DEFINE_RESULT__; /* WEBPACK VAR INJECTION */(function (module, global) {
2473 /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
2474 ;(function () {
2475 // Detect the `define` function exposed by asynchronous module loaders. The
2476 // strict `define` check is necessary for compatibility with `r.js`.
2477 var isLoader = "function" === "function" && __webpack_require__(14);
2478
2479 // A set of types used to distinguish objects from primitives.
2480 var objectTypes = {
2481 "function": true,
2482 "object": true
2483 };
2484
2485 // Detect the `exports` object exposed by CommonJS implementations.
2486 var freeExports = objectTypes[typeof exports === 'undefined' ? 'undefined' : _typeof(exports)] && exports && !exports.nodeType && exports;
2487
2488 // Use the `global` object exposed by Node (including Browserify via
2489 // `insert-module-globals`), Narwhal, and Ringo as the default context,
2490 // and the `window` object in browsers. Rhino exports a `global` function
2491 // instead.
2492 var root = objectTypes[typeof window === 'undefined' ? 'undefined' : _typeof(window)] && window || this,
2493 freeGlobal = freeExports && objectTypes[typeof module === 'undefined' ? 'undefined' : _typeof(module)] && module && !module.nodeType && (typeof global === 'undefined' ? 'undefined' : _typeof(global)) == "object" && global;
2494
2495 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
2496 root = freeGlobal;
2497 }
2498
2499 // Public: Initializes JSON 3 using the given `context` object, attaching the
2500 // `stringify` and `parse` functions to the specified `exports` object.
2501 function runInContext(context, exports) {
2502 context || (context = root["Object"]());
2503 exports || (exports = root["Object"]());
2504
2505 // Native constructor aliases.
2506 var Number = context["Number"] || root["Number"],
2507 String = context["String"] || root["String"],
2508 Object = context["Object"] || root["Object"],
2509 Date = context["Date"] || root["Date"],
2510 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
2511 TypeError = context["TypeError"] || root["TypeError"],
2512 Math = context["Math"] || root["Math"],
2513 nativeJSON = context["JSON"] || root["JSON"];
2514
2515 // Delegate to the native `stringify` and `parse` implementations.
2516 if ((typeof nativeJSON === 'undefined' ? 'undefined' : _typeof(nativeJSON)) == "object" && nativeJSON) {
2517 exports.stringify = nativeJSON.stringify;
2518 exports.parse = nativeJSON.parse;
2519 }
2520
2521 // Convenience aliases.
2522 var objectProto = Object.prototype,
2523 getClass = objectProto.toString,
2524 _isProperty,
2525 _forEach,
2526 undef;
2527
2528 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
2529 var isExtended = new Date(-3509827334573292);
2530 try {
2531 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
2532 // results for certain dates in Opera >= 10.53.
2533 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
2534 // Safari < 2.0.2 stores the internal millisecond time value correctly,
2535 // but clips the values returned by the date methods to the range of
2536 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
2537 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
2538 } catch (exception) {}
2539
2540 // Internal: Determines whether the native `JSON.stringify` and `parse`
2541 // implementations are spec-compliant. Based on work by Ken Snyder.
2542 function has(name) {
2543 if (has[name] !== undef) {
2544 // Return cached feature test result.
2545 return has[name];
2546 }
2547 var isSupported;
2548 if (name == "bug-string-char-index") {
2549 // IE <= 7 doesn't support accessing string characters using square
2550 // bracket notation. IE 8 only supports this for primitives.
2551 isSupported = "a"[0] != "a";
2552 } else if (name == "json") {
2553 // Indicates whether both `JSON.stringify` and `JSON.parse` are
2554 // supported.
2555 isSupported = has("json-stringify") && has("json-parse");
2556 } else {
2557 var value,
2558 serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
2559 // Test `JSON.stringify`.
2560 if (name == "json-stringify") {
2561 var stringify = exports.stringify,
2562 stringifySupported = typeof stringify == "function" && isExtended;
2563 if (stringifySupported) {
2564 // A test function object with a custom `toJSON` method.
2565 (value = function value() {
2566 return 1;
2567 }).toJSON = value;
2568 try {
2569 stringifySupported =
2570 // Firefox 3.1b1 and b2 serialize string, number, and boolean
2571 // primitives as object literals.
2572 stringify(0) === "0" &&
2573 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
2574 // literals.
2575 stringify(new Number()) === "0" && stringify(new String()) == '""' &&
2576 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
2577 // does not define a canonical JSON representation (this applies to
2578 // objects with `toJSON` properties as well, *unless* they are nested
2579 // within an object or array).
2580 stringify(getClass) === undef &&
2581 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
2582 // FF 3.1b3 pass this test.
2583 stringify(undef) === undef &&
2584 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
2585 // respectively, if the value is omitted entirely.
2586 stringify() === undef &&
2587 // FF 3.1b1, 2 throw an error if the given value is not a number,
2588 // string, array, object, Boolean, or `null` literal. This applies to
2589 // objects with custom `toJSON` methods as well, unless they are nested
2590 // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
2591 // methods entirely.
2592 stringify(value) === "1" && stringify([value]) == "[1]" &&
2593 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
2594 // `"[null]"`.
2595 stringify([undef]) == "[null]" &&
2596 // YUI 3.0.0b1 fails to serialize `null` literals.
2597 stringify(null) == "null" &&
2598 // FF 3.1b1, 2 halts serialization if an array contains a function:
2599 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
2600 // elides non-JSON values from objects and arrays, unless they
2601 // define custom `toJSON` methods.
2602 stringify([undef, getClass, null]) == "[null,null,null]" &&
2603 // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
2604 // where character escape codes are expected (e.g., `\b` => `\u0008`).
2605 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
2606 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
2607 stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
2608 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
2609 // serialize extended years.
2610 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
2611 // The milliseconds are optional in ES 5, but required in 5.1.
2612 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
2613 // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
2614 // four-digit years instead of six-digit years. Credits: @Yaffle.
2615 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
2616 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
2617 // values less than 1000. Credits: @Yaffle.
2618 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
2619 } catch (exception) {
2620 stringifySupported = false;
2621 }
2622 }
2623 isSupported = stringifySupported;
2624 }
2625 // Test `JSON.parse`.
2626 if (name == "json-parse") {
2627 var parse = exports.parse;
2628 if (typeof parse == "function") {
2629 try {
2630 // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
2631 // Conforming implementations should also coerce the initial argument to
2632 // a string prior to parsing.
2633 if (parse("0") === 0 && !parse(false)) {
2634 // Simple parsing test.
2635 value = parse(serialized);
2636 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
2637 if (parseSupported) {
2638 try {
2639 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
2640 parseSupported = !parse('"\t"');
2641 } catch (exception) {}
2642 if (parseSupported) {
2643 try {
2644 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
2645 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
2646 // certain octal literals.
2647 parseSupported = parse("01") !== 1;
2648 } catch (exception) {}
2649 }
2650 if (parseSupported) {
2651 try {
2652 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
2653 // points. These environments, along with FF 3.1b1 and 2,
2654 // also allow trailing commas in JSON objects and arrays.
2655 parseSupported = parse("1.") !== 1;
2656 } catch (exception) {}
2657 }
2658 }
2659 }
2660 } catch (exception) {
2661 parseSupported = false;
2662 }
2663 }
2664 isSupported = parseSupported;
2665 }
2666 }
2667 return has[name] = !!isSupported;
2668 }
2669
2670 if (!has("json")) {
2671 // Common `[[Class]]` name aliases.
2672 var functionClass = "[object Function]",
2673 dateClass = "[object Date]",
2674 numberClass = "[object Number]",
2675 stringClass = "[object String]",
2676 arrayClass = "[object Array]",
2677 booleanClass = "[object Boolean]";
2678
2679 // Detect incomplete support for accessing string characters by index.
2680 var charIndexBuggy = has("bug-string-char-index");
2681
2682 // Define additional utility methods if the `Date` methods are buggy.
2683 if (!isExtended) {
2684 var floor = Math.floor;
2685 // A mapping between the months of the year and the number of days between
2686 // January 1st and the first of the respective month.
2687 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
2688 // Internal: Calculates the number of days between the Unix epoch and the
2689 // first day of the given month.
2690 var getDay = function getDay(year, month) {
2691 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
2692 };
2693 }
2694
2695 // Internal: Determines if a property is a direct property of the given
2696 // object. Delegates to the native `Object#hasOwnProperty` method.
2697 if (!(_isProperty = objectProto.hasOwnProperty)) {
2698 _isProperty = function isProperty(property) {
2699 var members = {},
2700 constructor;
2701 if ((members.__proto__ = null, members.__proto__ = {
2702 // The *proto* property cannot be set multiple times in recent
2703 // versions of Firefox and SeaMonkey.
2704 "toString": 1
2705 }, members).toString != getClass) {
2706 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
2707 // supports the mutable *proto* property.
2708 _isProperty = function isProperty(property) {
2709 // Capture and break the object's prototype chain (see section 8.6.2
2710 // of the ES 5.1 spec). The parenthesized expression prevents an
2711 // unsafe transformation by the Closure Compiler.
2712 var original = this.__proto__,
2713 result = property in (this.__proto__ = null, this);
2714 // Restore the original prototype chain.
2715 this.__proto__ = original;
2716 return result;
2717 };
2718 } else {
2719 // Capture a reference to the top-level `Object` constructor.
2720 constructor = members.constructor;
2721 // Use the `constructor` property to simulate `Object#hasOwnProperty` in
2722 // other environments.
2723 _isProperty = function isProperty(property) {
2724 var parent = (this.constructor || constructor).prototype;
2725 return property in this && !(property in parent && this[property] === parent[property]);
2726 };
2727 }
2728 members = null;
2729 return _isProperty.call(this, property);
2730 };
2731 }
2732
2733 // Internal: Normalizes the `for...in` iteration algorithm across
2734 // environments. Each enumerated key is yielded to a `callback` function.
2735 _forEach = function forEach(object, callback) {
2736 var size = 0,
2737 Properties,
2738 members,
2739 property;
2740
2741 // Tests for bugs in the current environment's `for...in` algorithm. The
2742 // `valueOf` property inherits the non-enumerable flag from
2743 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
2744 (Properties = function Properties() {
2745 this.valueOf = 0;
2746 }).prototype.valueOf = 0;
2747
2748 // Iterate over a new instance of the `Properties` class.
2749 members = new Properties();
2750 for (property in members) {
2751 // Ignore all properties inherited from `Object.prototype`.
2752 if (_isProperty.call(members, property)) {
2753 size++;
2754 }
2755 }
2756 Properties = members = null;
2757
2758 // Normalize the iteration algorithm.
2759 if (!size) {
2760 // A list of non-enumerable properties inherited from `Object.prototype`.
2761 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
2762 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
2763 // properties.
2764 _forEach = function forEach(object, callback) {
2765 var isFunction = getClass.call(object) == functionClass,
2766 property,
2767 length;
2768 var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[_typeof(object.hasOwnProperty)] && object.hasOwnProperty || _isProperty;
2769 for (property in object) {
2770 // Gecko <= 1.0 enumerates the `prototype` property of functions under
2771 // certain conditions; IE does not.
2772 if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
2773 callback(property);
2774 }
2775 }
2776 // Manually invoke the callback for each non-enumerable property.
2777 for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)) {}
2778 };
2779 } else if (size == 2) {
2780 // Safari <= 2.0.4 enumerates shadowed properties twice.
2781 _forEach = function forEach(object, callback) {
2782 // Create a set of iterated properties.
2783 var members = {},
2784 isFunction = getClass.call(object) == functionClass,
2785 property;
2786 for (property in object) {
2787 // Store each property name to prevent double enumeration. The
2788 // `prototype` property of functions is not enumerated due to cross-
2789 // environment inconsistencies.
2790 if (!(isFunction && property == "prototype") && !_isProperty.call(members, property) && (members[property] = 1) && _isProperty.call(object, property)) {
2791 callback(property);
2792 }
2793 }
2794 };
2795 } else {
2796 // No bugs detected; use the standard `for...in` algorithm.
2797 _forEach = function forEach(object, callback) {
2798 var isFunction = getClass.call(object) == functionClass,
2799 property,
2800 isConstructor;
2801 for (property in object) {
2802 if (!(isFunction && property == "prototype") && _isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
2803 callback(property);
2804 }
2805 }
2806 // Manually invoke the callback for the `constructor` property due to
2807 // cross-environment inconsistencies.
2808 if (isConstructor || _isProperty.call(object, property = "constructor")) {
2809 callback(property);
2810 }
2811 };
2812 }
2813 return _forEach(object, callback);
2814 };
2815
2816 // Public: Serializes a JavaScript `value` as a JSON string. The optional
2817 // `filter` argument may specify either a function that alters how object and
2818 // array members are serialized, or an array of strings and numbers that
2819 // indicates which properties should be serialized. The optional `width`
2820 // argument may be either a string or number that specifies the indentation
2821 // level of the output.
2822 if (!has("json-stringify")) {
2823 // Internal: A map of control characters and their escaped equivalents.
2824 var Escapes = {
2825 92: "\\\\",
2826 34: '\\"',
2827 8: "\\b",
2828 12: "\\f",
2829 10: "\\n",
2830 13: "\\r",
2831 9: "\\t"
2832 };
2833
2834 // Internal: Converts `value` into a zero-padded string such that its
2835 // length is at least equal to `width`. The `width` must be <= 6.
2836 var leadingZeroes = "000000";
2837 var toPaddedString = function toPaddedString(width, value) {
2838 // The `|| 0` expression is necessary to work around a bug in
2839 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
2840 return (leadingZeroes + (value || 0)).slice(-width);
2841 };
2842
2843 // Internal: Double-quotes a string `value`, replacing all ASCII control
2844 // characters (characters with code unit values between 0 and 31) with
2845 // their escaped equivalents. This is an implementation of the
2846 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
2847 var unicodePrefix = '\\u00';
2848 var quote = function quote(value) {
2849 var result = '"',
2850 index = 0,
2851 length = value.length,
2852 useCharIndex = !charIndexBuggy || length > 10;
2853 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
2854 for (; index < length; index++) {
2855 var charCode = value.charCodeAt(index);
2856 // If the character is a control character, append its Unicode or
2857 // shorthand escape sequence; otherwise, append the character as-is.
2858 switch (charCode) {
2859 case 8:case 9:case 10:case 12:case 13:case 34:case 92:
2860 result += Escapes[charCode];
2861 break;
2862 default:
2863 if (charCode < 32) {
2864 result += unicodePrefix + toPaddedString(2, charCode.toString(16));
2865 break;
2866 }
2867 result += useCharIndex ? symbols[index] : value.charAt(index);
2868 }
2869 }
2870 return result + '"';
2871 };
2872
2873 // Internal: Recursively serializes an object. Implements the
2874 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
2875 var serialize = function serialize(property, object, callback, properties, whitespace, indentation, stack) {
2876 var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
2877 try {
2878 // Necessary for host object support.
2879 value = object[property];
2880 } catch (exception) {}
2881 if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) == "object" && value) {
2882 className = getClass.call(value);
2883 if (className == dateClass && !_isProperty.call(value, "toJSON")) {
2884 if (value > -1 / 0 && value < 1 / 0) {
2885 // Dates are serialized according to the `Date#toJSON` method
2886 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
2887 // for the ISO 8601 date time string format.
2888 if (getDay) {
2889 // Manually compute the year, month, date, hours, minutes,
2890 // seconds, and milliseconds if the `getUTC*` methods are
2891 // buggy. Adapted from @Yaffle's `date-shim` project.
2892 date = floor(value / 864e5);
2893 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++) {}
2894 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++) {}
2895 date = 1 + date - getDay(year, month);
2896 // The `time` value specifies the time within the day (see ES
2897 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
2898 // to compute `A modulo B`, as the `%` operator does not
2899 // correspond to the `modulo` operation for negative numbers.
2900 time = (value % 864e5 + 864e5) % 864e5;
2901 // The hours, minutes, seconds, and milliseconds are obtained by
2902 // decomposing the time within the day. See section 15.9.1.10.
2903 hours = floor(time / 36e5) % 24;
2904 minutes = floor(time / 6e4) % 60;
2905 seconds = floor(time / 1e3) % 60;
2906 milliseconds = time % 1e3;
2907 } else {
2908 year = value.getUTCFullYear();
2909 month = value.getUTCMonth();
2910 date = value.getUTCDate();
2911 hours = value.getUTCHours();
2912 minutes = value.getUTCMinutes();
2913 seconds = value.getUTCSeconds();
2914 milliseconds = value.getUTCMilliseconds();
2915 }
2916 // Serialize extended years correctly.
2917 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
2918 // Months, dates, hours, minutes, and seconds should have two
2919 // digits; milliseconds should have three.
2920 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
2921 // Milliseconds are optional in ES 5.0, but required in 5.1.
2922 "." + toPaddedString(3, milliseconds) + "Z";
2923 } else {
2924 value = null;
2925 }
2926 } else if (typeof value.toJSON == "function" && (className != numberClass && className != stringClass && className != arrayClass || _isProperty.call(value, "toJSON"))) {
2927 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
2928 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
2929 // ignores all `toJSON` methods on these objects unless they are
2930 // defined directly on an instance.
2931 value = value.toJSON(property);
2932 }
2933 }
2934 if (callback) {
2935 // If a replacement function was provided, call it to obtain the value
2936 // for serialization.
2937 value = callback.call(object, property, value);
2938 }
2939 if (value === null) {
2940 return "null";
2941 }
2942 className = getClass.call(value);
2943 if (className == booleanClass) {
2944 // Booleans are represented literally.
2945 return "" + value;
2946 } else if (className == numberClass) {
2947 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
2948 // `"null"`.
2949 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
2950 } else if (className == stringClass) {
2951 // Strings are double-quoted and escaped.
2952 return quote("" + value);
2953 }
2954 // Recursively serialize objects and arrays.
2955 if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) == "object") {
2956 // Check for cyclic structures. This is a linear search; performance
2957 // is inversely proportional to the number of unique nested objects.
2958 for (length = stack.length; length--;) {
2959 if (stack[length] === value) {
2960 // Cyclic structures cannot be serialized by `JSON.stringify`.
2961 throw TypeError();
2962 }
2963 }
2964 // Add the object to the stack of traversed objects.
2965 stack.push(value);
2966 results = [];
2967 // Save the current indentation level and indent one additional level.
2968 prefix = indentation;
2969 indentation += whitespace;
2970 if (className == arrayClass) {
2971 // Recursively serialize array elements.
2972 for (index = 0, length = value.length; index < length; index++) {
2973 element = serialize(index, value, callback, properties, whitespace, indentation, stack);
2974 results.push(element === undef ? "null" : element);
2975 }
2976 result = results.length ? whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : "[" + results.join(",") + "]" : "[]";
2977 } else {
2978 // Recursively serialize object members. Members are selected from
2979 // either a user-specified list of property names, or the object
2980 // itself.
2981 _forEach(properties || value, function (property) {
2982 var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
2983 if (element !== undef) {
2984 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
2985 // is not the empty string, let `member` {quote(property) + ":"}
2986 // be the concatenation of `member` and the `space` character."
2987 // The "`space` character" refers to the literal space
2988 // character, not the `space` {width} argument provided to
2989 // `JSON.stringify`.
2990 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
2991 }
2992 });
2993 result = results.length ? whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : "{" + results.join(",") + "}" : "{}";
2994 }
2995 // Remove the object from the traversed object stack.
2996 stack.pop();
2997 return result;
2998 }
2999 };
3000
3001 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
3002 exports.stringify = function (source, filter, width) {
3003 var whitespace, callback, properties, className;
3004 if (objectTypes[typeof filter === 'undefined' ? 'undefined' : _typeof(filter)] && filter) {
3005 if ((className = getClass.call(filter)) == functionClass) {
3006 callback = filter;
3007 } else if (className == arrayClass) {
3008 // Convert the property names array into a makeshift set.
3009 properties = {};
3010 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], (className = getClass.call(value), className == stringClass || className == numberClass) && (properties[value] = 1)) {}
3011 }
3012 }
3013 if (width) {
3014 if ((className = getClass.call(width)) == numberClass) {
3015 // Convert the `width` to an integer and create a string containing
3016 // `width` number of space characters.
3017 if ((width -= width % 1) > 0) {
3018 for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ") {}
3019 }
3020 } else if (className == stringClass) {
3021 whitespace = width.length <= 10 ? width : width.slice(0, 10);
3022 }
3023 }
3024 // Opera <= 7.54u2 discards the values associated with empty string keys
3025 // (`""`) only if they are used directly within an object member list
3026 // (e.g., `!("" in { "": 1})`).
3027 return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
3028 };
3029 }
3030
3031 // Public: Parses a JSON source string.
3032 if (!has("json-parse")) {
3033 var fromCharCode = String.fromCharCode;
3034
3035 // Internal: A map of escaped control characters and their unescaped
3036 // equivalents.
3037 var Unescapes = {
3038 92: "\\",
3039 34: '"',
3040 47: "/",
3041 98: "\b",
3042 116: "\t",
3043 110: "\n",
3044 102: "\f",
3045 114: "\r"
3046 };
3047
3048 // Internal: Stores the parser state.
3049 var Index, Source;
3050
3051 // Internal: Resets the parser state and throws a `SyntaxError`.
3052 var abort = function abort() {
3053 Index = Source = null;
3054 throw SyntaxError();
3055 };
3056
3057 // Internal: Returns the next token, or `"$"` if the parser has reached
3058 // the end of the source string. A token may be a string, number, `null`
3059 // literal, or Boolean literal.
3060 var lex = function lex() {
3061 var source = Source,
3062 length = source.length,
3063 value,
3064 begin,
3065 position,
3066 isSigned,
3067 charCode;
3068 while (Index < length) {
3069 charCode = source.charCodeAt(Index);
3070 switch (charCode) {
3071 case 9:case 10:case 13:case 32:
3072 // Skip whitespace tokens, including tabs, carriage returns, line
3073 // feeds, and space characters.
3074 Index++;
3075 break;
3076 case 123:case 125:case 91:case 93:case 58:case 44:
3077 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
3078 // the current position.
3079 value = charIndexBuggy ? source.charAt(Index) : source[Index];
3080 Index++;
3081 return value;
3082 case 34:
3083 // `"` delimits a JSON string; advance to the next character and
3084 // begin parsing the string. String tokens are prefixed with the
3085 // sentinel `@` character to distinguish them from punctuators and
3086 // end-of-string tokens.
3087 for (value = "@", Index++; Index < length;) {
3088 charCode = source.charCodeAt(Index);
3089 if (charCode < 32) {
3090 // Unescaped ASCII control characters (those with a code unit
3091 // less than the space character) are not permitted.
3092 abort();
3093 } else if (charCode == 92) {
3094 // A reverse solidus (`\`) marks the beginning of an escaped
3095 // control character (including `"`, `\`, and `/`) or Unicode
3096 // escape sequence.
3097 charCode = source.charCodeAt(++Index);
3098 switch (charCode) {
3099 case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:
3100 // Revive escaped control characters.
3101 value += Unescapes[charCode];
3102 Index++;
3103 break;
3104 case 117:
3105 // `\u` marks the beginning of a Unicode escape sequence.
3106 // Advance to the first character and validate the
3107 // four-digit code point.
3108 begin = ++Index;
3109 for (position = Index + 4; Index < position; Index++) {
3110 charCode = source.charCodeAt(Index);
3111 // A valid sequence comprises four hexdigits (case-
3112 // insensitive) that form a single hexadecimal value.
3113 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
3114 // Invalid Unicode escape sequence.
3115 abort();
3116 }
3117 }
3118 // Revive the escaped character.
3119 value += fromCharCode("0x" + source.slice(begin, Index));
3120 break;
3121 default:
3122 // Invalid escape sequence.
3123 abort();
3124 }
3125 } else {
3126 if (charCode == 34) {
3127 // An unescaped double-quote character marks the end of the
3128 // string.
3129 break;
3130 }
3131 charCode = source.charCodeAt(Index);
3132 begin = Index;
3133 // Optimize for the common case where a string is valid.
3134 while (charCode >= 32 && charCode != 92 && charCode != 34) {
3135 charCode = source.charCodeAt(++Index);
3136 }
3137 // Append the string as-is.
3138 value += source.slice(begin, Index);
3139 }
3140 }
3141 if (source.charCodeAt(Index) == 34) {
3142 // Advance to the next character and return the revived string.
3143 Index++;
3144 return value;
3145 }
3146 // Unterminated string.
3147 abort();
3148 default:
3149 // Parse numbers and literals.
3150 begin = Index;
3151 // Advance past the negative sign, if one is specified.
3152 if (charCode == 45) {
3153 isSigned = true;
3154 charCode = source.charCodeAt(++Index);
3155 }
3156 // Parse an integer or floating-point value.
3157 if (charCode >= 48 && charCode <= 57) {
3158 // Leading zeroes are interpreted as octal literals.
3159 if (charCode == 48 && (charCode = source.charCodeAt(Index + 1), charCode >= 48 && charCode <= 57)) {
3160 // Illegal octal literal.
3161 abort();
3162 }
3163 isSigned = false;
3164 // Parse the integer component.
3165 for (; Index < length && (charCode = source.charCodeAt(Index), charCode >= 48 && charCode <= 57); Index++) {}
3166 // Floats cannot contain a leading decimal point; however, this
3167 // case is already accounted for by the parser.
3168 if (source.charCodeAt(Index) == 46) {
3169 position = ++Index;
3170 // Parse the decimal component.
3171 for (; position < length && (charCode = source.charCodeAt(position), charCode >= 48 && charCode <= 57); position++) {}
3172 if (position == Index) {
3173 // Illegal trailing decimal.
3174 abort();
3175 }
3176 Index = position;
3177 }
3178 // Parse exponents. The `e` denoting the exponent is
3179 // case-insensitive.
3180 charCode = source.charCodeAt(Index);
3181 if (charCode == 101 || charCode == 69) {
3182 charCode = source.charCodeAt(++Index);
3183 // Skip past the sign following the exponent, if one is
3184 // specified.
3185 if (charCode == 43 || charCode == 45) {
3186 Index++;
3187 }
3188 // Parse the exponential component.
3189 for (position = Index; position < length && (charCode = source.charCodeAt(position), charCode >= 48 && charCode <= 57); position++) {}
3190 if (position == Index) {
3191 // Illegal empty exponent.
3192 abort();
3193 }
3194 Index = position;
3195 }
3196 // Coerce the parsed value to a JavaScript number.
3197 return +source.slice(begin, Index);
3198 }
3199 // A negative sign may only precede numbers.
3200 if (isSigned) {
3201 abort();
3202 }
3203 // `true`, `false`, and `null` literals.
3204 if (source.slice(Index, Index + 4) == "true") {
3205 Index += 4;
3206 return true;
3207 } else if (source.slice(Index, Index + 5) == "false") {
3208 Index += 5;
3209 return false;
3210 } else if (source.slice(Index, Index + 4) == "null") {
3211 Index += 4;
3212 return null;
3213 }
3214 // Unrecognized token.
3215 abort();
3216 }
3217 }
3218 // Return the sentinel `$` character if the parser has reached the end
3219 // of the source string.
3220 return "$";
3221 };
3222
3223 // Internal: Parses a JSON `value` token.
3224 var get = function get(value) {
3225 var results, hasMembers;
3226 if (value == "$") {
3227 // Unexpected end of input.
3228 abort();
3229 }
3230 if (typeof value == "string") {
3231 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
3232 // Remove the sentinel `@` character.
3233 return value.slice(1);
3234 }
3235 // Parse object and array literals.
3236 if (value == "[") {
3237 // Parses a JSON array, returning a new JavaScript array.
3238 results = [];
3239 for (;; hasMembers || (hasMembers = true)) {
3240 value = lex();
3241 // A closing square bracket marks the end of the array literal.
3242 if (value == "]") {
3243 break;
3244 }
3245 // If the array literal contains elements, the current token
3246 // should be a comma separating the previous element from the
3247 // next.
3248 if (hasMembers) {
3249 if (value == ",") {
3250 value = lex();
3251 if (value == "]") {
3252 // Unexpected trailing `,` in array literal.
3253 abort();
3254 }
3255 } else {
3256 // A `,` must separate each array element.
3257 abort();
3258 }
3259 }
3260 // Elisions and leading commas are not permitted.
3261 if (value == ",") {
3262 abort();
3263 }
3264 results.push(get(value));
3265 }
3266 return results;
3267 } else if (value == "{") {
3268 // Parses a JSON object, returning a new JavaScript object.
3269 results = {};
3270 for (;; hasMembers || (hasMembers = true)) {
3271 value = lex();
3272 // A closing curly brace marks the end of the object literal.
3273 if (value == "}") {
3274 break;
3275 }
3276 // If the object literal contains members, the current token
3277 // should be a comma separator.
3278 if (hasMembers) {
3279 if (value == ",") {
3280 value = lex();
3281 if (value == "}") {
3282 // Unexpected trailing `,` in object literal.
3283 abort();
3284 }
3285 } else {
3286 // A `,` must separate each object member.
3287 abort();
3288 }
3289 }
3290 // Leading commas are not permitted, object property names must be
3291 // double-quoted strings, and a `:` must separate each property
3292 // name and value.
3293 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
3294 abort();
3295 }
3296 results[value.slice(1)] = get(lex());
3297 }
3298 return results;
3299 }
3300 // Unexpected token encountered.
3301 abort();
3302 }
3303 return value;
3304 };
3305
3306 // Internal: Updates a traversed object member.
3307 var update = function update(source, property, callback) {
3308 var element = walk(source, property, callback);
3309 if (element === undef) {
3310 delete source[property];
3311 } else {
3312 source[property] = element;
3313 }
3314 };
3315
3316 // Internal: Recursively traverses a parsed JSON object, invoking the
3317 // `callback` function for each value. This is an implementation of the
3318 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
3319 var walk = function walk(source, property, callback) {
3320 var value = source[property],
3321 length;
3322 if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) == "object" && value) {
3323 // `forEach` can't be used to traverse an array in Opera <= 8.54
3324 // because its `Object#hasOwnProperty` implementation returns `false`
3325 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
3326 if (getClass.call(value) == arrayClass) {
3327 for (length = value.length; length--;) {
3328 update(value, length, callback);
3329 }
3330 } else {
3331 _forEach(value, function (property) {
3332 update(value, property, callback);
3333 });
3334 }
3335 }
3336 return callback.call(source, property, value);
3337 };
3338
3339 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
3340 exports.parse = function (source, callback) {
3341 var result, value;
3342 Index = 0;
3343 Source = "" + source;
3344 result = get(lex());
3345 // If a JSON string contains multiple tokens, it is invalid.
3346 if (lex() != "$") {
3347 abort();
3348 }
3349 // Reset the parser state.
3350 Index = Source = null;
3351 return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
3352 };
3353 }
3354 }
3355
3356 exports["runInContext"] = runInContext;
3357 return exports;
3358 }
3359
3360 if (freeExports && !isLoader) {
3361 // Export for CommonJS environments.
3362 runInContext(root, freeExports);
3363 } else {
3364 // Export for web browsers and JavaScript engines.
3365 var nativeJSON = root.JSON,
3366 previousJSON = root["JSON3"],
3367 isRestored = false;
3368
3369 var JSON3 = runInContext(root, root["JSON3"] = {
3370 // Public: Restores the original value of the global `JSON` object and
3371 // returns a reference to the `JSON3` object.
3372 "noConflict": function noConflict() {
3373 if (!isRestored) {
3374 isRestored = true;
3375 root.JSON = nativeJSON;
3376 root["JSON3"] = previousJSON;
3377 nativeJSON = previousJSON = null;
3378 }
3379 return JSON3;
3380 }
3381 });
3382
3383 root.JSON = {
3384 "parse": JSON3.parse,
3385 "stringify": JSON3.stringify
3386 };
3387 }
3388
3389 // Export for asynchronous module loaders.
3390 if (isLoader) {
3391 !(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
3392 return JSON3;
3393 }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
3394 }
3395 }).call(this);
3396
3397 /* WEBPACK VAR INJECTION */
3398 }).call(exports, __webpack_require__(13)(module), function () {
3399 return this;
3400 }());
3401
3402 /***/
3403},
3404/* 13 */
3405/***/function (module, exports) {
3406
3407 module.exports = function (module) {
3408 if (!module.webpackPolyfill) {
3409 module.deprecate = function () {};
3410 module.paths = [];
3411 // module.parent = undefined by default
3412 module.children = [];
3413 module.webpackPolyfill = 1;
3414 }
3415 return module;
3416 };
3417
3418 /***/
3419},
3420/* 14 */
3421/***/function (module, exports) {
3422
3423 /* WEBPACK VAR INJECTION */(function (__webpack_amd_options__) {
3424 module.exports = __webpack_amd_options__;
3425
3426 /* WEBPACK VAR INJECTION */
3427 }).call(exports, {});
3428
3429 /***/
3430},
3431/* 15 */
3432/***/function (module, exports) {
3433
3434 /**
3435 * Expose `Emitter`.
3436 */
3437
3438 module.exports = Emitter;
3439
3440 /**
3441 * Initialize a new `Emitter`.
3442 *
3443 * @api public
3444 */
3445
3446 function Emitter(obj) {
3447 if (obj) return mixin(obj);
3448 };
3449
3450 /**
3451 * Mixin the emitter properties.
3452 *
3453 * @param {Object} obj
3454 * @return {Object}
3455 * @api private
3456 */
3457
3458 function mixin(obj) {
3459 for (var key in Emitter.prototype) {
3460 obj[key] = Emitter.prototype[key];
3461 }
3462 return obj;
3463 }
3464
3465 /**
3466 * Listen on the given `event` with `fn`.
3467 *
3468 * @param {String} event
3469 * @param {Function} fn
3470 * @return {Emitter}
3471 * @api public
3472 */
3473
3474 Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
3475 this._callbacks = this._callbacks || {};
3476 (this._callbacks[event] = this._callbacks[event] || []).push(fn);
3477 return this;
3478 };
3479
3480 /**
3481 * Adds an `event` listener that will be invoked a single
3482 * time then automatically removed.
3483 *
3484 * @param {String} event
3485 * @param {Function} fn
3486 * @return {Emitter}
3487 * @api public
3488 */
3489
3490 Emitter.prototype.once = function (event, fn) {
3491 var self = this;
3492 this._callbacks = this._callbacks || {};
3493
3494 function on() {
3495 self.off(event, on);
3496 fn.apply(this, arguments);
3497 }
3498
3499 on.fn = fn;
3500 this.on(event, on);
3501 return this;
3502 };
3503
3504 /**
3505 * Remove the given callback for `event` or all
3506 * registered callbacks.
3507 *
3508 * @param {String} event
3509 * @param {Function} fn
3510 * @return {Emitter}
3511 * @api public
3512 */
3513
3514 Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
3515 this._callbacks = this._callbacks || {};
3516
3517 // all
3518 if (0 == arguments.length) {
3519 this._callbacks = {};
3520 return this;
3521 }
3522
3523 // specific event
3524 var callbacks = this._callbacks[event];
3525 if (!callbacks) return this;
3526
3527 // remove all handlers
3528 if (1 == arguments.length) {
3529 delete this._callbacks[event];
3530 return this;
3531 }
3532
3533 // remove specific handler
3534 var cb;
3535 for (var i = 0; i < callbacks.length; i++) {
3536 cb = callbacks[i];
3537 if (cb === fn || cb.fn === fn) {
3538 callbacks.splice(i, 1);
3539 break;
3540 }
3541 }
3542 return this;
3543 };
3544
3545 /**
3546 * Emit `event` with the given args.
3547 *
3548 * @param {String} event
3549 * @param {Mixed} ...
3550 * @return {Emitter}
3551 */
3552
3553 Emitter.prototype.emit = function (event) {
3554 this._callbacks = this._callbacks || {};
3555 var args = [].slice.call(arguments, 1),
3556 callbacks = this._callbacks[event];
3557
3558 if (callbacks) {
3559 callbacks = callbacks.slice(0);
3560 for (var i = 0, len = callbacks.length; i < len; ++i) {
3561 callbacks[i].apply(this, args);
3562 }
3563 }
3564
3565 return this;
3566 };
3567
3568 /**
3569 * Return array of callbacks for `event`.
3570 *
3571 * @param {String} event
3572 * @return {Array}
3573 * @api public
3574 */
3575
3576 Emitter.prototype.listeners = function (event) {
3577 this._callbacks = this._callbacks || {};
3578 return this._callbacks[event] || [];
3579 };
3580
3581 /**
3582 * Check if this emitter has `event` handlers.
3583 *
3584 * @param {String} event
3585 * @return {Boolean}
3586 * @api public
3587 */
3588
3589 Emitter.prototype.hasListeners = function (event) {
3590 return !!this.listeners(event).length;
3591 };
3592
3593 /***/
3594},
3595/* 16 */
3596/***/function (module, exports, __webpack_require__) {
3597
3598 /* WEBPACK VAR INJECTION */(function (global) {
3599 /*global Blob,File*/
3600
3601 /**
3602 * Module requirements
3603 */
3604
3605 var isArray = __webpack_require__(17);
3606 var isBuf = __webpack_require__(18);
3607
3608 /**
3609 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
3610 * Anything with blobs or files should be fed through removeBlobs before coming
3611 * here.
3612 *
3613 * @param {Object} packet - socket.io event packet
3614 * @return {Object} with deconstructed packet and list of buffers
3615 * @api public
3616 */
3617
3618 exports.deconstructPacket = function (packet) {
3619 var buffers = [];
3620 var packetData = packet.data;
3621
3622 function _deconstructPacket(data) {
3623 if (!data) return data;
3624
3625 if (isBuf(data)) {
3626 var placeholder = { _placeholder: true, num: buffers.length };
3627 buffers.push(data);
3628 return placeholder;
3629 } else if (isArray(data)) {
3630 var newData = new Array(data.length);
3631 for (var i = 0; i < data.length; i++) {
3632 newData[i] = _deconstructPacket(data[i]);
3633 }
3634 return newData;
3635 } else if ('object' == (typeof data === 'undefined' ? 'undefined' : _typeof(data)) && !(data instanceof Date)) {
3636 var newData = {};
3637 for (var key in data) {
3638 newData[key] = _deconstructPacket(data[key]);
3639 }
3640 return newData;
3641 }
3642 return data;
3643 }
3644
3645 var pack = packet;
3646 pack.data = _deconstructPacket(packetData);
3647 pack.attachments = buffers.length; // number of binary 'attachments'
3648 return { packet: pack, buffers: buffers };
3649 };
3650
3651 /**
3652 * Reconstructs a binary packet from its placeholder packet and buffers
3653 *
3654 * @param {Object} packet - event packet with placeholders
3655 * @param {Array} buffers - binary buffers to put in placeholder positions
3656 * @return {Object} reconstructed packet
3657 * @api public
3658 */
3659
3660 exports.reconstructPacket = function (packet, buffers) {
3661 var curPlaceHolder = 0;
3662
3663 function _reconstructPacket(data) {
3664 if (data && data._placeholder) {
3665 var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
3666 return buf;
3667 } else if (isArray(data)) {
3668 for (var i = 0; i < data.length; i++) {
3669 data[i] = _reconstructPacket(data[i]);
3670 }
3671 return data;
3672 } else if (data && 'object' == (typeof data === 'undefined' ? 'undefined' : _typeof(data))) {
3673 for (var key in data) {
3674 data[key] = _reconstructPacket(data[key]);
3675 }
3676 return data;
3677 }
3678 return data;
3679 }
3680
3681 packet.data = _reconstructPacket(packet.data);
3682 packet.attachments = undefined; // no longer useful
3683 return packet;
3684 };
3685
3686 /**
3687 * Asynchronously removes Blobs or Files from data via
3688 * FileReader's readAsArrayBuffer method. Used before encoding
3689 * data as msgpack. Calls callback with the blobless data.
3690 *
3691 * @param {Object} data
3692 * @param {Function} callback
3693 * @api private
3694 */
3695
3696 exports.removeBlobs = function (data, callback) {
3697 function _removeBlobs(obj, curKey, containingObject) {
3698 if (!obj) return obj;
3699
3700 // convert any blob
3701 if (global.Blob && obj instanceof Blob || global.File && obj instanceof File) {
3702 pendingBlobs++;
3703
3704 // async filereader
3705 var fileReader = new FileReader();
3706 fileReader.onload = function () {
3707 // this.result == arraybuffer
3708 if (containingObject) {
3709 containingObject[curKey] = this.result;
3710 } else {
3711 bloblessData = this.result;
3712 }
3713
3714 // if nothing pending its callback time
3715 if (! --pendingBlobs) {
3716 callback(bloblessData);
3717 }
3718 };
3719
3720 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
3721 } else if (isArray(obj)) {
3722 // handle array
3723 for (var i = 0; i < obj.length; i++) {
3724 _removeBlobs(obj[i], i, obj);
3725 }
3726 } else if (obj && 'object' == (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) && !isBuf(obj)) {
3727 // and object
3728 for (var key in obj) {
3729 _removeBlobs(obj[key], key, obj);
3730 }
3731 }
3732 }
3733
3734 var pendingBlobs = 0;
3735 var bloblessData = data;
3736 _removeBlobs(bloblessData);
3737 if (!pendingBlobs) {
3738 callback(bloblessData);
3739 }
3740 };
3741
3742 /* WEBPACK VAR INJECTION */
3743 }).call(exports, function () {
3744 return this;
3745 }());
3746
3747 /***/
3748},
3749/* 17 */
3750/***/function (module, exports) {
3751
3752 module.exports = Array.isArray || function (arr) {
3753 return Object.prototype.toString.call(arr) == '[object Array]';
3754 };
3755
3756 /***/
3757},
3758/* 18 */
3759/***/function (module, exports) {
3760
3761 /* WEBPACK VAR INJECTION */(function (global) {
3762 module.exports = isBuf;
3763
3764 /**
3765 * Returns true if obj is a buffer or an arraybuffer.
3766 *
3767 * @api private
3768 */
3769
3770 function isBuf(obj) {
3771 return global.Buffer && global.Buffer.isBuffer(obj) || global.ArrayBuffer && obj instanceof ArrayBuffer;
3772 }
3773
3774 /* WEBPACK VAR INJECTION */
3775 }).call(exports, function () {
3776 return this;
3777 }());
3778
3779 /***/
3780},
3781/* 19 */
3782/***/function (module, exports, __webpack_require__) {
3783
3784 /**
3785 * Module dependencies.
3786 */
3787
3788 var eio = __webpack_require__(20);
3789 var Socket = __webpack_require__(49);
3790 var Emitter = __webpack_require__(37);
3791 var parser = __webpack_require__(8);
3792 var on = __webpack_require__(51);
3793 var bind = __webpack_require__(52);
3794 var debug = __webpack_require__(4)('socket.io-client:manager');
3795 var indexOf = __webpack_require__(47);
3796 var Backoff = __webpack_require__(53);
3797
3798 /**
3799 * IE6+ hasOwnProperty
3800 */
3801
3802 var has = Object.prototype.hasOwnProperty;
3803
3804 /**
3805 * Module exports
3806 */
3807
3808 module.exports = Manager;
3809
3810 /**
3811 * `Manager` constructor.
3812 *
3813 * @param {String} engine instance or engine uri/opts
3814 * @param {Object} options
3815 * @api public
3816 */
3817
3818 function Manager(uri, opts) {
3819 if (!(this instanceof Manager)) return new Manager(uri, opts);
3820 if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
3821 opts = uri;
3822 uri = undefined;
3823 }
3824 opts = opts || {};
3825
3826 opts.path = opts.path || '/socket.io';
3827 this.nsps = {};
3828 this.subs = [];
3829 this.opts = opts;
3830 this.reconnection(opts.reconnection !== false);
3831 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3832 this.reconnectionDelay(opts.reconnectionDelay || 1000);
3833 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
3834 this.randomizationFactor(opts.randomizationFactor || 0.5);
3835 this.backoff = new Backoff({
3836 min: this.reconnectionDelay(),
3837 max: this.reconnectionDelayMax(),
3838 jitter: this.randomizationFactor()
3839 });
3840 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
3841 this.readyState = 'closed';
3842 this.uri = uri;
3843 this.connecting = [];
3844 this.lastPing = null;
3845 this.encoding = false;
3846 this.packetBuffer = [];
3847 this.encoder = new parser.Encoder();
3848 this.decoder = new parser.Decoder();
3849 this.autoConnect = opts.autoConnect !== false;
3850 if (this.autoConnect) this.open();
3851 }
3852
3853 /**
3854 * Propagate given event to sockets and emit on `this`
3855 *
3856 * @api private
3857 */
3858
3859 Manager.prototype.emitAll = function () {
3860 this.emit.apply(this, arguments);
3861 for (var nsp in this.nsps) {
3862 if (has.call(this.nsps, nsp)) {
3863 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
3864 }
3865 }
3866 };
3867
3868 /**
3869 * Update `socket.id` of all sockets
3870 *
3871 * @api private
3872 */
3873
3874 Manager.prototype.updateSocketIds = function () {
3875 for (var nsp in this.nsps) {
3876 if (has.call(this.nsps, nsp)) {
3877 this.nsps[nsp].id = this.engine.id;
3878 }
3879 }
3880 };
3881
3882 /**
3883 * Mix in `Emitter`.
3884 */
3885
3886 Emitter(Manager.prototype);
3887
3888 /**
3889 * Sets the `reconnection` config.
3890 *
3891 * @param {Boolean} true/false if it should automatically reconnect
3892 * @return {Manager} self or value
3893 * @api public
3894 */
3895
3896 Manager.prototype.reconnection = function (v) {
3897 if (!arguments.length) return this._reconnection;
3898 this._reconnection = !!v;
3899 return this;
3900 };
3901
3902 /**
3903 * Sets the reconnection attempts config.
3904 *
3905 * @param {Number} max reconnection attempts before giving up
3906 * @return {Manager} self or value
3907 * @api public
3908 */
3909
3910 Manager.prototype.reconnectionAttempts = function (v) {
3911 if (!arguments.length) return this._reconnectionAttempts;
3912 this._reconnectionAttempts = v;
3913 return this;
3914 };
3915
3916 /**
3917 * Sets the delay between reconnections.
3918 *
3919 * @param {Number} delay
3920 * @return {Manager} self or value
3921 * @api public
3922 */
3923
3924 Manager.prototype.reconnectionDelay = function (v) {
3925 if (!arguments.length) return this._reconnectionDelay;
3926 this._reconnectionDelay = v;
3927 this.backoff && this.backoff.setMin(v);
3928 return this;
3929 };
3930
3931 Manager.prototype.randomizationFactor = function (v) {
3932 if (!arguments.length) return this._randomizationFactor;
3933 this._randomizationFactor = v;
3934 this.backoff && this.backoff.setJitter(v);
3935 return this;
3936 };
3937
3938 /**
3939 * Sets the maximum delay between reconnections.
3940 *
3941 * @param {Number} delay
3942 * @return {Manager} self or value
3943 * @api public
3944 */
3945
3946 Manager.prototype.reconnectionDelayMax = function (v) {
3947 if (!arguments.length) return this._reconnectionDelayMax;
3948 this._reconnectionDelayMax = v;
3949 this.backoff && this.backoff.setMax(v);
3950 return this;
3951 };
3952
3953 /**
3954 * Sets the connection timeout. `false` to disable
3955 *
3956 * @return {Manager} self or value
3957 * @api public
3958 */
3959
3960 Manager.prototype.timeout = function (v) {
3961 if (!arguments.length) return this._timeout;
3962 this._timeout = v;
3963 return this;
3964 };
3965
3966 /**
3967 * Starts trying to reconnect if reconnection is enabled and we have not
3968 * started reconnecting yet
3969 *
3970 * @api private
3971 */
3972
3973 Manager.prototype.maybeReconnectOnOpen = function () {
3974 // Only try to reconnect if it's the first time we're connecting
3975 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
3976 // keeps reconnection from firing twice for the same reconnection loop
3977 this.reconnect();
3978 }
3979 };
3980
3981 /**
3982 * Sets the current transport `socket`.
3983 *
3984 * @param {Function} optional, callback
3985 * @return {Manager} self
3986 * @api public
3987 */
3988
3989 Manager.prototype.open = Manager.prototype.connect = function (fn, opts) {
3990 debug('readyState %s', this.readyState);
3991 if (~this.readyState.indexOf('open')) return this;
3992
3993 debug('opening %s', this.uri);
3994 this.engine = eio(this.uri, this.opts);
3995 var socket = this.engine;
3996 var self = this;
3997 this.readyState = 'opening';
3998 this.skipReconnect = false;
3999
4000 // emit `open`
4001 var openSub = on(socket, 'open', function () {
4002 self.onopen();
4003 fn && fn();
4004 });
4005
4006 // emit `connect_error`
4007 var errorSub = on(socket, 'error', function (data) {
4008 debug('connect_error');
4009 self.cleanup();
4010 self.readyState = 'closed';
4011 self.emitAll('connect_error', data);
4012 if (fn) {
4013 var err = new Error('Connection error');
4014 err.data = data;
4015 fn(err);
4016 } else {
4017 // Only do this if there is no fn to handle the error
4018 self.maybeReconnectOnOpen();
4019 }
4020 });
4021
4022 // emit `connect_timeout`
4023 if (false !== this._timeout) {
4024 var timeout = this._timeout;
4025 debug('connect attempt will timeout after %d', timeout);
4026
4027 // set timer
4028 var timer = setTimeout(function () {
4029 debug('connect attempt timed out after %d', timeout);
4030 openSub.destroy();
4031 socket.close();
4032 socket.emit('error', 'timeout');
4033 self.emitAll('connect_timeout', timeout);
4034 }, timeout);
4035
4036 this.subs.push({
4037 destroy: function destroy() {
4038 clearTimeout(timer);
4039 }
4040 });
4041 }
4042
4043 this.subs.push(openSub);
4044 this.subs.push(errorSub);
4045
4046 return this;
4047 };
4048
4049 /**
4050 * Called upon transport open.
4051 *
4052 * @api private
4053 */
4054
4055 Manager.prototype.onopen = function () {
4056 debug('open');
4057
4058 // clear old subs
4059 this.cleanup();
4060
4061 // mark as open
4062 this.readyState = 'open';
4063 this.emit('open');
4064
4065 // add new subs
4066 var socket = this.engine;
4067 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
4068 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
4069 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
4070 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
4071 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
4072 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
4073 };
4074
4075 /**
4076 * Called upon a ping.
4077 *
4078 * @api private
4079 */
4080
4081 Manager.prototype.onping = function () {
4082 this.lastPing = new Date();
4083 this.emitAll('ping');
4084 };
4085
4086 /**
4087 * Called upon a packet.
4088 *
4089 * @api private
4090 */
4091
4092 Manager.prototype.onpong = function () {
4093 this.emitAll('pong', new Date() - this.lastPing);
4094 };
4095
4096 /**
4097 * Called with data.
4098 *
4099 * @api private
4100 */
4101
4102 Manager.prototype.ondata = function (data) {
4103 this.decoder.add(data);
4104 };
4105
4106 /**
4107 * Called when parser fully decodes a packet.
4108 *
4109 * @api private
4110 */
4111
4112 Manager.prototype.ondecoded = function (packet) {
4113 this.emit('packet', packet);
4114 };
4115
4116 /**
4117 * Called upon socket error.
4118 *
4119 * @api private
4120 */
4121
4122 Manager.prototype.onerror = function (err) {
4123 debug('error', err);
4124 this.emitAll('error', err);
4125 };
4126
4127 /**
4128 * Creates a new socket for the given `nsp`.
4129 *
4130 * @return {Socket}
4131 * @api public
4132 */
4133
4134 Manager.prototype.socket = function (nsp, opts) {
4135 var socket = this.nsps[nsp];
4136 if (!socket) {
4137 socket = new Socket(this, nsp, opts);
4138 this.nsps[nsp] = socket;
4139 var self = this;
4140 socket.on('connecting', onConnecting);
4141 socket.on('connect', function () {
4142 socket.id = self.engine.id;
4143 });
4144
4145 if (this.autoConnect) {
4146 // manually call here since connecting evnet is fired before listening
4147 onConnecting();
4148 }
4149 }
4150
4151 function onConnecting() {
4152 if (!~indexOf(self.connecting, socket)) {
4153 self.connecting.push(socket);
4154 }
4155 }
4156
4157 return socket;
4158 };
4159
4160 /**
4161 * Called upon a socket close.
4162 *
4163 * @param {Socket} socket
4164 */
4165
4166 Manager.prototype.destroy = function (socket) {
4167 var index = indexOf(this.connecting, socket);
4168 if (~index) this.connecting.splice(index, 1);
4169 if (this.connecting.length) return;
4170
4171 this.close();
4172 };
4173
4174 /**
4175 * Writes a packet.
4176 *
4177 * @param {Object} packet
4178 * @api private
4179 */
4180
4181 Manager.prototype.packet = function (packet) {
4182 debug('writing packet %j', packet);
4183 var self = this;
4184 if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
4185
4186 if (!self.encoding) {
4187 // encode, then write to engine with result
4188 self.encoding = true;
4189 this.encoder.encode(packet, function (encodedPackets) {
4190 for (var i = 0; i < encodedPackets.length; i++) {
4191 self.engine.write(encodedPackets[i], packet.options);
4192 }
4193 self.encoding = false;
4194 self.processPacketQueue();
4195 });
4196 } else {
4197 // add packet to the queue
4198 self.packetBuffer.push(packet);
4199 }
4200 };
4201
4202 /**
4203 * If packet buffer is non-empty, begins encoding the
4204 * next packet in line.
4205 *
4206 * @api private
4207 */
4208
4209 Manager.prototype.processPacketQueue = function () {
4210 if (this.packetBuffer.length > 0 && !this.encoding) {
4211 var pack = this.packetBuffer.shift();
4212 this.packet(pack);
4213 }
4214 };
4215
4216 /**
4217 * Clean up transport subscriptions and packet buffer.
4218 *
4219 * @api private
4220 */
4221
4222 Manager.prototype.cleanup = function () {
4223 debug('cleanup');
4224
4225 var subsLength = this.subs.length;
4226 for (var i = 0; i < subsLength; i++) {
4227 var sub = this.subs.shift();
4228 sub.destroy();
4229 }
4230
4231 this.packetBuffer = [];
4232 this.encoding = false;
4233 this.lastPing = null;
4234
4235 this.decoder.destroy();
4236 };
4237
4238 /**
4239 * Close the current socket.
4240 *
4241 * @api private
4242 */
4243
4244 Manager.prototype.close = Manager.prototype.disconnect = function () {
4245 debug('disconnect');
4246 this.skipReconnect = true;
4247 this.reconnecting = false;
4248 if ('opening' === this.readyState) {
4249 // `onclose` will not fire because
4250 // an open event never happened
4251 this.cleanup();
4252 }
4253 this.backoff.reset();
4254 this.readyState = 'closed';
4255 if (this.engine) this.engine.close();
4256 };
4257
4258 /**
4259 * Called upon engine close.
4260 *
4261 * @api private
4262 */
4263
4264 Manager.prototype.onclose = function (reason) {
4265 debug('onclose');
4266
4267 this.cleanup();
4268 this.backoff.reset();
4269 this.readyState = 'closed';
4270 this.emit('close', reason);
4271
4272 if (this._reconnection && !this.skipReconnect) {
4273 this.reconnect();
4274 }
4275 };
4276
4277 /**
4278 * Attempt a reconnection.
4279 *
4280 * @api private
4281 */
4282
4283 Manager.prototype.reconnect = function () {
4284 if (this.reconnecting || this.skipReconnect) return this;
4285
4286 var self = this;
4287
4288 if (this.backoff.attempts >= this._reconnectionAttempts) {
4289 debug('reconnect failed');
4290 this.backoff.reset();
4291 this.emitAll('reconnect_failed');
4292 this.reconnecting = false;
4293 } else {
4294 var delay = this.backoff.duration();
4295 debug('will wait %dms before reconnect attempt', delay);
4296
4297 this.reconnecting = true;
4298 var timer = setTimeout(function () {
4299 if (self.skipReconnect) return;
4300
4301 debug('attempting reconnect');
4302 self.emitAll('reconnect_attempt', self.backoff.attempts);
4303 self.emitAll('reconnecting', self.backoff.attempts);
4304
4305 // check again for the case socket closed in above events
4306 if (self.skipReconnect) return;
4307
4308 self.open(function (err) {
4309 if (err) {
4310 debug('reconnect attempt error');
4311 self.reconnecting = false;
4312 self.reconnect();
4313 self.emitAll('reconnect_error', err.data);
4314 } else {
4315 debug('reconnect success');
4316 self.onreconnect();
4317 }
4318 });
4319 }, delay);
4320
4321 this.subs.push({
4322 destroy: function destroy() {
4323 clearTimeout(timer);
4324 }
4325 });
4326 }
4327 };
4328
4329 /**
4330 * Called upon successful reconnect.
4331 *
4332 * @api private
4333 */
4334
4335 Manager.prototype.onreconnect = function () {
4336 var attempt = this.backoff.attempts;
4337 this.reconnecting = false;
4338 this.backoff.reset();
4339 this.updateSocketIds();
4340 this.emitAll('reconnect', attempt);
4341 };
4342
4343 /***/
4344},
4345/* 20 */
4346/***/function (module, exports, __webpack_require__) {
4347
4348 module.exports = __webpack_require__(21);
4349
4350 /***/
4351},
4352/* 21 */
4353/***/function (module, exports, __webpack_require__) {
4354
4355 module.exports = __webpack_require__(22);
4356
4357 /**
4358 * Exports parser
4359 *
4360 * @api public
4361 *
4362 */
4363 module.exports.parser = __webpack_require__(29);
4364
4365 /***/
4366},
4367/* 22 */
4368/***/function (module, exports, __webpack_require__) {
4369
4370 /* WEBPACK VAR INJECTION */(function (global) {
4371 /**
4372 * Module dependencies.
4373 */
4374
4375 var transports = __webpack_require__(23);
4376 var Emitter = __webpack_require__(37);
4377 var debug = __webpack_require__(41)('engine.io-client:socket');
4378 var index = __webpack_require__(47);
4379 var parser = __webpack_require__(29);
4380 var parseuri = __webpack_require__(3);
4381 var parsejson = __webpack_require__(48);
4382 var parseqs = __webpack_require__(38);
4383
4384 /**
4385 * Module exports.
4386 */
4387
4388 module.exports = Socket;
4389
4390 /**
4391 * Socket constructor.
4392 *
4393 * @param {String|Object} uri or options
4394 * @param {Object} options
4395 * @api public
4396 */
4397
4398 function Socket(uri, opts) {
4399 if (!(this instanceof Socket)) return new Socket(uri, opts);
4400
4401 opts = opts || {};
4402
4403 if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
4404 opts = uri;
4405 uri = null;
4406 }
4407
4408 if (uri) {
4409 uri = parseuri(uri);
4410 opts.hostname = uri.host;
4411 opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
4412 opts.port = uri.port;
4413 if (uri.query) opts.query = uri.query;
4414 } else if (opts.host) {
4415 opts.hostname = parseuri(opts.host).host;
4416 }
4417
4418 this.secure = null != opts.secure ? opts.secure : global.location && 'https:' === location.protocol;
4419
4420 if (opts.hostname && !opts.port) {
4421 // if no port is specified manually, use the protocol default
4422 opts.port = this.secure ? '443' : '80';
4423 }
4424
4425 this.agent = opts.agent || false;
4426 this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost');
4427 this.port = opts.port || (global.location && location.port ? location.port : this.secure ? 443 : 80);
4428 this.query = opts.query || {};
4429 if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
4430 this.upgrade = false !== opts.upgrade;
4431 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
4432 this.forceJSONP = !!opts.forceJSONP;
4433 this.jsonp = false !== opts.jsonp;
4434 this.forceBase64 = !!opts.forceBase64;
4435 this.enablesXDR = !!opts.enablesXDR;
4436 this.timestampParam = opts.timestampParam || 't';
4437 this.timestampRequests = opts.timestampRequests;
4438 this.transports = opts.transports || ['polling', 'websocket'];
4439 this.readyState = '';
4440 this.writeBuffer = [];
4441 this.prevBufferLen = 0;
4442 this.policyPort = opts.policyPort || 843;
4443 this.rememberUpgrade = opts.rememberUpgrade || false;
4444 this.binaryType = null;
4445 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
4446 this.perMessageDeflate = false !== opts.perMessageDeflate ? opts.perMessageDeflate || {} : false;
4447
4448 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
4449 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
4450 this.perMessageDeflate.threshold = 1024;
4451 }
4452
4453 // SSL options for Node.js client
4454 this.pfx = opts.pfx || null;
4455 this.key = opts.key || null;
4456 this.passphrase = opts.passphrase || null;
4457 this.cert = opts.cert || null;
4458 this.ca = opts.ca || null;
4459 this.ciphers = opts.ciphers || null;
4460 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
4461 this.forceNode = !!opts.forceNode;
4462
4463 // other options for Node.js client
4464 var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global;
4465 if (freeGlobal.global === freeGlobal) {
4466 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
4467 this.extraHeaders = opts.extraHeaders;
4468 }
4469
4470 if (opts.localAddress) {
4471 this.localAddress = opts.localAddress;
4472 }
4473 }
4474
4475 // set on handshake
4476 this.id = null;
4477 this.upgrades = null;
4478 this.pingInterval = null;
4479 this.pingTimeout = null;
4480
4481 // set on heartbeat
4482 this.pingIntervalTimer = null;
4483 this.pingTimeoutTimer = null;
4484
4485 this.open();
4486 }
4487
4488 Socket.priorWebsocketSuccess = false;
4489
4490 /**
4491 * Mix in `Emitter`.
4492 */
4493
4494 Emitter(Socket.prototype);
4495
4496 /**
4497 * Protocol version.
4498 *
4499 * @api public
4500 */
4501
4502 Socket.protocol = parser.protocol; // this is an int
4503
4504 /**
4505 * Expose deps for legacy compatibility
4506 * and standalone browser access.
4507 */
4508
4509 Socket.Socket = Socket;
4510 Socket.Transport = __webpack_require__(28);
4511 Socket.transports = __webpack_require__(23);
4512 Socket.parser = __webpack_require__(29);
4513
4514 /**
4515 * Creates transport of the given type.
4516 *
4517 * @param {String} transport name
4518 * @return {Transport}
4519 * @api private
4520 */
4521
4522 Socket.prototype.createTransport = function (name) {
4523 debug('creating transport "%s"', name);
4524 var query = clone(this.query);
4525
4526 // append engine.io protocol identifier
4527 query.EIO = parser.protocol;
4528
4529 // transport name
4530 query.transport = name;
4531
4532 // session id if we already have one
4533 if (this.id) query.sid = this.id;
4534
4535 var transport = new transports[name]({
4536 agent: this.agent,
4537 hostname: this.hostname,
4538 port: this.port,
4539 secure: this.secure,
4540 path: this.path,
4541 query: query,
4542 forceJSONP: this.forceJSONP,
4543 jsonp: this.jsonp,
4544 forceBase64: this.forceBase64,
4545 enablesXDR: this.enablesXDR,
4546 timestampRequests: this.timestampRequests,
4547 timestampParam: this.timestampParam,
4548 policyPort: this.policyPort,
4549 socket: this,
4550 pfx: this.pfx,
4551 key: this.key,
4552 passphrase: this.passphrase,
4553 cert: this.cert,
4554 ca: this.ca,
4555 ciphers: this.ciphers,
4556 rejectUnauthorized: this.rejectUnauthorized,
4557 perMessageDeflate: this.perMessageDeflate,
4558 extraHeaders: this.extraHeaders,
4559 forceNode: this.forceNode,
4560 localAddress: this.localAddress
4561 });
4562
4563 return transport;
4564 };
4565
4566 function clone(obj) {
4567 var o = {};
4568 for (var i in obj) {
4569 if (obj.hasOwnProperty(i)) {
4570 o[i] = obj[i];
4571 }
4572 }
4573 return o;
4574 }
4575
4576 /**
4577 * Initializes transport to use and starts probe.
4578 *
4579 * @api private
4580 */
4581 Socket.prototype.open = function () {
4582 var transport;
4583 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
4584 transport = 'websocket';
4585 } else if (0 === this.transports.length) {
4586 // Emit error on next tick so it can be listened to
4587 var self = this;
4588 setTimeout(function () {
4589 self.emit('error', 'No transports available');
4590 }, 0);
4591 return;
4592 } else {
4593 transport = this.transports[0];
4594 }
4595 this.readyState = 'opening';
4596
4597 // Retry with the next transport if the transport is disabled (jsonp: false)
4598 try {
4599 transport = this.createTransport(transport);
4600 } catch (e) {
4601 this.transports.shift();
4602 this.open();
4603 return;
4604 }
4605
4606 transport.open();
4607 this.setTransport(transport);
4608 };
4609
4610 /**
4611 * Sets the current transport. Disables the existing one (if any).
4612 *
4613 * @api private
4614 */
4615
4616 Socket.prototype.setTransport = function (transport) {
4617 debug('setting transport %s', transport.name);
4618 var self = this;
4619
4620 if (this.transport) {
4621 debug('clearing existing transport %s', this.transport.name);
4622 this.transport.removeAllListeners();
4623 }
4624
4625 // set up transport
4626 this.transport = transport;
4627
4628 // set up transport listeners
4629 transport.on('drain', function () {
4630 self.onDrain();
4631 }).on('packet', function (packet) {
4632 self.onPacket(packet);
4633 }).on('error', function (e) {
4634 self.onError(e);
4635 }).on('close', function () {
4636 self.onClose('transport close');
4637 });
4638 };
4639
4640 /**
4641 * Probes a transport.
4642 *
4643 * @param {String} transport name
4644 * @api private
4645 */
4646
4647 Socket.prototype.probe = function (name) {
4648 debug('probing transport "%s"', name);
4649 var transport = this.createTransport(name, { probe: 1 });
4650 var failed = false;
4651 var self = this;
4652
4653 Socket.priorWebsocketSuccess = false;
4654
4655 function onTransportOpen() {
4656 if (self.onlyBinaryUpgrades) {
4657 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
4658 failed = failed || upgradeLosesBinary;
4659 }
4660 if (failed) return;
4661
4662 debug('probe transport "%s" opened', name);
4663 transport.send([{ type: 'ping', data: 'probe' }]);
4664 transport.once('packet', function (msg) {
4665 if (failed) return;
4666 if ('pong' === msg.type && 'probe' === msg.data) {
4667 debug('probe transport "%s" pong', name);
4668 self.upgrading = true;
4669 self.emit('upgrading', transport);
4670 if (!transport) return;
4671 Socket.priorWebsocketSuccess = 'websocket' === transport.name;
4672
4673 debug('pausing current transport "%s"', self.transport.name);
4674 self.transport.pause(function () {
4675 if (failed) return;
4676 if ('closed' === self.readyState) return;
4677 debug('changing transport and sending upgrade packet');
4678
4679 cleanup();
4680
4681 self.setTransport(transport);
4682 transport.send([{ type: 'upgrade' }]);
4683 self.emit('upgrade', transport);
4684 transport = null;
4685 self.upgrading = false;
4686 self.flush();
4687 });
4688 } else {
4689 debug('probe transport "%s" failed', name);
4690 var err = new Error('probe error');
4691 err.transport = transport.name;
4692 self.emit('upgradeError', err);
4693 }
4694 });
4695 }
4696
4697 function freezeTransport() {
4698 if (failed) return;
4699
4700 // Any callback called by transport should be ignored since now
4701 failed = true;
4702
4703 cleanup();
4704
4705 transport.close();
4706 transport = null;
4707 }
4708
4709 // Handle any error that happens while probing
4710 function onerror(err) {
4711 var error = new Error('probe error: ' + err);
4712 error.transport = transport.name;
4713
4714 freezeTransport();
4715
4716 debug('probe transport "%s" failed because of error: %s', name, err);
4717
4718 self.emit('upgradeError', error);
4719 }
4720
4721 function onTransportClose() {
4722 onerror('transport closed');
4723 }
4724
4725 // When the socket is closed while we're probing
4726 function onclose() {
4727 onerror('socket closed');
4728 }
4729
4730 // When the socket is upgraded while we're probing
4731 function onupgrade(to) {
4732 if (transport && to.name !== transport.name) {
4733 debug('"%s" works - aborting "%s"', to.name, transport.name);
4734 freezeTransport();
4735 }
4736 }
4737
4738 // Remove all listeners on the transport and on self
4739 function cleanup() {
4740 transport.removeListener('open', onTransportOpen);
4741 transport.removeListener('error', onerror);
4742 transport.removeListener('close', onTransportClose);
4743 self.removeListener('close', onclose);
4744 self.removeListener('upgrading', onupgrade);
4745 }
4746
4747 transport.once('open', onTransportOpen);
4748 transport.once('error', onerror);
4749 transport.once('close', onTransportClose);
4750
4751 this.once('close', onclose);
4752 this.once('upgrading', onupgrade);
4753
4754 transport.open();
4755 };
4756
4757 /**
4758 * Called when connection is deemed open.
4759 *
4760 * @api public
4761 */
4762
4763 Socket.prototype.onOpen = function () {
4764 debug('socket open');
4765 this.readyState = 'open';
4766 Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
4767 this.emit('open');
4768 this.flush();
4769
4770 // we check for `readyState` in case an `open`
4771 // listener already closed the socket
4772 if ('open' === this.readyState && this.upgrade && this.transport.pause) {
4773 debug('starting upgrade probes');
4774 for (var i = 0, l = this.upgrades.length; i < l; i++) {
4775 this.probe(this.upgrades[i]);
4776 }
4777 }
4778 };
4779
4780 /**
4781 * Handles a packet.
4782 *
4783 * @api private
4784 */
4785
4786 Socket.prototype.onPacket = function (packet) {
4787 if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
4788 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
4789
4790 this.emit('packet', packet);
4791
4792 // Socket is live - any packet counts
4793 this.emit('heartbeat');
4794
4795 switch (packet.type) {
4796 case 'open':
4797 this.onHandshake(parsejson(packet.data));
4798 break;
4799
4800 case 'pong':
4801 this.setPing();
4802 this.emit('pong');
4803 break;
4804
4805 case 'error':
4806 var err = new Error('server error');
4807 err.code = packet.data;
4808 this.onError(err);
4809 break;
4810
4811 case 'message':
4812 this.emit('data', packet.data);
4813 this.emit('message', packet.data);
4814 break;
4815 }
4816 } else {
4817 debug('packet received with socket readyState "%s"', this.readyState);
4818 }
4819 };
4820
4821 /**
4822 * Called upon handshake completion.
4823 *
4824 * @param {Object} handshake obj
4825 * @api private
4826 */
4827
4828 Socket.prototype.onHandshake = function (data) {
4829 this.emit('handshake', data);
4830 this.id = data.sid;
4831 this.transport.query.sid = data.sid;
4832 this.upgrades = this.filterUpgrades(data.upgrades);
4833 this.pingInterval = data.pingInterval;
4834 this.pingTimeout = data.pingTimeout;
4835 this.onOpen();
4836 // In case open handler closes socket
4837 if ('closed' === this.readyState) return;
4838 this.setPing();
4839
4840 // Prolong liveness of socket on heartbeat
4841 this.removeListener('heartbeat', this.onHeartbeat);
4842 this.on('heartbeat', this.onHeartbeat);
4843 };
4844
4845 /**
4846 * Resets ping timeout.
4847 *
4848 * @api private
4849 */
4850
4851 Socket.prototype.onHeartbeat = function (timeout) {
4852 clearTimeout(this.pingTimeoutTimer);
4853 var self = this;
4854 self.pingTimeoutTimer = setTimeout(function () {
4855 if ('closed' === self.readyState) return;
4856 self.onClose('ping timeout');
4857 }, timeout || self.pingInterval + self.pingTimeout);
4858 };
4859
4860 /**
4861 * Pings server every `this.pingInterval` and expects response
4862 * within `this.pingTimeout` or closes connection.
4863 *
4864 * @api private
4865 */
4866
4867 Socket.prototype.setPing = function () {
4868 var self = this;
4869 clearTimeout(self.pingIntervalTimer);
4870 self.pingIntervalTimer = setTimeout(function () {
4871 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
4872 self.ping();
4873 self.onHeartbeat(self.pingTimeout);
4874 }, self.pingInterval);
4875 };
4876
4877 /**
4878 * Sends a ping packet.
4879 *
4880 * @api private
4881 */
4882
4883 Socket.prototype.ping = function () {
4884 var self = this;
4885 this.sendPacket('ping', function () {
4886 self.emit('ping');
4887 });
4888 };
4889
4890 /**
4891 * Called on `drain` event
4892 *
4893 * @api private
4894 */
4895
4896 Socket.prototype.onDrain = function () {
4897 this.writeBuffer.splice(0, this.prevBufferLen);
4898
4899 // setting prevBufferLen = 0 is very important
4900 // for example, when upgrading, upgrade packet is sent over,
4901 // and a nonzero prevBufferLen could cause problems on `drain`
4902 this.prevBufferLen = 0;
4903
4904 if (0 === this.writeBuffer.length) {
4905 this.emit('drain');
4906 } else {
4907 this.flush();
4908 }
4909 };
4910
4911 /**
4912 * Flush write buffers.
4913 *
4914 * @api private
4915 */
4916
4917 Socket.prototype.flush = function () {
4918 if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
4919 debug('flushing %d packets in socket', this.writeBuffer.length);
4920 this.transport.send(this.writeBuffer);
4921 // keep track of current length of writeBuffer
4922 // splice writeBuffer and callbackBuffer on `drain`
4923 this.prevBufferLen = this.writeBuffer.length;
4924 this.emit('flush');
4925 }
4926 };
4927
4928 /**
4929 * Sends a message.
4930 *
4931 * @param {String} message.
4932 * @param {Function} callback function.
4933 * @param {Object} options.
4934 * @return {Socket} for chaining.
4935 * @api public
4936 */
4937
4938 Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) {
4939 this.sendPacket('message', msg, options, fn);
4940 return this;
4941 };
4942
4943 /**
4944 * Sends a packet.
4945 *
4946 * @param {String} packet type.
4947 * @param {String} data.
4948 * @param {Object} options.
4949 * @param {Function} callback function.
4950 * @api private
4951 */
4952
4953 Socket.prototype.sendPacket = function (type, data, options, fn) {
4954 if ('function' === typeof data) {
4955 fn = data;
4956 data = undefined;
4957 }
4958
4959 if ('function' === typeof options) {
4960 fn = options;
4961 options = null;
4962 }
4963
4964 if ('closing' === this.readyState || 'closed' === this.readyState) {
4965 return;
4966 }
4967
4968 options = options || {};
4969 options.compress = false !== options.compress;
4970
4971 var packet = {
4972 type: type,
4973 data: data,
4974 options: options
4975 };
4976 this.emit('packetCreate', packet);
4977 this.writeBuffer.push(packet);
4978 if (fn) this.once('flush', fn);
4979 this.flush();
4980 };
4981
4982 /**
4983 * Closes the connection.
4984 *
4985 * @api private
4986 */
4987
4988 Socket.prototype.close = function () {
4989 if ('opening' === this.readyState || 'open' === this.readyState) {
4990 this.readyState = 'closing';
4991
4992 var self = this;
4993
4994 if (this.writeBuffer.length) {
4995 this.once('drain', function () {
4996 if (this.upgrading) {
4997 waitForUpgrade();
4998 } else {
4999 close();
5000 }
5001 });
5002 } else if (this.upgrading) {
5003 waitForUpgrade();
5004 } else {
5005 close();
5006 }
5007 }
5008
5009 function close() {
5010 self.onClose('forced close');
5011 debug('socket closing - telling transport to close');
5012 self.transport.close();
5013 }
5014
5015 function cleanupAndClose() {
5016 self.removeListener('upgrade', cleanupAndClose);
5017 self.removeListener('upgradeError', cleanupAndClose);
5018 close();
5019 }
5020
5021 function waitForUpgrade() {
5022 // wait for upgrade to finish since we can't send packets while pausing a transport
5023 self.once('upgrade', cleanupAndClose);
5024 self.once('upgradeError', cleanupAndClose);
5025 }
5026
5027 return this;
5028 };
5029
5030 /**
5031 * Called upon transport error
5032 *
5033 * @api private
5034 */
5035
5036 Socket.prototype.onError = function (err) {
5037 debug('socket error %j', err);
5038 Socket.priorWebsocketSuccess = false;
5039 this.emit('error', err);
5040 this.onClose('transport error', err);
5041 };
5042
5043 /**
5044 * Called upon transport close.
5045 *
5046 * @api private
5047 */
5048
5049 Socket.prototype.onClose = function (reason, desc) {
5050 if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
5051 debug('socket close with reason: "%s"', reason);
5052 var self = this;
5053
5054 // clear timers
5055 clearTimeout(this.pingIntervalTimer);
5056 clearTimeout(this.pingTimeoutTimer);
5057
5058 // stop event from firing again for transport
5059 this.transport.removeAllListeners('close');
5060
5061 // ensure transport won't stay open
5062 this.transport.close();
5063
5064 // ignore further transport communication
5065 this.transport.removeAllListeners();
5066
5067 // set ready state
5068 this.readyState = 'closed';
5069
5070 // clear session id
5071 this.id = null;
5072
5073 // emit close event
5074 this.emit('close', reason, desc);
5075
5076 // clean buffers after, so users can still
5077 // grab the buffers on `close` event
5078 self.writeBuffer = [];
5079 self.prevBufferLen = 0;
5080 }
5081 };
5082
5083 /**
5084 * Filters upgrades, returning only those matching client transports.
5085 *
5086 * @param {Array} server upgrades
5087 * @api private
5088 *
5089 */
5090
5091 Socket.prototype.filterUpgrades = function (upgrades) {
5092 var filteredUpgrades = [];
5093 for (var i = 0, j = upgrades.length; i < j; i++) {
5094 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
5095 }
5096 return filteredUpgrades;
5097 };
5098
5099 /* WEBPACK VAR INJECTION */
5100 }).call(exports, function () {
5101 return this;
5102 }());
5103
5104 /***/
5105},
5106/* 23 */
5107/***/function (module, exports, __webpack_require__) {
5108
5109 /* WEBPACK VAR INJECTION */(function (global) {
5110 /**
5111 * Module dependencies
5112 */
5113
5114 var XMLHttpRequest = __webpack_require__(24);
5115 var XHR = __webpack_require__(26);
5116 var JSONP = __webpack_require__(44);
5117 var websocket = __webpack_require__(45);
5118
5119 /**
5120 * Export transports.
5121 */
5122
5123 exports.polling = polling;
5124 exports.websocket = websocket;
5125
5126 /**
5127 * Polling transport polymorphic constructor.
5128 * Decides on xhr vs jsonp based on feature detection.
5129 *
5130 * @api private
5131 */
5132
5133 function polling(opts) {
5134 var xhr;
5135 var xd = false;
5136 var xs = false;
5137 var jsonp = false !== opts.jsonp;
5138
5139 if (global.location) {
5140 var isSSL = 'https:' === location.protocol;
5141 var port = location.port;
5142
5143 // some user agents have empty `location.port`
5144 if (!port) {
5145 port = isSSL ? 443 : 80;
5146 }
5147
5148 xd = opts.hostname !== location.hostname || port !== opts.port;
5149 xs = opts.secure !== isSSL;
5150 }
5151
5152 opts.xdomain = xd;
5153 opts.xscheme = xs;
5154 xhr = new XMLHttpRequest(opts);
5155
5156 if ('open' in xhr && !opts.forceJSONP) {
5157 return new XHR(opts);
5158 } else {
5159 if (!jsonp) throw new Error('JSONP disabled');
5160 return new JSONP(opts);
5161 }
5162 }
5163
5164 /* WEBPACK VAR INJECTION */
5165 }).call(exports, function () {
5166 return this;
5167 }());
5168
5169 /***/
5170},
5171/* 24 */
5172/***/function (module, exports, __webpack_require__) {
5173
5174 /* WEBPACK VAR INJECTION */(function (global) {
5175 // browser shim for xmlhttprequest module
5176
5177 var hasCORS = __webpack_require__(25);
5178
5179 module.exports = function (opts) {
5180 var xdomain = opts.xdomain;
5181
5182 // scheme must be same when usign XDomainRequest
5183 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
5184 var xscheme = opts.xscheme;
5185
5186 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
5187 // https://github.com/Automattic/engine.io-client/pull/217
5188 var enablesXDR = opts.enablesXDR;
5189
5190 // XMLHttpRequest can be disabled on IE
5191 try {
5192 if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
5193 return new XMLHttpRequest();
5194 }
5195 } catch (e) {}
5196
5197 // Use XDomainRequest for IE8 if enablesXDR is true
5198 // because loading bar keeps flashing when using jsonp-polling
5199 // https://github.com/yujiosaka/socke.io-ie8-loading-example
5200 try {
5201 if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
5202 return new XDomainRequest();
5203 }
5204 } catch (e) {}
5205
5206 if (!xdomain) {
5207 try {
5208 return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
5209 } catch (e) {}
5210 }
5211 };
5212
5213 /* WEBPACK VAR INJECTION */
5214 }).call(exports, function () {
5215 return this;
5216 }());
5217
5218 /***/
5219},
5220/* 25 */
5221/***/function (module, exports) {
5222
5223 /**
5224 * Module exports.
5225 *
5226 * Logic borrowed from Modernizr:
5227 *
5228 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
5229 */
5230
5231 try {
5232 module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
5233 } catch (err) {
5234 // if XMLHttp support is disabled in IE then it will throw
5235 // when trying to create
5236 module.exports = false;
5237 }
5238
5239 /***/
5240},
5241/* 26 */
5242/***/function (module, exports, __webpack_require__) {
5243
5244 /* WEBPACK VAR INJECTION */(function (global) {
5245 /**
5246 * Module requirements.
5247 */
5248
5249 var XMLHttpRequest = __webpack_require__(24);
5250 var Polling = __webpack_require__(27);
5251 var Emitter = __webpack_require__(37);
5252 var inherit = __webpack_require__(39);
5253 var debug = __webpack_require__(41)('engine.io-client:polling-xhr');
5254
5255 /**
5256 * Module exports.
5257 */
5258
5259 module.exports = XHR;
5260 module.exports.Request = Request;
5261
5262 /**
5263 * Empty function
5264 */
5265
5266 function empty() {}
5267
5268 /**
5269 * XHR Polling constructor.
5270 *
5271 * @param {Object} opts
5272 * @api public
5273 */
5274
5275 function XHR(opts) {
5276 Polling.call(this, opts);
5277 this.requestTimeout = opts.requestTimeout;
5278
5279 if (global.location) {
5280 var isSSL = 'https:' === location.protocol;
5281 var port = location.port;
5282
5283 // some user agents have empty `location.port`
5284 if (!port) {
5285 port = isSSL ? 443 : 80;
5286 }
5287
5288 this.xd = opts.hostname !== global.location.hostname || port !== opts.port;
5289 this.xs = opts.secure !== isSSL;
5290 } else {
5291 this.extraHeaders = opts.extraHeaders;
5292 }
5293 }
5294
5295 /**
5296 * Inherits from Polling.
5297 */
5298
5299 inherit(XHR, Polling);
5300
5301 /**
5302 * XHR supports binary
5303 */
5304
5305 XHR.prototype.supportsBinary = true;
5306
5307 /**
5308 * Creates a request.
5309 *
5310 * @param {String} method
5311 * @api private
5312 */
5313
5314 XHR.prototype.request = function (opts) {
5315 opts = opts || {};
5316 opts.uri = this.uri();
5317 opts.xd = this.xd;
5318 opts.xs = this.xs;
5319 opts.agent = this.agent || false;
5320 opts.supportsBinary = this.supportsBinary;
5321 opts.enablesXDR = this.enablesXDR;
5322
5323 // SSL options for Node.js client
5324 opts.pfx = this.pfx;
5325 opts.key = this.key;
5326 opts.passphrase = this.passphrase;
5327 opts.cert = this.cert;
5328 opts.ca = this.ca;
5329 opts.ciphers = this.ciphers;
5330 opts.rejectUnauthorized = this.rejectUnauthorized;
5331 opts.requestTimeout = this.requestTimeout;
5332
5333 // other options for Node.js client
5334 opts.extraHeaders = this.extraHeaders;
5335
5336 return new Request(opts);
5337 };
5338
5339 /**
5340 * Sends data.
5341 *
5342 * @param {String} data to send.
5343 * @param {Function} called upon flush.
5344 * @api private
5345 */
5346
5347 XHR.prototype.doWrite = function (data, fn) {
5348 var isBinary = typeof data !== 'string' && data !== undefined;
5349 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
5350 var self = this;
5351 req.on('success', fn);
5352 req.on('error', function (err) {
5353 self.onError('xhr post error', err);
5354 });
5355 this.sendXhr = req;
5356 };
5357
5358 /**
5359 * Starts a poll cycle.
5360 *
5361 * @api private
5362 */
5363
5364 XHR.prototype.doPoll = function () {
5365 debug('xhr poll');
5366 var req = this.request();
5367 var self = this;
5368 req.on('data', function (data) {
5369 self.onData(data);
5370 });
5371 req.on('error', function (err) {
5372 self.onError('xhr poll error', err);
5373 });
5374 this.pollXhr = req;
5375 };
5376
5377 /**
5378 * Request constructor
5379 *
5380 * @param {Object} options
5381 * @api public
5382 */
5383
5384 function Request(opts) {
5385 this.method = opts.method || 'GET';
5386 this.uri = opts.uri;
5387 this.xd = !!opts.xd;
5388 this.xs = !!opts.xs;
5389 this.async = false !== opts.async;
5390 this.data = undefined !== opts.data ? opts.data : null;
5391 this.agent = opts.agent;
5392 this.isBinary = opts.isBinary;
5393 this.supportsBinary = opts.supportsBinary;
5394 this.enablesXDR = opts.enablesXDR;
5395 this.requestTimeout = opts.requestTimeout;
5396
5397 // SSL options for Node.js client
5398 this.pfx = opts.pfx;
5399 this.key = opts.key;
5400 this.passphrase = opts.passphrase;
5401 this.cert = opts.cert;
5402 this.ca = opts.ca;
5403 this.ciphers = opts.ciphers;
5404 this.rejectUnauthorized = opts.rejectUnauthorized;
5405
5406 // other options for Node.js client
5407 this.extraHeaders = opts.extraHeaders;
5408
5409 this.create();
5410 }
5411
5412 /**
5413 * Mix in `Emitter`.
5414 */
5415
5416 Emitter(Request.prototype);
5417
5418 /**
5419 * Creates the XHR object and sends the request.
5420 *
5421 * @api private
5422 */
5423
5424 Request.prototype.create = function () {
5425 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
5426
5427 // SSL options for Node.js client
5428 opts.pfx = this.pfx;
5429 opts.key = this.key;
5430 opts.passphrase = this.passphrase;
5431 opts.cert = this.cert;
5432 opts.ca = this.ca;
5433 opts.ciphers = this.ciphers;
5434 opts.rejectUnauthorized = this.rejectUnauthorized;
5435
5436 var xhr = this.xhr = new XMLHttpRequest(opts);
5437 var self = this;
5438
5439 try {
5440 debug('xhr open %s: %s', this.method, this.uri);
5441 xhr.open(this.method, this.uri, this.async);
5442 try {
5443 if (this.extraHeaders) {
5444 xhr.setDisableHeaderCheck(true);
5445 for (var i in this.extraHeaders) {
5446 if (this.extraHeaders.hasOwnProperty(i)) {
5447 xhr.setRequestHeader(i, this.extraHeaders[i]);
5448 }
5449 }
5450 }
5451 } catch (e) {}
5452 if (this.supportsBinary) {
5453 // This has to be done after open because Firefox is stupid
5454 // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
5455 xhr.responseType = 'arraybuffer';
5456 }
5457
5458 if ('POST' === this.method) {
5459 try {
5460 if (this.isBinary) {
5461 xhr.setRequestHeader('Content-type', 'application/octet-stream');
5462 } else {
5463 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
5464 }
5465 } catch (e) {}
5466 }
5467
5468 try {
5469 xhr.setRequestHeader('Accept', '*/*');
5470 } catch (e) {}
5471
5472 // ie6 check
5473 if ('withCredentials' in xhr) {
5474 xhr.withCredentials = true;
5475 }
5476
5477 if (this.requestTimeout) {
5478 xhr.timeout = this.requestTimeout;
5479 }
5480
5481 if (this.hasXDR()) {
5482 xhr.onload = function () {
5483 self.onLoad();
5484 };
5485 xhr.onerror = function () {
5486 self.onError(xhr.responseText);
5487 };
5488 } else {
5489 xhr.onreadystatechange = function () {
5490 if (4 !== xhr.readyState) return;
5491 if (200 === xhr.status || 1223 === xhr.status) {
5492 self.onLoad();
5493 } else {
5494 // make sure the `error` event handler that's user-set
5495 // does not throw in the same tick and gets caught here
5496 setTimeout(function () {
5497 self.onError(xhr.status);
5498 }, 0);
5499 }
5500 };
5501 }
5502
5503 debug('xhr data %s', this.data);
5504 xhr.send(this.data);
5505 } catch (e) {
5506 // Need to defer since .create() is called directly fhrom the constructor
5507 // and thus the 'error' event can only be only bound *after* this exception
5508 // occurs. Therefore, also, we cannot throw here at all.
5509 setTimeout(function () {
5510 self.onError(e);
5511 }, 0);
5512 return;
5513 }
5514
5515 if (global.document) {
5516 this.index = Request.requestsCount++;
5517 Request.requests[this.index] = this;
5518 }
5519 };
5520
5521 /**
5522 * Called upon successful response.
5523 *
5524 * @api private
5525 */
5526
5527 Request.prototype.onSuccess = function () {
5528 this.emit('success');
5529 this.cleanup();
5530 };
5531
5532 /**
5533 * Called if we have data.
5534 *
5535 * @api private
5536 */
5537
5538 Request.prototype.onData = function (data) {
5539 this.emit('data', data);
5540 this.onSuccess();
5541 };
5542
5543 /**
5544 * Called upon error.
5545 *
5546 * @api private
5547 */
5548
5549 Request.prototype.onError = function (err) {
5550 this.emit('error', err);
5551 this.cleanup(true);
5552 };
5553
5554 /**
5555 * Cleans up house.
5556 *
5557 * @api private
5558 */
5559
5560 Request.prototype.cleanup = function (fromError) {
5561 if ('undefined' === typeof this.xhr || null === this.xhr) {
5562 return;
5563 }
5564 // xmlhttprequest
5565 if (this.hasXDR()) {
5566 this.xhr.onload = this.xhr.onerror = empty;
5567 } else {
5568 this.xhr.onreadystatechange = empty;
5569 }
5570
5571 if (fromError) {
5572 try {
5573 this.xhr.abort();
5574 } catch (e) {}
5575 }
5576
5577 if (global.document) {
5578 delete Request.requests[this.index];
5579 }
5580
5581 this.xhr = null;
5582 };
5583
5584 /**
5585 * Called upon load.
5586 *
5587 * @api private
5588 */
5589
5590 Request.prototype.onLoad = function () {
5591 var data;
5592 try {
5593 var contentType;
5594 try {
5595 contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
5596 } catch (e) {}
5597 if (contentType === 'application/octet-stream') {
5598 data = this.xhr.response || this.xhr.responseText;
5599 } else {
5600 if (!this.supportsBinary) {
5601 data = this.xhr.responseText;
5602 } else {
5603 try {
5604 data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
5605 } catch (e) {
5606 var ui8Arr = new Uint8Array(this.xhr.response);
5607 var dataArray = [];
5608 for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
5609 dataArray.push(ui8Arr[idx]);
5610 }
5611
5612 data = String.fromCharCode.apply(null, dataArray);
5613 }
5614 }
5615 }
5616 } catch (e) {
5617 this.onError(e);
5618 }
5619 if (null != data) {
5620 this.onData(data);
5621 }
5622 };
5623
5624 /**
5625 * Check if it has XDomainRequest.
5626 *
5627 * @api private
5628 */
5629
5630 Request.prototype.hasXDR = function () {
5631 return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
5632 };
5633
5634 /**
5635 * Aborts the request.
5636 *
5637 * @api public
5638 */
5639
5640 Request.prototype.abort = function () {
5641 this.cleanup();
5642 };
5643
5644 /**
5645 * Aborts pending requests when unloading the window. This is needed to prevent
5646 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
5647 * emitted.
5648 */
5649
5650 Request.requestsCount = 0;
5651 Request.requests = {};
5652
5653 if (global.document) {
5654 if (global.attachEvent) {
5655 global.attachEvent('onunload', unloadHandler);
5656 } else if (global.addEventListener) {
5657 global.addEventListener('beforeunload', unloadHandler, false);
5658 }
5659 }
5660
5661 function unloadHandler() {
5662 for (var i in Request.requests) {
5663 if (Request.requests.hasOwnProperty(i)) {
5664 Request.requests[i].abort();
5665 }
5666 }
5667 }
5668
5669 /* WEBPACK VAR INJECTION */
5670 }).call(exports, function () {
5671 return this;
5672 }());
5673
5674 /***/
5675},
5676/* 27 */
5677/***/function (module, exports, __webpack_require__) {
5678
5679 /**
5680 * Module dependencies.
5681 */
5682
5683 var Transport = __webpack_require__(28);
5684 var parseqs = __webpack_require__(38);
5685 var parser = __webpack_require__(29);
5686 var inherit = __webpack_require__(39);
5687 var yeast = __webpack_require__(40);
5688 var debug = __webpack_require__(41)('engine.io-client:polling');
5689
5690 /**
5691 * Module exports.
5692 */
5693
5694 module.exports = Polling;
5695
5696 /**
5697 * Is XHR2 supported?
5698 */
5699
5700 var hasXHR2 = function () {
5701 var XMLHttpRequest = __webpack_require__(24);
5702 var xhr = new XMLHttpRequest({ xdomain: false });
5703 return null != xhr.responseType;
5704 }();
5705
5706 /**
5707 * Polling interface.
5708 *
5709 * @param {Object} opts
5710 * @api private
5711 */
5712
5713 function Polling(opts) {
5714 var forceBase64 = opts && opts.forceBase64;
5715 if (!hasXHR2 || forceBase64) {
5716 this.supportsBinary = false;
5717 }
5718 Transport.call(this, opts);
5719 }
5720
5721 /**
5722 * Inherits from Transport.
5723 */
5724
5725 inherit(Polling, Transport);
5726
5727 /**
5728 * Transport name.
5729 */
5730
5731 Polling.prototype.name = 'polling';
5732
5733 /**
5734 * Opens the socket (triggers polling). We write a PING message to determine
5735 * when the transport is open.
5736 *
5737 * @api private
5738 */
5739
5740 Polling.prototype.doOpen = function () {
5741 this.poll();
5742 };
5743
5744 /**
5745 * Pauses polling.
5746 *
5747 * @param {Function} callback upon buffers are flushed and transport is paused
5748 * @api private
5749 */
5750
5751 Polling.prototype.pause = function (onPause) {
5752 var self = this;
5753
5754 this.readyState = 'pausing';
5755
5756 function pause() {
5757 debug('paused');
5758 self.readyState = 'paused';
5759 onPause();
5760 }
5761
5762 if (this.polling || !this.writable) {
5763 var total = 0;
5764
5765 if (this.polling) {
5766 debug('we are currently polling - waiting to pause');
5767 total++;
5768 this.once('pollComplete', function () {
5769 debug('pre-pause polling complete');
5770 --total || pause();
5771 });
5772 }
5773
5774 if (!this.writable) {
5775 debug('we are currently writing - waiting to pause');
5776 total++;
5777 this.once('drain', function () {
5778 debug('pre-pause writing complete');
5779 --total || pause();
5780 });
5781 }
5782 } else {
5783 pause();
5784 }
5785 };
5786
5787 /**
5788 * Starts polling cycle.
5789 *
5790 * @api public
5791 */
5792
5793 Polling.prototype.poll = function () {
5794 debug('polling');
5795 this.polling = true;
5796 this.doPoll();
5797 this.emit('poll');
5798 };
5799
5800 /**
5801 * Overloads onData to detect payloads.
5802 *
5803 * @api private
5804 */
5805
5806 Polling.prototype.onData = function (data) {
5807 var self = this;
5808 debug('polling got data %s', data);
5809 var callback = function callback(packet, index, total) {
5810 // if its the first message we consider the transport open
5811 if ('opening' === self.readyState) {
5812 self.onOpen();
5813 }
5814
5815 // if its a close packet, we close the ongoing requests
5816 if ('close' === packet.type) {
5817 self.onClose();
5818 return false;
5819 }
5820
5821 // otherwise bypass onData and handle the message
5822 self.onPacket(packet);
5823 };
5824
5825 // decode payload
5826 parser.decodePayload(data, this.socket.binaryType, callback);
5827
5828 // if an event did not trigger closing
5829 if ('closed' !== this.readyState) {
5830 // if we got data we're not polling
5831 this.polling = false;
5832 this.emit('pollComplete');
5833
5834 if ('open' === this.readyState) {
5835 this.poll();
5836 } else {
5837 debug('ignoring poll - transport state "%s"', this.readyState);
5838 }
5839 }
5840 };
5841
5842 /**
5843 * For polling, send a close packet.
5844 *
5845 * @api private
5846 */
5847
5848 Polling.prototype.doClose = function () {
5849 var self = this;
5850
5851 function close() {
5852 debug('writing close packet');
5853 self.write([{ type: 'close' }]);
5854 }
5855
5856 if ('open' === this.readyState) {
5857 debug('transport open - closing');
5858 close();
5859 } else {
5860 // in case we're trying to close while
5861 // handshaking is in progress (GH-164)
5862 debug('transport not open - deferring close');
5863 this.once('open', close);
5864 }
5865 };
5866
5867 /**
5868 * Writes a packets payload.
5869 *
5870 * @param {Array} data packets
5871 * @param {Function} drain callback
5872 * @api private
5873 */
5874
5875 Polling.prototype.write = function (packets) {
5876 var self = this;
5877 this.writable = false;
5878 var callbackfn = function callbackfn() {
5879 self.writable = true;
5880 self.emit('drain');
5881 };
5882
5883 parser.encodePayload(packets, this.supportsBinary, function (data) {
5884 self.doWrite(data, callbackfn);
5885 });
5886 };
5887
5888 /**
5889 * Generates uri for connection.
5890 *
5891 * @api private
5892 */
5893
5894 Polling.prototype.uri = function () {
5895 var query = this.query || {};
5896 var schema = this.secure ? 'https' : 'http';
5897 var port = '';
5898
5899 // cache busting is forced
5900 if (false !== this.timestampRequests) {
5901 query[this.timestampParam] = yeast();
5902 }
5903
5904 if (!this.supportsBinary && !query.sid) {
5905 query.b64 = 1;
5906 }
5907
5908 query = parseqs.encode(query);
5909
5910 // avoid port if default for schema
5911 if (this.port && ('https' === schema && Number(this.port) !== 443 || 'http' === schema && Number(this.port) !== 80)) {
5912 port = ':' + this.port;
5913 }
5914
5915 // prepend ? to query
5916 if (query.length) {
5917 query = '?' + query;
5918 }
5919
5920 var ipv6 = this.hostname.indexOf(':') !== -1;
5921 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
5922 };
5923
5924 /***/
5925},
5926/* 28 */
5927/***/function (module, exports, __webpack_require__) {
5928
5929 /**
5930 * Module dependencies.
5931 */
5932
5933 var parser = __webpack_require__(29);
5934 var Emitter = __webpack_require__(37);
5935
5936 /**
5937 * Module exports.
5938 */
5939
5940 module.exports = Transport;
5941
5942 /**
5943 * Transport abstract constructor.
5944 *
5945 * @param {Object} options.
5946 * @api private
5947 */
5948
5949 function Transport(opts) {
5950 this.path = opts.path;
5951 this.hostname = opts.hostname;
5952 this.port = opts.port;
5953 this.secure = opts.secure;
5954 this.query = opts.query;
5955 this.timestampParam = opts.timestampParam;
5956 this.timestampRequests = opts.timestampRequests;
5957 this.readyState = '';
5958 this.agent = opts.agent || false;
5959 this.socket = opts.socket;
5960 this.enablesXDR = opts.enablesXDR;
5961
5962 // SSL options for Node.js client
5963 this.pfx = opts.pfx;
5964 this.key = opts.key;
5965 this.passphrase = opts.passphrase;
5966 this.cert = opts.cert;
5967 this.ca = opts.ca;
5968 this.ciphers = opts.ciphers;
5969 this.rejectUnauthorized = opts.rejectUnauthorized;
5970 this.forceNode = opts.forceNode;
5971
5972 // other options for Node.js client
5973 this.extraHeaders = opts.extraHeaders;
5974 this.localAddress = opts.localAddress;
5975 }
5976
5977 /**
5978 * Mix in `Emitter`.
5979 */
5980
5981 Emitter(Transport.prototype);
5982
5983 /**
5984 * Emits an error.
5985 *
5986 * @param {String} str
5987 * @return {Transport} for chaining
5988 * @api public
5989 */
5990
5991 Transport.prototype.onError = function (msg, desc) {
5992 var err = new Error(msg);
5993 err.type = 'TransportError';
5994 err.description = desc;
5995 this.emit('error', err);
5996 return this;
5997 };
5998
5999 /**
6000 * Opens the transport.
6001 *
6002 * @api public
6003 */
6004
6005 Transport.prototype.open = function () {
6006 if ('closed' === this.readyState || '' === this.readyState) {
6007 this.readyState = 'opening';
6008 this.doOpen();
6009 }
6010
6011 return this;
6012 };
6013
6014 /**
6015 * Closes the transport.
6016 *
6017 * @api private
6018 */
6019
6020 Transport.prototype.close = function () {
6021 if ('opening' === this.readyState || 'open' === this.readyState) {
6022 this.doClose();
6023 this.onClose();
6024 }
6025
6026 return this;
6027 };
6028
6029 /**
6030 * Sends multiple packets.
6031 *
6032 * @param {Array} packets
6033 * @api private
6034 */
6035
6036 Transport.prototype.send = function (packets) {
6037 if ('open' === this.readyState) {
6038 this.write(packets);
6039 } else {
6040 throw new Error('Transport not open');
6041 }
6042 };
6043
6044 /**
6045 * Called upon open
6046 *
6047 * @api private
6048 */
6049
6050 Transport.prototype.onOpen = function () {
6051 this.readyState = 'open';
6052 this.writable = true;
6053 this.emit('open');
6054 };
6055
6056 /**
6057 * Called with data.
6058 *
6059 * @param {String} data
6060 * @api private
6061 */
6062
6063 Transport.prototype.onData = function (data) {
6064 var packet = parser.decodePacket(data, this.socket.binaryType);
6065 this.onPacket(packet);
6066 };
6067
6068 /**
6069 * Called with a decoded packet.
6070 */
6071
6072 Transport.prototype.onPacket = function (packet) {
6073 this.emit('packet', packet);
6074 };
6075
6076 /**
6077 * Called upon close.
6078 *
6079 * @api private
6080 */
6081
6082 Transport.prototype.onClose = function () {
6083 this.readyState = 'closed';
6084 this.emit('close');
6085 };
6086
6087 /***/
6088},
6089/* 29 */
6090/***/function (module, exports, __webpack_require__) {
6091
6092 /* WEBPACK VAR INJECTION */(function (global) {
6093 /**
6094 * Module dependencies.
6095 */
6096
6097 var keys = __webpack_require__(30);
6098 var hasBinary = __webpack_require__(31);
6099 var sliceBuffer = __webpack_require__(32);
6100 var after = __webpack_require__(33);
6101 var utf8 = __webpack_require__(34);
6102
6103 var base64encoder;
6104 if (global && global.ArrayBuffer) {
6105 base64encoder = __webpack_require__(35);
6106 }
6107
6108 /**
6109 * Check if we are running an android browser. That requires us to use
6110 * ArrayBuffer with polling transports...
6111 *
6112 * http://ghinda.net/jpeg-blob-ajax-android/
6113 */
6114
6115 var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
6116
6117 /**
6118 * Check if we are running in PhantomJS.
6119 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
6120 * https://github.com/ariya/phantomjs/issues/11395
6121 * @type boolean
6122 */
6123 var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
6124
6125 /**
6126 * When true, avoids using Blobs to encode payloads.
6127 * @type boolean
6128 */
6129 var dontSendBlobs = isAndroid || isPhantomJS;
6130
6131 /**
6132 * Current protocol version.
6133 */
6134
6135 exports.protocol = 3;
6136
6137 /**
6138 * Packet types.
6139 */
6140
6141 var packets = exports.packets = {
6142 open: 0 // non-ws
6143 , close: 1 // non-ws
6144 , ping: 2,
6145 pong: 3,
6146 message: 4,
6147 upgrade: 5,
6148 noop: 6
6149 };
6150
6151 var packetslist = keys(packets);
6152
6153 /**
6154 * Premade error packet.
6155 */
6156
6157 var err = { type: 'error', data: 'parser error' };
6158
6159 /**
6160 * Create a blob api even for blob builder when vendor prefixes exist
6161 */
6162
6163 var Blob = __webpack_require__(36);
6164
6165 /**
6166 * Encodes a packet.
6167 *
6168 * <packet type id> [ <data> ]
6169 *
6170 * Example:
6171 *
6172 * 5hello world
6173 * 3
6174 * 4
6175 *
6176 * Binary is encoded in an identical principle
6177 *
6178 * @api private
6179 */
6180
6181 exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
6182 if ('function' == typeof supportsBinary) {
6183 callback = supportsBinary;
6184 supportsBinary = false;
6185 }
6186
6187 if ('function' == typeof utf8encode) {
6188 callback = utf8encode;
6189 utf8encode = null;
6190 }
6191
6192 var data = packet.data === undefined ? undefined : packet.data.buffer || packet.data;
6193
6194 if (global.ArrayBuffer && data instanceof ArrayBuffer) {
6195 return encodeArrayBuffer(packet, supportsBinary, callback);
6196 } else if (Blob && data instanceof global.Blob) {
6197 return encodeBlob(packet, supportsBinary, callback);
6198 }
6199
6200 // might be an object with { base64: true, data: dataAsBase64String }
6201 if (data && data.base64) {
6202 return encodeBase64Object(packet, callback);
6203 }
6204
6205 // Sending data as a utf-8 string
6206 var encoded = packets[packet.type];
6207
6208 // data fragment is optional
6209 if (undefined !== packet.data) {
6210 encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
6211 }
6212
6213 return callback('' + encoded);
6214 };
6215
6216 function encodeBase64Object(packet, callback) {
6217 // packet data is an object { base64: true, data: dataAsBase64String }
6218 var message = 'b' + exports.packets[packet.type] + packet.data.data;
6219 return callback(message);
6220 }
6221
6222 /**
6223 * Encode packet helpers for binary types
6224 */
6225
6226 function encodeArrayBuffer(packet, supportsBinary, callback) {
6227 if (!supportsBinary) {
6228 return exports.encodeBase64Packet(packet, callback);
6229 }
6230
6231 var data = packet.data;
6232 var contentArray = new Uint8Array(data);
6233 var resultBuffer = new Uint8Array(1 + data.byteLength);
6234
6235 resultBuffer[0] = packets[packet.type];
6236 for (var i = 0; i < contentArray.length; i++) {
6237 resultBuffer[i + 1] = contentArray[i];
6238 }
6239
6240 return callback(resultBuffer.buffer);
6241 }
6242
6243 function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
6244 if (!supportsBinary) {
6245 return exports.encodeBase64Packet(packet, callback);
6246 }
6247
6248 var fr = new FileReader();
6249 fr.onload = function () {
6250 packet.data = fr.result;
6251 exports.encodePacket(packet, supportsBinary, true, callback);
6252 };
6253 return fr.readAsArrayBuffer(packet.data);
6254 }
6255
6256 function encodeBlob(packet, supportsBinary, callback) {
6257 if (!supportsBinary) {
6258 return exports.encodeBase64Packet(packet, callback);
6259 }
6260
6261 if (dontSendBlobs) {
6262 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
6263 }
6264
6265 var length = new Uint8Array(1);
6266 length[0] = packets[packet.type];
6267 var blob = new Blob([length.buffer, packet.data]);
6268
6269 return callback(blob);
6270 }
6271
6272 /**
6273 * Encodes a packet with binary data in a base64 string
6274 *
6275 * @param {Object} packet, has `type` and `data`
6276 * @return {String} base64 encoded message
6277 */
6278
6279 exports.encodeBase64Packet = function (packet, callback) {
6280 var message = 'b' + exports.packets[packet.type];
6281 if (Blob && packet.data instanceof global.Blob) {
6282 var fr = new FileReader();
6283 fr.onload = function () {
6284 var b64 = fr.result.split(',')[1];
6285 callback(message + b64);
6286 };
6287 return fr.readAsDataURL(packet.data);
6288 }
6289
6290 var b64data;
6291 try {
6292 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
6293 } catch (e) {
6294 // iPhone Safari doesn't let you apply with typed arrays
6295 var typed = new Uint8Array(packet.data);
6296 var basic = new Array(typed.length);
6297 for (var i = 0; i < typed.length; i++) {
6298 basic[i] = typed[i];
6299 }
6300 b64data = String.fromCharCode.apply(null, basic);
6301 }
6302 message += global.btoa(b64data);
6303 return callback(message);
6304 };
6305
6306 /**
6307 * Decodes a packet. Changes format to Blob if requested.
6308 *
6309 * @return {Object} with `type` and `data` (if any)
6310 * @api private
6311 */
6312
6313 exports.decodePacket = function (data, binaryType, utf8decode) {
6314 if (data === undefined) {
6315 return err;
6316 }
6317 // String data
6318 if (typeof data == 'string') {
6319 if (data.charAt(0) == 'b') {
6320 return exports.decodeBase64Packet(data.substr(1), binaryType);
6321 }
6322
6323 if (utf8decode) {
6324 data = tryDecode(data);
6325 if (data === false) {
6326 return err;
6327 }
6328 }
6329 var type = data.charAt(0);
6330
6331 if (Number(type) != type || !packetslist[type]) {
6332 return err;
6333 }
6334
6335 if (data.length > 1) {
6336 return { type: packetslist[type], data: data.substring(1) };
6337 } else {
6338 return { type: packetslist[type] };
6339 }
6340 }
6341
6342 var asArray = new Uint8Array(data);
6343 var type = asArray[0];
6344 var rest = sliceBuffer(data, 1);
6345 if (Blob && binaryType === 'blob') {
6346 rest = new Blob([rest]);
6347 }
6348 return { type: packetslist[type], data: rest };
6349 };
6350
6351 function tryDecode(data) {
6352 try {
6353 data = utf8.decode(data);
6354 } catch (e) {
6355 return false;
6356 }
6357 return data;
6358 }
6359
6360 /**
6361 * Decodes a packet encoded in a base64 string
6362 *
6363 * @param {String} base64 encoded message
6364 * @return {Object} with `type` and `data` (if any)
6365 */
6366
6367 exports.decodeBase64Packet = function (msg, binaryType) {
6368 var type = packetslist[msg.charAt(0)];
6369 if (!base64encoder) {
6370 return { type: type, data: { base64: true, data: msg.substr(1) } };
6371 }
6372
6373 var data = base64encoder.decode(msg.substr(1));
6374
6375 if (binaryType === 'blob' && Blob) {
6376 data = new Blob([data]);
6377 }
6378
6379 return { type: type, data: data };
6380 };
6381
6382 /**
6383 * Encodes multiple messages (payload).
6384 *
6385 * <length>:data
6386 *
6387 * Example:
6388 *
6389 * 11:hello world2:hi
6390 *
6391 * If any contents are binary, they will be encoded as base64 strings. Base64
6392 * encoded strings are marked with a b before the length specifier
6393 *
6394 * @param {Array} packets
6395 * @api private
6396 */
6397
6398 exports.encodePayload = function (packets, supportsBinary, callback) {
6399 if (typeof supportsBinary == 'function') {
6400 callback = supportsBinary;
6401 supportsBinary = null;
6402 }
6403
6404 var isBinary = hasBinary(packets);
6405
6406 if (supportsBinary && isBinary) {
6407 if (Blob && !dontSendBlobs) {
6408 return exports.encodePayloadAsBlob(packets, callback);
6409 }
6410
6411 return exports.encodePayloadAsArrayBuffer(packets, callback);
6412 }
6413
6414 if (!packets.length) {
6415 return callback('0:');
6416 }
6417
6418 function setLengthHeader(message) {
6419 return message.length + ':' + message;
6420 }
6421
6422 function encodeOne(packet, doneCallback) {
6423 exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function (message) {
6424 doneCallback(null, setLengthHeader(message));
6425 });
6426 }
6427
6428 map(packets, encodeOne, function (err, results) {
6429 return callback(results.join(''));
6430 });
6431 };
6432
6433 /**
6434 * Async array map using after
6435 */
6436
6437 function map(ary, each, done) {
6438 var result = new Array(ary.length);
6439 var next = after(ary.length, done);
6440
6441 var eachWithIndex = function eachWithIndex(i, el, cb) {
6442 each(el, function (error, msg) {
6443 result[i] = msg;
6444 cb(error, result);
6445 });
6446 };
6447
6448 for (var i = 0; i < ary.length; i++) {
6449 eachWithIndex(i, ary[i], next);
6450 }
6451 }
6452
6453 /*
6454 * Decodes data when a payload is maybe expected. Possible binary contents are
6455 * decoded from their base64 representation
6456 *
6457 * @param {String} data, callback method
6458 * @api public
6459 */
6460
6461 exports.decodePayload = function (data, binaryType, callback) {
6462 if (typeof data != 'string') {
6463 return exports.decodePayloadAsBinary(data, binaryType, callback);
6464 }
6465
6466 if (typeof binaryType === 'function') {
6467 callback = binaryType;
6468 binaryType = null;
6469 }
6470
6471 var packet;
6472 if (data == '') {
6473 // parser error - ignoring payload
6474 return callback(err, 0, 1);
6475 }
6476
6477 var length = '',
6478 n,
6479 msg;
6480
6481 for (var i = 0, l = data.length; i < l; i++) {
6482 var chr = data.charAt(i);
6483
6484 if (':' != chr) {
6485 length += chr;
6486 } else {
6487 if ('' == length || length != (n = Number(length))) {
6488 // parser error - ignoring payload
6489 return callback(err, 0, 1);
6490 }
6491
6492 msg = data.substr(i + 1, n);
6493
6494 if (length != msg.length) {
6495 // parser error - ignoring payload
6496 return callback(err, 0, 1);
6497 }
6498
6499 if (msg.length) {
6500 packet = exports.decodePacket(msg, binaryType, true);
6501
6502 if (err.type == packet.type && err.data == packet.data) {
6503 // parser error in individual packet - ignoring payload
6504 return callback(err, 0, 1);
6505 }
6506
6507 var ret = callback(packet, i + n, l);
6508 if (false === ret) return;
6509 }
6510
6511 // advance cursor
6512 i += n;
6513 length = '';
6514 }
6515 }
6516
6517 if (length != '') {
6518 // parser error - ignoring payload
6519 return callback(err, 0, 1);
6520 }
6521 };
6522
6523 /**
6524 * Encodes multiple messages (payload) as binary.
6525 *
6526 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
6527 * 255><data>
6528 *
6529 * Example:
6530 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
6531 *
6532 * @param {Array} packets
6533 * @return {ArrayBuffer} encoded payload
6534 * @api private
6535 */
6536
6537 exports.encodePayloadAsArrayBuffer = function (packets, callback) {
6538 if (!packets.length) {
6539 return callback(new ArrayBuffer(0));
6540 }
6541
6542 function encodeOne(packet, doneCallback) {
6543 exports.encodePacket(packet, true, true, function (data) {
6544 return doneCallback(null, data);
6545 });
6546 }
6547
6548 map(packets, encodeOne, function (err, encodedPackets) {
6549 var totalLength = encodedPackets.reduce(function (acc, p) {
6550 var len;
6551 if (typeof p === 'string') {
6552 len = p.length;
6553 } else {
6554 len = p.byteLength;
6555 }
6556 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
6557 }, 0);
6558
6559 var resultArray = new Uint8Array(totalLength);
6560
6561 var bufferIndex = 0;
6562 encodedPackets.forEach(function (p) {
6563 var isString = typeof p === 'string';
6564 var ab = p;
6565 if (isString) {
6566 var view = new Uint8Array(p.length);
6567 for (var i = 0; i < p.length; i++) {
6568 view[i] = p.charCodeAt(i);
6569 }
6570 ab = view.buffer;
6571 }
6572
6573 if (isString) {
6574 // not true binary
6575 resultArray[bufferIndex++] = 0;
6576 } else {
6577 // true binary
6578 resultArray[bufferIndex++] = 1;
6579 }
6580
6581 var lenStr = ab.byteLength.toString();
6582 for (var i = 0; i < lenStr.length; i++) {
6583 resultArray[bufferIndex++] = parseInt(lenStr[i]);
6584 }
6585 resultArray[bufferIndex++] = 255;
6586
6587 var view = new Uint8Array(ab);
6588 for (var i = 0; i < view.length; i++) {
6589 resultArray[bufferIndex++] = view[i];
6590 }
6591 });
6592
6593 return callback(resultArray.buffer);
6594 });
6595 };
6596
6597 /**
6598 * Encode as Blob
6599 */
6600
6601 exports.encodePayloadAsBlob = function (packets, callback) {
6602 function encodeOne(packet, doneCallback) {
6603 exports.encodePacket(packet, true, true, function (encoded) {
6604 var binaryIdentifier = new Uint8Array(1);
6605 binaryIdentifier[0] = 1;
6606 if (typeof encoded === 'string') {
6607 var view = new Uint8Array(encoded.length);
6608 for (var i = 0; i < encoded.length; i++) {
6609 view[i] = encoded.charCodeAt(i);
6610 }
6611 encoded = view.buffer;
6612 binaryIdentifier[0] = 0;
6613 }
6614
6615 var len = encoded instanceof ArrayBuffer ? encoded.byteLength : encoded.size;
6616
6617 var lenStr = len.toString();
6618 var lengthAry = new Uint8Array(lenStr.length + 1);
6619 for (var i = 0; i < lenStr.length; i++) {
6620 lengthAry[i] = parseInt(lenStr[i]);
6621 }
6622 lengthAry[lenStr.length] = 255;
6623
6624 if (Blob) {
6625 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
6626 doneCallback(null, blob);
6627 }
6628 });
6629 }
6630
6631 map(packets, encodeOne, function (err, results) {
6632 return callback(new Blob(results));
6633 });
6634 };
6635
6636 /*
6637 * Decodes data when a payload is maybe expected. Strings are decoded by
6638 * interpreting each byte as a key code for entries marked to start with 0. See
6639 * description of encodePayloadAsBinary
6640 *
6641 * @param {ArrayBuffer} data, callback method
6642 * @api public
6643 */
6644
6645 exports.decodePayloadAsBinary = function (data, binaryType, callback) {
6646 if (typeof binaryType === 'function') {
6647 callback = binaryType;
6648 binaryType = null;
6649 }
6650
6651 var bufferTail = data;
6652 var buffers = [];
6653
6654 var numberTooLong = false;
6655 while (bufferTail.byteLength > 0) {
6656 var tailArray = new Uint8Array(bufferTail);
6657 var isString = tailArray[0] === 0;
6658 var msgLength = '';
6659
6660 for (var i = 1;; i++) {
6661 if (tailArray[i] == 255) break;
6662
6663 if (msgLength.length > 310) {
6664 numberTooLong = true;
6665 break;
6666 }
6667
6668 msgLength += tailArray[i];
6669 }
6670
6671 if (numberTooLong) return callback(err, 0, 1);
6672
6673 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
6674 msgLength = parseInt(msgLength);
6675
6676 var msg = sliceBuffer(bufferTail, 0, msgLength);
6677 if (isString) {
6678 try {
6679 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
6680 } catch (e) {
6681 // iPhone Safari doesn't let you apply to typed arrays
6682 var typed = new Uint8Array(msg);
6683 msg = '';
6684 for (var i = 0; i < typed.length; i++) {
6685 msg += String.fromCharCode(typed[i]);
6686 }
6687 }
6688 }
6689
6690 buffers.push(msg);
6691 bufferTail = sliceBuffer(bufferTail, msgLength);
6692 }
6693
6694 var total = buffers.length;
6695 buffers.forEach(function (buffer, i) {
6696 callback(exports.decodePacket(buffer, binaryType, true), i, total);
6697 });
6698 };
6699
6700 /* WEBPACK VAR INJECTION */
6701 }).call(exports, function () {
6702 return this;
6703 }());
6704
6705 /***/
6706},
6707/* 30 */
6708/***/function (module, exports) {
6709
6710 /**
6711 * Gets the keys for an object.
6712 *
6713 * @return {Array} keys
6714 * @api private
6715 */
6716
6717 module.exports = Object.keys || function keys(obj) {
6718 var arr = [];
6719 var has = Object.prototype.hasOwnProperty;
6720
6721 for (var i in obj) {
6722 if (has.call(obj, i)) {
6723 arr.push(i);
6724 }
6725 }
6726 return arr;
6727 };
6728
6729 /***/
6730},
6731/* 31 */
6732/***/function (module, exports, __webpack_require__) {
6733
6734 /* WEBPACK VAR INJECTION */(function (global) {
6735 /*
6736 * Module requirements.
6737 */
6738
6739 var isArray = __webpack_require__(17);
6740
6741 /**
6742 * Module exports.
6743 */
6744
6745 module.exports = hasBinary;
6746
6747 /**
6748 * Checks for binary data.
6749 *
6750 * Right now only Buffer and ArrayBuffer are supported..
6751 *
6752 * @param {Object} anything
6753 * @api public
6754 */
6755
6756 function hasBinary(data) {
6757
6758 function _hasBinary(obj) {
6759 if (!obj) return false;
6760
6761 if (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj) || global.ArrayBuffer && obj instanceof ArrayBuffer || global.Blob && obj instanceof Blob || global.File && obj instanceof File) {
6762 return true;
6763 }
6764
6765 if (isArray(obj)) {
6766 for (var i = 0; i < obj.length; i++) {
6767 if (_hasBinary(obj[i])) {
6768 return true;
6769 }
6770 }
6771 } else if (obj && 'object' == (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))) {
6772 // see: https://github.com/Automattic/has-binary/pull/4
6773 if (obj.toJSON && 'function' == typeof obj.toJSON) {
6774 obj = obj.toJSON();
6775 }
6776
6777 for (var key in obj) {
6778 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
6779 return true;
6780 }
6781 }
6782 }
6783
6784 return false;
6785 }
6786
6787 return _hasBinary(data);
6788 }
6789
6790 /* WEBPACK VAR INJECTION */
6791 }).call(exports, function () {
6792 return this;
6793 }());
6794
6795 /***/
6796},
6797/* 32 */
6798/***/function (module, exports) {
6799
6800 /**
6801 * An abstraction for slicing an arraybuffer even when
6802 * ArrayBuffer.prototype.slice is not supported
6803 *
6804 * @api public
6805 */
6806
6807 module.exports = function (arraybuffer, start, end) {
6808 var bytes = arraybuffer.byteLength;
6809 start = start || 0;
6810 end = end || bytes;
6811
6812 if (arraybuffer.slice) {
6813 return arraybuffer.slice(start, end);
6814 }
6815
6816 if (start < 0) {
6817 start += bytes;
6818 }
6819 if (end < 0) {
6820 end += bytes;
6821 }
6822 if (end > bytes) {
6823 end = bytes;
6824 }
6825
6826 if (start >= bytes || start >= end || bytes === 0) {
6827 return new ArrayBuffer(0);
6828 }
6829
6830 var abv = new Uint8Array(arraybuffer);
6831 var result = new Uint8Array(end - start);
6832 for (var i = start, ii = 0; i < end; i++, ii++) {
6833 result[ii] = abv[i];
6834 }
6835 return result.buffer;
6836 };
6837
6838 /***/
6839},
6840/* 33 */
6841/***/function (module, exports) {
6842
6843 module.exports = after;
6844
6845 function after(count, callback, err_cb) {
6846 var bail = false;
6847 err_cb = err_cb || noop;
6848 proxy.count = count;
6849
6850 return count === 0 ? callback() : proxy;
6851
6852 function proxy(err, result) {
6853 if (proxy.count <= 0) {
6854 throw new Error('after called too many times');
6855 }
6856 --proxy.count;
6857
6858 // after first error, rest are passed to err_cb
6859 if (err) {
6860 bail = true;
6861 callback(err);
6862 // future error callbacks will go to error handler
6863 callback = err_cb;
6864 } else if (proxy.count === 0 && !bail) {
6865 callback(null, result);
6866 }
6867 }
6868 }
6869
6870 function noop() {}
6871
6872 /***/
6873},
6874/* 34 */
6875/***/function (module, exports, __webpack_require__) {
6876
6877 var __WEBPACK_AMD_DEFINE_RESULT__; /* WEBPACK VAR INJECTION */(function (module, global) {
6878 /*! https://mths.be/wtf8 v1.0.0 by @mathias */
6879 ;(function (root) {
6880
6881 // Detect free variables `exports`
6882 var freeExports = (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) == 'object' && exports;
6883
6884 // Detect free variable `module`
6885 var freeModule = (typeof module === 'undefined' ? 'undefined' : _typeof(module)) == 'object' && module && module.exports == freeExports && module;
6886
6887 // Detect free variable `global`, from Node.js or Browserified code,
6888 // and use it as `root`
6889 var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) == 'object' && global;
6890 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
6891 root = freeGlobal;
6892 }
6893
6894 /*--------------------------------------------------------------------------*/
6895
6896 var stringFromCharCode = String.fromCharCode;
6897
6898 // Taken from https://mths.be/punycode
6899 function ucs2decode(string) {
6900 var output = [];
6901 var counter = 0;
6902 var length = string.length;
6903 var value;
6904 var extra;
6905 while (counter < length) {
6906 value = string.charCodeAt(counter++);
6907 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
6908 // high surrogate, and there is a next character
6909 extra = string.charCodeAt(counter++);
6910 if ((extra & 0xFC00) == 0xDC00) {
6911 // low surrogate
6912 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
6913 } else {
6914 // unmatched surrogate; only append this code unit, in case the next
6915 // code unit is the high surrogate of a surrogate pair
6916 output.push(value);
6917 counter--;
6918 }
6919 } else {
6920 output.push(value);
6921 }
6922 }
6923 return output;
6924 }
6925
6926 // Taken from https://mths.be/punycode
6927 function ucs2encode(array) {
6928 var length = array.length;
6929 var index = -1;
6930 var value;
6931 var output = '';
6932 while (++index < length) {
6933 value = array[index];
6934 if (value > 0xFFFF) {
6935 value -= 0x10000;
6936 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
6937 value = 0xDC00 | value & 0x3FF;
6938 }
6939 output += stringFromCharCode(value);
6940 }
6941 return output;
6942 }
6943
6944 /*--------------------------------------------------------------------------*/
6945
6946 function createByte(codePoint, shift) {
6947 return stringFromCharCode(codePoint >> shift & 0x3F | 0x80);
6948 }
6949
6950 function encodeCodePoint(codePoint) {
6951 if ((codePoint & 0xFFFFFF80) == 0) {
6952 // 1-byte sequence
6953 return stringFromCharCode(codePoint);
6954 }
6955 var symbol = '';
6956 if ((codePoint & 0xFFFFF800) == 0) {
6957 // 2-byte sequence
6958 symbol = stringFromCharCode(codePoint >> 6 & 0x1F | 0xC0);
6959 } else if ((codePoint & 0xFFFF0000) == 0) {
6960 // 3-byte sequence
6961 symbol = stringFromCharCode(codePoint >> 12 & 0x0F | 0xE0);
6962 symbol += createByte(codePoint, 6);
6963 } else if ((codePoint & 0xFFE00000) == 0) {
6964 // 4-byte sequence
6965 symbol = stringFromCharCode(codePoint >> 18 & 0x07 | 0xF0);
6966 symbol += createByte(codePoint, 12);
6967 symbol += createByte(codePoint, 6);
6968 }
6969 symbol += stringFromCharCode(codePoint & 0x3F | 0x80);
6970 return symbol;
6971 }
6972
6973 function wtf8encode(string) {
6974 var codePoints = ucs2decode(string);
6975 var length = codePoints.length;
6976 var index = -1;
6977 var codePoint;
6978 var byteString = '';
6979 while (++index < length) {
6980 codePoint = codePoints[index];
6981 byteString += encodeCodePoint(codePoint);
6982 }
6983 return byteString;
6984 }
6985
6986 /*--------------------------------------------------------------------------*/
6987
6988 function readContinuationByte() {
6989 if (byteIndex >= byteCount) {
6990 throw Error('Invalid byte index');
6991 }
6992
6993 var continuationByte = byteArray[byteIndex] & 0xFF;
6994 byteIndex++;
6995
6996 if ((continuationByte & 0xC0) == 0x80) {
6997 return continuationByte & 0x3F;
6998 }
6999
7000 // If we end up here, it’s not a continuation byte.
7001 throw Error('Invalid continuation byte');
7002 }
7003
7004 function decodeSymbol() {
7005 var byte1;
7006 var byte2;
7007 var byte3;
7008 var byte4;
7009 var codePoint;
7010
7011 if (byteIndex > byteCount) {
7012 throw Error('Invalid byte index');
7013 }
7014
7015 if (byteIndex == byteCount) {
7016 return false;
7017 }
7018
7019 // Read the first byte.
7020 byte1 = byteArray[byteIndex] & 0xFF;
7021 byteIndex++;
7022
7023 // 1-byte sequence (no continuation bytes)
7024 if ((byte1 & 0x80) == 0) {
7025 return byte1;
7026 }
7027
7028 // 2-byte sequence
7029 if ((byte1 & 0xE0) == 0xC0) {
7030 var byte2 = readContinuationByte();
7031 codePoint = (byte1 & 0x1F) << 6 | byte2;
7032 if (codePoint >= 0x80) {
7033 return codePoint;
7034 } else {
7035 throw Error('Invalid continuation byte');
7036 }
7037 }
7038
7039 // 3-byte sequence (may include unpaired surrogates)
7040 if ((byte1 & 0xF0) == 0xE0) {
7041 byte2 = readContinuationByte();
7042 byte3 = readContinuationByte();
7043 codePoint = (byte1 & 0x0F) << 12 | byte2 << 6 | byte3;
7044 if (codePoint >= 0x0800) {
7045 return codePoint;
7046 } else {
7047 throw Error('Invalid continuation byte');
7048 }
7049 }
7050
7051 // 4-byte sequence
7052 if ((byte1 & 0xF8) == 0xF0) {
7053 byte2 = readContinuationByte();
7054 byte3 = readContinuationByte();
7055 byte4 = readContinuationByte();
7056 codePoint = (byte1 & 0x0F) << 0x12 | byte2 << 0x0C | byte3 << 0x06 | byte4;
7057 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
7058 return codePoint;
7059 }
7060 }
7061
7062 throw Error('Invalid WTF-8 detected');
7063 }
7064
7065 var byteArray;
7066 var byteCount;
7067 var byteIndex;
7068 function wtf8decode(byteString) {
7069 byteArray = ucs2decode(byteString);
7070 byteCount = byteArray.length;
7071 byteIndex = 0;
7072 var codePoints = [];
7073 var tmp;
7074 while ((tmp = decodeSymbol()) !== false) {
7075 codePoints.push(tmp);
7076 }
7077 return ucs2encode(codePoints);
7078 }
7079
7080 /*--------------------------------------------------------------------------*/
7081
7082 var wtf8 = {
7083 'version': '1.0.0',
7084 'encode': wtf8encode,
7085 'decode': wtf8decode
7086 };
7087
7088 // Some AMD build optimizers, like r.js, check for specific condition patterns
7089 // like the following:
7090 if (true) {
7091 !(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
7092 return wtf8;
7093 }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
7094 } else if (freeExports && !freeExports.nodeType) {
7095 if (freeModule) {
7096 // in Node.js or RingoJS v0.8.0+
7097 freeModule.exports = wtf8;
7098 } else {
7099 // in Narwhal or RingoJS v0.7.0-
7100 var object = {};
7101 var hasOwnProperty = object.hasOwnProperty;
7102 for (var key in wtf8) {
7103 hasOwnProperty.call(wtf8, key) && (freeExports[key] = wtf8[key]);
7104 }
7105 }
7106 } else {
7107 // in Rhino or a web browser
7108 root.wtf8 = wtf8;
7109 }
7110 })(this);
7111
7112 /* WEBPACK VAR INJECTION */
7113 }).call(exports, __webpack_require__(13)(module), function () {
7114 return this;
7115 }());
7116
7117 /***/
7118},
7119/* 35 */
7120/***/function (module, exports) {
7121
7122 /*
7123 * base64-arraybuffer
7124 * https://github.com/niklasvh/base64-arraybuffer
7125 *
7126 * Copyright (c) 2012 Niklas von Hertzen
7127 * Licensed under the MIT license.
7128 */
7129 (function () {
7130 "use strict";
7131
7132 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7133
7134 // Use a lookup table to find the index.
7135 var lookup = new Uint8Array(256);
7136 for (var i = 0; i < chars.length; i++) {
7137 lookup[chars.charCodeAt(i)] = i;
7138 }
7139
7140 exports.encode = function (arraybuffer) {
7141 var bytes = new Uint8Array(arraybuffer),
7142 i,
7143 len = bytes.length,
7144 base64 = "";
7145
7146 for (i = 0; i < len; i += 3) {
7147 base64 += chars[bytes[i] >> 2];
7148 base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
7149 base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
7150 base64 += chars[bytes[i + 2] & 63];
7151 }
7152
7153 if (len % 3 === 2) {
7154 base64 = base64.substring(0, base64.length - 1) + "=";
7155 } else if (len % 3 === 1) {
7156 base64 = base64.substring(0, base64.length - 2) + "==";
7157 }
7158
7159 return base64;
7160 };
7161
7162 exports.decode = function (base64) {
7163 var bufferLength = base64.length * 0.75,
7164 len = base64.length,
7165 i,
7166 p = 0,
7167 encoded1,
7168 encoded2,
7169 encoded3,
7170 encoded4;
7171
7172 if (base64[base64.length - 1] === "=") {
7173 bufferLength--;
7174 if (base64[base64.length - 2] === "=") {
7175 bufferLength--;
7176 }
7177 }
7178
7179 var arraybuffer = new ArrayBuffer(bufferLength),
7180 bytes = new Uint8Array(arraybuffer);
7181
7182 for (i = 0; i < len; i += 4) {
7183 encoded1 = lookup[base64.charCodeAt(i)];
7184 encoded2 = lookup[base64.charCodeAt(i + 1)];
7185 encoded3 = lookup[base64.charCodeAt(i + 2)];
7186 encoded4 = lookup[base64.charCodeAt(i + 3)];
7187
7188 bytes[p++] = encoded1 << 2 | encoded2 >> 4;
7189 bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
7190 bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
7191 }
7192
7193 return arraybuffer;
7194 };
7195 })();
7196
7197 /***/
7198},
7199/* 36 */
7200/***/function (module, exports) {
7201
7202 /* WEBPACK VAR INJECTION */(function (global) {
7203 /**
7204 * Create a blob builder even when vendor prefixes exist
7205 */
7206
7207 var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder;
7208
7209 /**
7210 * Check if Blob constructor is supported
7211 */
7212
7213 var blobSupported = function () {
7214 try {
7215 var a = new Blob(['hi']);
7216 return a.size === 2;
7217 } catch (e) {
7218 return false;
7219 }
7220 }();
7221
7222 /**
7223 * Check if Blob constructor supports ArrayBufferViews
7224 * Fails in Safari 6, so we need to map to ArrayBuffers there.
7225 */
7226
7227 var blobSupportsArrayBufferView = blobSupported && function () {
7228 try {
7229 var b = new Blob([new Uint8Array([1, 2])]);
7230 return b.size === 2;
7231 } catch (e) {
7232 return false;
7233 }
7234 }();
7235
7236 /**
7237 * Check if BlobBuilder is supported
7238 */
7239
7240 var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob;
7241
7242 /**
7243 * Helper function that maps ArrayBufferViews to ArrayBuffers
7244 * Used by BlobBuilder constructor and old browsers that didn't
7245 * support it in the Blob constructor.
7246 */
7247
7248 function mapArrayBufferViews(ary) {
7249 for (var i = 0; i < ary.length; i++) {
7250 var chunk = ary[i];
7251 if (chunk.buffer instanceof ArrayBuffer) {
7252 var buf = chunk.buffer;
7253
7254 // if this is a subarray, make a copy so we only
7255 // include the subarray region from the underlying buffer
7256 if (chunk.byteLength !== buf.byteLength) {
7257 var copy = new Uint8Array(chunk.byteLength);
7258 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
7259 buf = copy.buffer;
7260 }
7261
7262 ary[i] = buf;
7263 }
7264 }
7265 }
7266
7267 function BlobBuilderConstructor(ary, options) {
7268 options = options || {};
7269
7270 var bb = new BlobBuilder();
7271 mapArrayBufferViews(ary);
7272
7273 for (var i = 0; i < ary.length; i++) {
7274 bb.append(ary[i]);
7275 }
7276
7277 return options.type ? bb.getBlob(options.type) : bb.getBlob();
7278 };
7279
7280 function BlobConstructor(ary, options) {
7281 mapArrayBufferViews(ary);
7282 return new Blob(ary, options || {});
7283 };
7284
7285 module.exports = function () {
7286 if (blobSupported) {
7287 return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
7288 } else if (blobBuilderSupported) {
7289 return BlobBuilderConstructor;
7290 } else {
7291 return undefined;
7292 }
7293 }();
7294
7295 /* WEBPACK VAR INJECTION */
7296 }).call(exports, function () {
7297 return this;
7298 }());
7299
7300 /***/
7301},
7302/* 37 */
7303/***/function (module, exports, __webpack_require__) {
7304
7305 /**
7306 * Expose `Emitter`.
7307 */
7308
7309 if (true) {
7310 module.exports = Emitter;
7311 }
7312
7313 /**
7314 * Initialize a new `Emitter`.
7315 *
7316 * @api public
7317 */
7318
7319 function Emitter(obj) {
7320 if (obj) return mixin(obj);
7321 };
7322
7323 /**
7324 * Mixin the emitter properties.
7325 *
7326 * @param {Object} obj
7327 * @return {Object}
7328 * @api private
7329 */
7330
7331 function mixin(obj) {
7332 for (var key in Emitter.prototype) {
7333 obj[key] = Emitter.prototype[key];
7334 }
7335 return obj;
7336 }
7337
7338 /**
7339 * Listen on the given `event` with `fn`.
7340 *
7341 * @param {String} event
7342 * @param {Function} fn
7343 * @return {Emitter}
7344 * @api public
7345 */
7346
7347 Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
7348 this._callbacks = this._callbacks || {};
7349 (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
7350 return this;
7351 };
7352
7353 /**
7354 * Adds an `event` listener that will be invoked a single
7355 * time then automatically removed.
7356 *
7357 * @param {String} event
7358 * @param {Function} fn
7359 * @return {Emitter}
7360 * @api public
7361 */
7362
7363 Emitter.prototype.once = function (event, fn) {
7364 function on() {
7365 this.off(event, on);
7366 fn.apply(this, arguments);
7367 }
7368
7369 on.fn = fn;
7370 this.on(event, on);
7371 return this;
7372 };
7373
7374 /**
7375 * Remove the given callback for `event` or all
7376 * registered callbacks.
7377 *
7378 * @param {String} event
7379 * @param {Function} fn
7380 * @return {Emitter}
7381 * @api public
7382 */
7383
7384 Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
7385 this._callbacks = this._callbacks || {};
7386
7387 // all
7388 if (0 == arguments.length) {
7389 this._callbacks = {};
7390 return this;
7391 }
7392
7393 // specific event
7394 var callbacks = this._callbacks['$' + event];
7395 if (!callbacks) return this;
7396
7397 // remove all handlers
7398 if (1 == arguments.length) {
7399 delete this._callbacks['$' + event];
7400 return this;
7401 }
7402
7403 // remove specific handler
7404 var cb;
7405 for (var i = 0; i < callbacks.length; i++) {
7406 cb = callbacks[i];
7407 if (cb === fn || cb.fn === fn) {
7408 callbacks.splice(i, 1);
7409 break;
7410 }
7411 }
7412 return this;
7413 };
7414
7415 /**
7416 * Emit `event` with the given args.
7417 *
7418 * @param {String} event
7419 * @param {Mixed} ...
7420 * @return {Emitter}
7421 */
7422
7423 Emitter.prototype.emit = function (event) {
7424 this._callbacks = this._callbacks || {};
7425 var args = [].slice.call(arguments, 1),
7426 callbacks = this._callbacks['$' + event];
7427
7428 if (callbacks) {
7429 callbacks = callbacks.slice(0);
7430 for (var i = 0, len = callbacks.length; i < len; ++i) {
7431 callbacks[i].apply(this, args);
7432 }
7433 }
7434
7435 return this;
7436 };
7437
7438 /**
7439 * Return array of callbacks for `event`.
7440 *
7441 * @param {String} event
7442 * @return {Array}
7443 * @api public
7444 */
7445
7446 Emitter.prototype.listeners = function (event) {
7447 this._callbacks = this._callbacks || {};
7448 return this._callbacks['$' + event] || [];
7449 };
7450
7451 /**
7452 * Check if this emitter has `event` handlers.
7453 *
7454 * @param {String} event
7455 * @return {Boolean}
7456 * @api public
7457 */
7458
7459 Emitter.prototype.hasListeners = function (event) {
7460 return !!this.listeners(event).length;
7461 };
7462
7463 /***/
7464},
7465/* 38 */
7466/***/function (module, exports) {
7467
7468 /**
7469 * Compiles a querystring
7470 * Returns string representation of the object
7471 *
7472 * @param {Object}
7473 * @api private
7474 */
7475
7476 exports.encode = function (obj) {
7477 var str = '';
7478
7479 for (var i in obj) {
7480 if (obj.hasOwnProperty(i)) {
7481 if (str.length) str += '&';
7482 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
7483 }
7484 }
7485
7486 return str;
7487 };
7488
7489 /**
7490 * Parses a simple querystring into an object
7491 *
7492 * @param {String} qs
7493 * @api private
7494 */
7495
7496 exports.decode = function (qs) {
7497 var qry = {};
7498 var pairs = qs.split('&');
7499 for (var i = 0, l = pairs.length; i < l; i++) {
7500 var pair = pairs[i].split('=');
7501 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
7502 }
7503 return qry;
7504 };
7505
7506 /***/
7507},
7508/* 39 */
7509/***/function (module, exports) {
7510
7511 module.exports = function (a, b) {
7512 var fn = function fn() {};
7513 fn.prototype = b.prototype;
7514 a.prototype = new fn();
7515 a.prototype.constructor = a;
7516 };
7517
7518 /***/
7519},
7520/* 40 */
7521/***/function (module, exports) {
7522
7523 'use strict';
7524
7525 var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
7526 length = 64,
7527 map = {},
7528 seed = 0,
7529 i = 0,
7530 prev;
7531
7532 /**
7533 * Return a string representing the specified number.
7534 *
7535 * @param {Number} num The number to convert.
7536 * @returns {String} The string representation of the number.
7537 * @api public
7538 */
7539 function encode(num) {
7540 var encoded = '';
7541
7542 do {
7543 encoded = alphabet[num % length] + encoded;
7544 num = Math.floor(num / length);
7545 } while (num > 0);
7546
7547 return encoded;
7548 }
7549
7550 /**
7551 * Return the integer value specified by the given string.
7552 *
7553 * @param {String} str The string to convert.
7554 * @returns {Number} The integer value represented by the string.
7555 * @api public
7556 */
7557 function decode(str) {
7558 var decoded = 0;
7559
7560 for (i = 0; i < str.length; i++) {
7561 decoded = decoded * length + map[str.charAt(i)];
7562 }
7563
7564 return decoded;
7565 }
7566
7567 /**
7568 * Yeast: A tiny growing id generator.
7569 *
7570 * @returns {String} A unique id.
7571 * @api public
7572 */
7573 function yeast() {
7574 var now = encode(+new Date());
7575
7576 if (now !== prev) return seed = 0, prev = now;
7577 return now + '.' + encode(seed++);
7578 }
7579
7580 //
7581 // Map each character to its index.
7582 //
7583 for (; i < length; i++) {
7584 map[alphabet[i]] = i;
7585 } //
7586 // Expose the `yeast`, `encode` and `decode` functions.
7587 //
7588 yeast.encode = encode;
7589 yeast.decode = decode;
7590 module.exports = yeast;
7591
7592 /***/
7593},
7594/* 41 */
7595/***/function (module, exports, __webpack_require__) {
7596
7597 /* WEBPACK VAR INJECTION */(function (process) {
7598 /**
7599 * This is the web browser implementation of `debug()`.
7600 *
7601 * Expose `debug()` as the module.
7602 */
7603
7604 exports = module.exports = __webpack_require__(42);
7605 exports.log = log;
7606 exports.formatArgs = formatArgs;
7607 exports.save = save;
7608 exports.load = load;
7609 exports.useColors = useColors;
7610 exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
7611
7612 /**
7613 * Colors.
7614 */
7615
7616 exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson'];
7617
7618 /**
7619 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
7620 * and the Firebug extension (any Firefox version) are known
7621 * to support "%c" CSS customizations.
7622 *
7623 * TODO: add a `localStorage` variable to explicitly enable/disable colors
7624 */
7625
7626 function useColors() {
7627 // is webkit? http://stackoverflow.com/a/16459606/376773
7628 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
7629 return typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style ||
7630 // is firebug? http://stackoverflow.com/a/398120/376773
7631 window.console && (console.firebug || console.exception && console.table) ||
7632 // is firefox >= v31?
7633 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
7634 navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31;
7635 }
7636
7637 /**
7638 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
7639 */
7640
7641 exports.formatters.j = function (v) {
7642 try {
7643 return JSON.stringify(v);
7644 } catch (err) {
7645 return '[UnexpectedJSONParseError]: ' + err.message;
7646 }
7647 };
7648
7649 /**
7650 * Colorize log arguments if enabled.
7651 *
7652 * @api public
7653 */
7654
7655 function formatArgs() {
7656 var args = arguments;
7657 var useColors = this.useColors;
7658
7659 args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
7660
7661 if (!useColors) return args;
7662
7663 var c = 'color: ' + this.color;
7664 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
7665
7666 // the final "%c" is somewhat tricky, because there could be other
7667 // arguments passed either before or after the %c, so we need to
7668 // figure out the correct index to insert the CSS into
7669 var index = 0;
7670 var lastC = 0;
7671 args[0].replace(/%[a-z%]/g, function (match) {
7672 if ('%%' === match) return;
7673 index++;
7674 if ('%c' === match) {
7675 // we only are interested in the *last* %c
7676 // (the user may have provided their own)
7677 lastC = index;
7678 }
7679 });
7680
7681 args.splice(lastC, 0, c);
7682 return args;
7683 }
7684
7685 /**
7686 * Invokes `console.log()` when available.
7687 * No-op when `console.log` is not a "function".
7688 *
7689 * @api public
7690 */
7691
7692 function log() {
7693 // this hackery is required for IE8/9, where
7694 // the `console.log` function doesn't have 'apply'
7695 return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
7696 }
7697
7698 /**
7699 * Save `namespaces`.
7700 *
7701 * @param {String} namespaces
7702 * @api private
7703 */
7704
7705 function save(namespaces) {
7706 try {
7707 if (null == namespaces) {
7708 exports.storage.removeItem('debug');
7709 } else {
7710 exports.storage.debug = namespaces;
7711 }
7712 } catch (e) {}
7713 }
7714
7715 /**
7716 * Load `namespaces`.
7717 *
7718 * @return {String} returns the previously persisted debug modes
7719 * @api private
7720 */
7721
7722 function load() {
7723 var r;
7724 try {
7725 return exports.storage.debug;
7726 } catch (e) {}
7727
7728 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
7729 if (typeof process !== 'undefined' && 'env' in process) {
7730 return process.env.DEBUG;
7731 }
7732 }
7733
7734 /**
7735 * Enable namespaces listed in `localStorage.debug` initially.
7736 */
7737
7738 exports.enable(load());
7739
7740 /**
7741 * Localstorage attempts to return the localstorage.
7742 *
7743 * This is necessary because safari throws
7744 * when a user disables cookies/localstorage
7745 * and you attempt to access it.
7746 *
7747 * @return {LocalStorage}
7748 * @api private
7749 */
7750
7751 function localstorage() {
7752 try {
7753 return window.localStorage;
7754 } catch (e) {}
7755 }
7756
7757 /* WEBPACK VAR INJECTION */
7758 }).call(exports, __webpack_require__(5));
7759
7760 /***/
7761},
7762/* 42 */
7763/***/function (module, exports, __webpack_require__) {
7764
7765 /**
7766 * This is the common logic for both the Node.js and web browser
7767 * implementations of `debug()`.
7768 *
7769 * Expose `debug()` as the module.
7770 */
7771
7772 exports = module.exports = debug.debug = debug;
7773 exports.coerce = coerce;
7774 exports.disable = disable;
7775 exports.enable = enable;
7776 exports.enabled = enabled;
7777 exports.humanize = __webpack_require__(43);
7778
7779 /**
7780 * The currently active debug mode names, and names to skip.
7781 */
7782
7783 exports.names = [];
7784 exports.skips = [];
7785
7786 /**
7787 * Map of special "%n" handling functions, for the debug "format" argument.
7788 *
7789 * Valid key names are a single, lowercased letter, i.e. "n".
7790 */
7791
7792 exports.formatters = {};
7793
7794 /**
7795 * Previously assigned color.
7796 */
7797
7798 var prevColor = 0;
7799
7800 /**
7801 * Previous log timestamp.
7802 */
7803
7804 var prevTime;
7805
7806 /**
7807 * Select a color.
7808 *
7809 * @return {Number}
7810 * @api private
7811 */
7812
7813 function selectColor() {
7814 return exports.colors[prevColor++ % exports.colors.length];
7815 }
7816
7817 /**
7818 * Create a debugger with the given `namespace`.
7819 *
7820 * @param {String} namespace
7821 * @return {Function}
7822 * @api public
7823 */
7824
7825 function debug(namespace) {
7826
7827 // define the `disabled` version
7828 function disabled() {}
7829 disabled.enabled = false;
7830
7831 // define the `enabled` version
7832 function enabled() {
7833
7834 var self = enabled;
7835
7836 // set `diff` timestamp
7837 var curr = +new Date();
7838 var ms = curr - (prevTime || curr);
7839 self.diff = ms;
7840 self.prev = prevTime;
7841 self.curr = curr;
7842 prevTime = curr;
7843
7844 // add the `color` if not set
7845 if (null == self.useColors) self.useColors = exports.useColors();
7846 if (null == self.color && self.useColors) self.color = selectColor();
7847
7848 var args = new Array(arguments.length);
7849 for (var i = 0; i < args.length; i++) {
7850 args[i] = arguments[i];
7851 }
7852
7853 args[0] = exports.coerce(args[0]);
7854
7855 if ('string' !== typeof args[0]) {
7856 // anything else let's inspect with %o
7857 args = ['%o'].concat(args);
7858 }
7859
7860 // apply any `formatters` transformations
7861 var index = 0;
7862 args[0] = args[0].replace(/%([a-z%])/g, function (match, format) {
7863 // if we encounter an escaped % then don't increase the array index
7864 if (match === '%%') return match;
7865 index++;
7866 var formatter = exports.formatters[format];
7867 if ('function' === typeof formatter) {
7868 var val = args[index];
7869 match = formatter.call(self, val);
7870
7871 // now we need to remove `args[index]` since it's inlined in the `format`
7872 args.splice(index, 1);
7873 index--;
7874 }
7875 return match;
7876 });
7877
7878 // apply env-specific formatting
7879 args = exports.formatArgs.apply(self, args);
7880
7881 var logFn = enabled.log || exports.log || console.log.bind(console);
7882 logFn.apply(self, args);
7883 }
7884 enabled.enabled = true;
7885
7886 var fn = exports.enabled(namespace) ? enabled : disabled;
7887
7888 fn.namespace = namespace;
7889
7890 return fn;
7891 }
7892
7893 /**
7894 * Enables a debug mode by namespaces. This can include modes
7895 * separated by a colon and wildcards.
7896 *
7897 * @param {String} namespaces
7898 * @api public
7899 */
7900
7901 function enable(namespaces) {
7902 exports.save(namespaces);
7903
7904 var split = (namespaces || '').split(/[\s,]+/);
7905 var len = split.length;
7906
7907 for (var i = 0; i < len; i++) {
7908 if (!split[i]) continue; // ignore empty strings
7909 namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
7910 if (namespaces[0] === '-') {
7911 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
7912 } else {
7913 exports.names.push(new RegExp('^' + namespaces + '$'));
7914 }
7915 }
7916 }
7917
7918 /**
7919 * Disable debug output.
7920 *
7921 * @api public
7922 */
7923
7924 function disable() {
7925 exports.enable('');
7926 }
7927
7928 /**
7929 * Returns true if the given mode name is enabled, false otherwise.
7930 *
7931 * @param {String} name
7932 * @return {Boolean}
7933 * @api public
7934 */
7935
7936 function enabled(name) {
7937 var i, len;
7938 for (i = 0, len = exports.skips.length; i < len; i++) {
7939 if (exports.skips[i].test(name)) {
7940 return false;
7941 }
7942 }
7943 for (i = 0, len = exports.names.length; i < len; i++) {
7944 if (exports.names[i].test(name)) {
7945 return true;
7946 }
7947 }
7948 return false;
7949 }
7950
7951 /**
7952 * Coerce `val`.
7953 *
7954 * @param {Mixed} val
7955 * @return {Mixed}
7956 * @api private
7957 */
7958
7959 function coerce(val) {
7960 if (val instanceof Error) return val.stack || val.message;
7961 return val;
7962 }
7963
7964 /***/
7965},
7966/* 43 */
7967/***/function (module, exports) {
7968
7969 /**
7970 * Helpers.
7971 */
7972
7973 var s = 1000;
7974 var m = s * 60;
7975 var h = m * 60;
7976 var d = h * 24;
7977 var y = d * 365.25;
7978
7979 /**
7980 * Parse or format the given `val`.
7981 *
7982 * Options:
7983 *
7984 * - `long` verbose formatting [false]
7985 *
7986 * @param {String|Number} val
7987 * @param {Object} options
7988 * @throws {Error} throw an error if val is not a non-empty string or a number
7989 * @return {String|Number}
7990 * @api public
7991 */
7992
7993 module.exports = function (val, options) {
7994 options = options || {};
7995 var type = typeof val === 'undefined' ? 'undefined' : _typeof(val);
7996 if (type === 'string' && val.length > 0) {
7997 return parse(val);
7998 } else if (type === 'number' && isNaN(val) === false) {
7999 return options.long ? fmtLong(val) : fmtShort(val);
8000 }
8001 throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
8002 };
8003
8004 /**
8005 * Parse the given `str` and return milliseconds.
8006 *
8007 * @param {String} str
8008 * @return {Number}
8009 * @api private
8010 */
8011
8012 function parse(str) {
8013 str = String(str);
8014 if (str.length > 10000) {
8015 return;
8016 }
8017 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
8018 if (!match) {
8019 return;
8020 }
8021 var n = parseFloat(match[1]);
8022 var type = (match[2] || 'ms').toLowerCase();
8023 switch (type) {
8024 case 'years':
8025 case 'year':
8026 case 'yrs':
8027 case 'yr':
8028 case 'y':
8029 return n * y;
8030 case 'days':
8031 case 'day':
8032 case 'd':
8033 return n * d;
8034 case 'hours':
8035 case 'hour':
8036 case 'hrs':
8037 case 'hr':
8038 case 'h':
8039 return n * h;
8040 case 'minutes':
8041 case 'minute':
8042 case 'mins':
8043 case 'min':
8044 case 'm':
8045 return n * m;
8046 case 'seconds':
8047 case 'second':
8048 case 'secs':
8049 case 'sec':
8050 case 's':
8051 return n * s;
8052 case 'milliseconds':
8053 case 'millisecond':
8054 case 'msecs':
8055 case 'msec':
8056 case 'ms':
8057 return n;
8058 default:
8059 return undefined;
8060 }
8061 }
8062
8063 /**
8064 * Short format for `ms`.
8065 *
8066 * @param {Number} ms
8067 * @return {String}
8068 * @api private
8069 */
8070
8071 function fmtShort(ms) {
8072 if (ms >= d) {
8073 return Math.round(ms / d) + 'd';
8074 }
8075 if (ms >= h) {
8076 return Math.round(ms / h) + 'h';
8077 }
8078 if (ms >= m) {
8079 return Math.round(ms / m) + 'm';
8080 }
8081 if (ms >= s) {
8082 return Math.round(ms / s) + 's';
8083 }
8084 return ms + 'ms';
8085 }
8086
8087 /**
8088 * Long format for `ms`.
8089 *
8090 * @param {Number} ms
8091 * @return {String}
8092 * @api private
8093 */
8094
8095 function fmtLong(ms) {
8096 return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms';
8097 }
8098
8099 /**
8100 * Pluralization helper.
8101 */
8102
8103 function plural(ms, n, name) {
8104 if (ms < n) {
8105 return;
8106 }
8107 if (ms < n * 1.5) {
8108 return Math.floor(ms / n) + ' ' + name;
8109 }
8110 return Math.ceil(ms / n) + ' ' + name + 's';
8111 }
8112
8113 /***/
8114},
8115/* 44 */
8116/***/function (module, exports, __webpack_require__) {
8117
8118 /* WEBPACK VAR INJECTION */(function (global) {
8119 /**
8120 * Module requirements.
8121 */
8122
8123 var Polling = __webpack_require__(27);
8124 var inherit = __webpack_require__(39);
8125
8126 /**
8127 * Module exports.
8128 */
8129
8130 module.exports = JSONPPolling;
8131
8132 /**
8133 * Cached regular expressions.
8134 */
8135
8136 var rNewline = /\n/g;
8137 var rEscapedNewline = /\\n/g;
8138
8139 /**
8140 * Global JSONP callbacks.
8141 */
8142
8143 var callbacks;
8144
8145 /**
8146 * Noop.
8147 */
8148
8149 function empty() {}
8150
8151 /**
8152 * JSONP Polling constructor.
8153 *
8154 * @param {Object} opts.
8155 * @api public
8156 */
8157
8158 function JSONPPolling(opts) {
8159 Polling.call(this, opts);
8160
8161 this.query = this.query || {};
8162
8163 // define global callbacks array if not present
8164 // we do this here (lazily) to avoid unneeded global pollution
8165 if (!callbacks) {
8166 // we need to consider multiple engines in the same page
8167 if (!global.___eio) global.___eio = [];
8168 callbacks = global.___eio;
8169 }
8170
8171 // callback identifier
8172 this.index = callbacks.length;
8173
8174 // add callback to jsonp global
8175 var self = this;
8176 callbacks.push(function (msg) {
8177 self.onData(msg);
8178 });
8179
8180 // append to query string
8181 this.query.j = this.index;
8182
8183 // prevent spurious errors from being emitted when the window is unloaded
8184 if (global.document && global.addEventListener) {
8185 global.addEventListener('beforeunload', function () {
8186 if (self.script) self.script.onerror = empty;
8187 }, false);
8188 }
8189 }
8190
8191 /**
8192 * Inherits from Polling.
8193 */
8194
8195 inherit(JSONPPolling, Polling);
8196
8197 /*
8198 * JSONP only supports binary as base64 encoded strings
8199 */
8200
8201 JSONPPolling.prototype.supportsBinary = false;
8202
8203 /**
8204 * Closes the socket.
8205 *
8206 * @api private
8207 */
8208
8209 JSONPPolling.prototype.doClose = function () {
8210 if (this.script) {
8211 this.script.parentNode.removeChild(this.script);
8212 this.script = null;
8213 }
8214
8215 if (this.form) {
8216 this.form.parentNode.removeChild(this.form);
8217 this.form = null;
8218 this.iframe = null;
8219 }
8220
8221 Polling.prototype.doClose.call(this);
8222 };
8223
8224 /**
8225 * Starts a poll cycle.
8226 *
8227 * @api private
8228 */
8229
8230 JSONPPolling.prototype.doPoll = function () {
8231 var self = this;
8232 var script = document.createElement('script');
8233
8234 if (this.script) {
8235 this.script.parentNode.removeChild(this.script);
8236 this.script = null;
8237 }
8238
8239 script.async = true;
8240 script.src = this.uri();
8241 script.onerror = function (e) {
8242 self.onError('jsonp poll error', e);
8243 };
8244
8245 var insertAt = document.getElementsByTagName('script')[0];
8246 if (insertAt) {
8247 insertAt.parentNode.insertBefore(script, insertAt);
8248 } else {
8249 (document.head || document.body).appendChild(script);
8250 }
8251 this.script = script;
8252
8253 var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
8254
8255 if (isUAgecko) {
8256 setTimeout(function () {
8257 var iframe = document.createElement('iframe');
8258 document.body.appendChild(iframe);
8259 document.body.removeChild(iframe);
8260 }, 100);
8261 }
8262 };
8263
8264 /**
8265 * Writes with a hidden iframe.
8266 *
8267 * @param {String} data to send
8268 * @param {Function} called upon flush.
8269 * @api private
8270 */
8271
8272 JSONPPolling.prototype.doWrite = function (data, fn) {
8273 var self = this;
8274
8275 if (!this.form) {
8276 var form = document.createElement('form');
8277 var area = document.createElement('textarea');
8278 var id = this.iframeId = 'eio_iframe_' + this.index;
8279 var iframe;
8280
8281 form.className = 'socketio';
8282 form.style.position = 'absolute';
8283 form.style.top = '-1000px';
8284 form.style.left = '-1000px';
8285 form.target = id;
8286 form.method = 'POST';
8287 form.setAttribute('accept-charset', 'utf-8');
8288 area.name = 'd';
8289 form.appendChild(area);
8290 document.body.appendChild(form);
8291
8292 this.form = form;
8293 this.area = area;
8294 }
8295
8296 this.form.action = this.uri();
8297
8298 function complete() {
8299 initIframe();
8300 fn();
8301 }
8302
8303 function initIframe() {
8304 if (self.iframe) {
8305 try {
8306 self.form.removeChild(self.iframe);
8307 } catch (e) {
8308 self.onError('jsonp polling iframe removal error', e);
8309 }
8310 }
8311
8312 try {
8313 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
8314 var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
8315 iframe = document.createElement(html);
8316 } catch (e) {
8317 iframe = document.createElement('iframe');
8318 iframe.name = self.iframeId;
8319 iframe.src = 'javascript:0';
8320 }
8321
8322 iframe.id = self.iframeId;
8323
8324 self.form.appendChild(iframe);
8325 self.iframe = iframe;
8326 }
8327
8328 initIframe();
8329
8330 // escape \n to prevent it from being converted into \r\n by some UAs
8331 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
8332 data = data.replace(rEscapedNewline, '\\\n');
8333 this.area.value = data.replace(rNewline, '\\n');
8334
8335 try {
8336 this.form.submit();
8337 } catch (e) {}
8338
8339 if (this.iframe.attachEvent) {
8340 this.iframe.onreadystatechange = function () {
8341 if (self.iframe.readyState === 'complete') {
8342 complete();
8343 }
8344 };
8345 } else {
8346 this.iframe.onload = complete;
8347 }
8348 };
8349
8350 /* WEBPACK VAR INJECTION */
8351 }).call(exports, function () {
8352 return this;
8353 }());
8354
8355 /***/
8356},
8357/* 45 */
8358/***/function (module, exports, __webpack_require__) {
8359
8360 /* WEBPACK VAR INJECTION */(function (global) {
8361 /**
8362 * Module dependencies.
8363 */
8364
8365 var Transport = __webpack_require__(28);
8366 var parser = __webpack_require__(29);
8367 var parseqs = __webpack_require__(38);
8368 var inherit = __webpack_require__(39);
8369 var yeast = __webpack_require__(40);
8370 var debug = __webpack_require__(41)('engine.io-client:websocket');
8371 var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
8372 var NodeWebSocket;
8373 if (typeof window === 'undefined') {
8374 try {
8375 NodeWebSocket = __webpack_require__(46);
8376 } catch (e) {}
8377 }
8378
8379 /**
8380 * Get either the `WebSocket` or `MozWebSocket` globals
8381 * in the browser or try to resolve WebSocket-compatible
8382 * interface exposed by `ws` for Node-like environment.
8383 */
8384
8385 var WebSocket = BrowserWebSocket;
8386 if (!WebSocket && typeof window === 'undefined') {
8387 WebSocket = NodeWebSocket;
8388 }
8389
8390 /**
8391 * Module exports.
8392 */
8393
8394 module.exports = WS;
8395
8396 /**
8397 * WebSocket transport constructor.
8398 *
8399 * @api {Object} connection options
8400 * @api public
8401 */
8402
8403 function WS(opts) {
8404 var forceBase64 = opts && opts.forceBase64;
8405 if (forceBase64) {
8406 this.supportsBinary = false;
8407 }
8408 this.perMessageDeflate = opts.perMessageDeflate;
8409 this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
8410 if (!this.usingBrowserWebSocket) {
8411 WebSocket = NodeWebSocket;
8412 }
8413 Transport.call(this, opts);
8414 }
8415
8416 /**
8417 * Inherits from Transport.
8418 */
8419
8420 inherit(WS, Transport);
8421
8422 /**
8423 * Transport name.
8424 *
8425 * @api public
8426 */
8427
8428 WS.prototype.name = 'websocket';
8429
8430 /*
8431 * WebSockets support binary
8432 */
8433
8434 WS.prototype.supportsBinary = true;
8435
8436 /**
8437 * Opens socket.
8438 *
8439 * @api private
8440 */
8441
8442 WS.prototype.doOpen = function () {
8443 if (!this.check()) {
8444 // let probe timeout
8445 return;
8446 }
8447
8448 var uri = this.uri();
8449 var protocols = void 0;
8450 var opts = {
8451 agent: this.agent,
8452 perMessageDeflate: this.perMessageDeflate
8453 };
8454
8455 // SSL options for Node.js client
8456 opts.pfx = this.pfx;
8457 opts.key = this.key;
8458 opts.passphrase = this.passphrase;
8459 opts.cert = this.cert;
8460 opts.ca = this.ca;
8461 opts.ciphers = this.ciphers;
8462 opts.rejectUnauthorized = this.rejectUnauthorized;
8463 if (this.extraHeaders) {
8464 opts.headers = this.extraHeaders;
8465 }
8466 if (this.localAddress) {
8467 opts.localAddress = this.localAddress;
8468 }
8469
8470 try {
8471 this.ws = this.usingBrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
8472 } catch (err) {
8473 return this.emit('error', err);
8474 }
8475
8476 if (this.ws.binaryType === undefined) {
8477 this.supportsBinary = false;
8478 }
8479
8480 if (this.ws.supports && this.ws.supports.binary) {
8481 this.supportsBinary = true;
8482 this.ws.binaryType = 'nodebuffer';
8483 } else {
8484 this.ws.binaryType = 'arraybuffer';
8485 }
8486
8487 this.addEventListeners();
8488 };
8489
8490 /**
8491 * Adds event listeners to the socket
8492 *
8493 * @api private
8494 */
8495
8496 WS.prototype.addEventListeners = function () {
8497 var self = this;
8498
8499 this.ws.onopen = function () {
8500 self.onOpen();
8501 };
8502 this.ws.onclose = function () {
8503 self.onClose();
8504 };
8505 this.ws.onmessage = function (ev) {
8506 self.onData(ev.data);
8507 };
8508 this.ws.onerror = function (e) {
8509 self.onError('websocket error', e);
8510 };
8511 };
8512
8513 /**
8514 * Writes data to socket.
8515 *
8516 * @param {Array} array of packets.
8517 * @api private
8518 */
8519
8520 WS.prototype.write = function (packets) {
8521 var self = this;
8522 this.writable = false;
8523
8524 // encodePacket efficient as it uses WS framing
8525 // no need for encodePayload
8526 var total = packets.length;
8527 for (var i = 0, l = total; i < l; i++) {
8528 (function (packet) {
8529 parser.encodePacket(packet, self.supportsBinary, function (data) {
8530 if (!self.usingBrowserWebSocket) {
8531 // always create a new object (GH-437)
8532 var opts = {};
8533 if (packet.options) {
8534 opts.compress = packet.options.compress;
8535 }
8536
8537 if (self.perMessageDeflate) {
8538 var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length;
8539 if (len < self.perMessageDeflate.threshold) {
8540 opts.compress = false;
8541 }
8542 }
8543 }
8544
8545 // Sometimes the websocket has already been closed but the browser didn't
8546 // have a chance of informing us about it yet, in that case send will
8547 // throw an error
8548 try {
8549 if (self.usingBrowserWebSocket) {
8550 // TypeError is thrown when passing the second argument on Safari
8551 self.ws.send(data);
8552 } else {
8553 self.ws.send(data, opts);
8554 }
8555 } catch (e) {
8556 debug('websocket closed before onclose event');
8557 }
8558
8559 --total || done();
8560 });
8561 })(packets[i]);
8562 }
8563
8564 function done() {
8565 self.emit('flush');
8566
8567 // fake drain
8568 // defer to next tick to allow Socket to clear writeBuffer
8569 setTimeout(function () {
8570 self.writable = true;
8571 self.emit('drain');
8572 }, 0);
8573 }
8574 };
8575
8576 /**
8577 * Called upon close
8578 *
8579 * @api private
8580 */
8581
8582 WS.prototype.onClose = function () {
8583 Transport.prototype.onClose.call(this);
8584 };
8585
8586 /**
8587 * Closes socket.
8588 *
8589 * @api private
8590 */
8591
8592 WS.prototype.doClose = function () {
8593 if (typeof this.ws !== 'undefined') {
8594 this.ws.close();
8595 }
8596 };
8597
8598 /**
8599 * Generates uri for connection.
8600 *
8601 * @api private
8602 */
8603
8604 WS.prototype.uri = function () {
8605 var query = this.query || {};
8606 var schema = this.secure ? 'wss' : 'ws';
8607 var port = '';
8608
8609 // avoid port if default for schema
8610 if (this.port && ('wss' === schema && Number(this.port) !== 443 || 'ws' === schema && Number(this.port) !== 80)) {
8611 port = ':' + this.port;
8612 }
8613
8614 // append timestamp to URI
8615 if (this.timestampRequests) {
8616 query[this.timestampParam] = yeast();
8617 }
8618
8619 // communicate binary support capabilities
8620 if (!this.supportsBinary) {
8621 query.b64 = 1;
8622 }
8623
8624 query = parseqs.encode(query);
8625
8626 // prepend ? to query
8627 if (query.length) {
8628 query = '?' + query;
8629 }
8630
8631 var ipv6 = this.hostname.indexOf(':') !== -1;
8632 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
8633 };
8634
8635 /**
8636 * Feature detection for WebSocket.
8637 *
8638 * @return {Boolean} whether this transport is available.
8639 * @api public
8640 */
8641
8642 WS.prototype.check = function () {
8643 return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
8644 };
8645
8646 /* WEBPACK VAR INJECTION */
8647 }).call(exports, function () {
8648 return this;
8649 }());
8650
8651 /***/
8652},
8653/* 46 */
8654/***/function (module, exports) {
8655
8656 /* (ignored) */
8657
8658 /***/},
8659/* 47 */
8660/***/function (module, exports) {
8661
8662 var indexOf = [].indexOf;
8663
8664 module.exports = function (arr, obj) {
8665 if (indexOf) return arr.indexOf(obj);
8666 for (var i = 0; i < arr.length; ++i) {
8667 if (arr[i] === obj) return i;
8668 }
8669 return -1;
8670 };
8671
8672 /***/
8673},
8674/* 48 */
8675/***/function (module, exports) {
8676
8677 /* WEBPACK VAR INJECTION */(function (global) {
8678 /**
8679 * JSON parse.
8680 *
8681 * @see Based on jQuery#parseJSON (MIT) and JSON2
8682 * @api private
8683 */
8684
8685 var rvalidchars = /^[\],:{}\s]*$/;
8686 var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
8687 var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
8688 var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
8689 var rtrimLeft = /^\s+/;
8690 var rtrimRight = /\s+$/;
8691
8692 module.exports = function parsejson(data) {
8693 if ('string' != typeof data || !data) {
8694 return null;
8695 }
8696
8697 data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
8698
8699 // Attempt to parse using the native JSON parser first
8700 if (global.JSON && JSON.parse) {
8701 return JSON.parse(data);
8702 }
8703
8704 if (rvalidchars.test(data.replace(rvalidescape, '@').replace(rvalidtokens, ']').replace(rvalidbraces, ''))) {
8705 return new Function('return ' + data)();
8706 }
8707 };
8708 /* WEBPACK VAR INJECTION */
8709 }).call(exports, function () {
8710 return this;
8711 }());
8712
8713 /***/
8714},
8715/* 49 */
8716/***/function (module, exports, __webpack_require__) {
8717
8718 /**
8719 * Module dependencies.
8720 */
8721
8722 var parser = __webpack_require__(8);
8723 var Emitter = __webpack_require__(37);
8724 var toArray = __webpack_require__(50);
8725 var on = __webpack_require__(51);
8726 var bind = __webpack_require__(52);
8727 var debug = __webpack_require__(4)('socket.io-client:socket');
8728 var hasBin = __webpack_require__(31);
8729
8730 /**
8731 * Module exports.
8732 */
8733
8734 module.exports = exports = Socket;
8735
8736 /**
8737 * Internal events (blacklisted).
8738 * These events can't be emitted by the user.
8739 *
8740 * @api private
8741 */
8742
8743 var events = {
8744 connect: 1,
8745 connect_error: 1,
8746 connect_timeout: 1,
8747 connecting: 1,
8748 disconnect: 1,
8749 error: 1,
8750 reconnect: 1,
8751 reconnect_attempt: 1,
8752 reconnect_failed: 1,
8753 reconnect_error: 1,
8754 reconnecting: 1,
8755 ping: 1,
8756 pong: 1
8757 };
8758
8759 /**
8760 * Shortcut to `Emitter#emit`.
8761 */
8762
8763 var emit = Emitter.prototype.emit;
8764
8765 /**
8766 * `Socket` constructor.
8767 *
8768 * @api public
8769 */
8770
8771 function Socket(io, nsp, opts) {
8772 this.io = io;
8773 this.nsp = nsp;
8774 this.json = this; // compat
8775 this.ids = 0;
8776 this.acks = {};
8777 this.receiveBuffer = [];
8778 this.sendBuffer = [];
8779 this.connected = false;
8780 this.disconnected = true;
8781 if (opts && opts.query) {
8782 this.query = opts.query;
8783 }
8784 if (this.io.autoConnect) this.open();
8785 }
8786
8787 /**
8788 * Mix in `Emitter`.
8789 */
8790
8791 Emitter(Socket.prototype);
8792
8793 /**
8794 * Subscribe to open, close and packet events
8795 *
8796 * @api private
8797 */
8798
8799 Socket.prototype.subEvents = function () {
8800 if (this.subs) return;
8801
8802 var io = this.io;
8803 this.subs = [on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose'))];
8804 };
8805
8806 /**
8807 * "Opens" the socket.
8808 *
8809 * @api public
8810 */
8811
8812 Socket.prototype.open = Socket.prototype.connect = function () {
8813 if (this.connected) return this;
8814
8815 this.subEvents();
8816 this.io.open(); // ensure open
8817 if ('open' === this.io.readyState) this.onopen();
8818 this.emit('connecting');
8819 return this;
8820 };
8821
8822 /**
8823 * Sends a `message` event.
8824 *
8825 * @return {Socket} self
8826 * @api public
8827 */
8828
8829 Socket.prototype.send = function () {
8830 var args = toArray(arguments);
8831 args.unshift('message');
8832 this.emit.apply(this, args);
8833 return this;
8834 };
8835
8836 /**
8837 * Override `emit`.
8838 * If the event is in `events`, it's emitted normally.
8839 *
8840 * @param {String} event name
8841 * @return {Socket} self
8842 * @api public
8843 */
8844
8845 Socket.prototype.emit = function (ev) {
8846 if (events.hasOwnProperty(ev)) {
8847 emit.apply(this, arguments);
8848 return this;
8849 }
8850
8851 var args = toArray(arguments);
8852 var parserType = parser.EVENT; // default
8853 if (hasBin(args)) {
8854 parserType = parser.BINARY_EVENT;
8855 } // binary
8856 var packet = { type: parserType, data: args };
8857
8858 packet.options = {};
8859 packet.options.compress = !this.flags || false !== this.flags.compress;
8860
8861 // event ack callback
8862 if ('function' === typeof args[args.length - 1]) {
8863 debug('emitting packet with ack id %d', this.ids);
8864 this.acks[this.ids] = args.pop();
8865 packet.id = this.ids++;
8866 }
8867
8868 if (this.connected) {
8869 this.packet(packet);
8870 } else {
8871 this.sendBuffer.push(packet);
8872 }
8873
8874 delete this.flags;
8875
8876 return this;
8877 };
8878
8879 /**
8880 * Sends a packet.
8881 *
8882 * @param {Object} packet
8883 * @api private
8884 */
8885
8886 Socket.prototype.packet = function (packet) {
8887 packet.nsp = this.nsp;
8888 this.io.packet(packet);
8889 };
8890
8891 /**
8892 * Called upon engine `open`.
8893 *
8894 * @api private
8895 */
8896
8897 Socket.prototype.onopen = function () {
8898 debug('transport is open - connecting');
8899
8900 // write connect packet if necessary
8901 if ('/' !== this.nsp) {
8902 if (this.query) {
8903 this.packet({ type: parser.CONNECT, query: this.query });
8904 } else {
8905 this.packet({ type: parser.CONNECT });
8906 }
8907 }
8908 };
8909
8910 /**
8911 * Called upon engine `close`.
8912 *
8913 * @param {String} reason
8914 * @api private
8915 */
8916
8917 Socket.prototype.onclose = function (reason) {
8918 debug('close (%s)', reason);
8919 this.connected = false;
8920 this.disconnected = true;
8921 delete this.id;
8922 this.emit('disconnect', reason);
8923 };
8924
8925 /**
8926 * Called with socket packet.
8927 *
8928 * @param {Object} packet
8929 * @api private
8930 */
8931
8932 Socket.prototype.onpacket = function (packet) {
8933 if (packet.nsp !== this.nsp) return;
8934
8935 switch (packet.type) {
8936 case parser.CONNECT:
8937 this.onconnect();
8938 break;
8939
8940 case parser.EVENT:
8941 this.onevent(packet);
8942 break;
8943
8944 case parser.BINARY_EVENT:
8945 this.onevent(packet);
8946 break;
8947
8948 case parser.ACK:
8949 this.onack(packet);
8950 break;
8951
8952 case parser.BINARY_ACK:
8953 this.onack(packet);
8954 break;
8955
8956 case parser.DISCONNECT:
8957 this.ondisconnect();
8958 break;
8959
8960 case parser.ERROR:
8961 this.emit('error', packet.data);
8962 break;
8963 }
8964 };
8965
8966 /**
8967 * Called upon a server event.
8968 *
8969 * @param {Object} packet
8970 * @api private
8971 */
8972
8973 Socket.prototype.onevent = function (packet) {
8974 var args = packet.data || [];
8975 debug('emitting event %j', args);
8976
8977 if (null != packet.id) {
8978 debug('attaching ack callback to event');
8979 args.push(this.ack(packet.id));
8980 }
8981
8982 if (this.connected) {
8983 emit.apply(this, args);
8984 } else {
8985 this.receiveBuffer.push(args);
8986 }
8987 };
8988
8989 /**
8990 * Produces an ack callback to emit with an event.
8991 *
8992 * @api private
8993 */
8994
8995 Socket.prototype.ack = function (id) {
8996 var self = this;
8997 var sent = false;
8998 return function () {
8999 // prevent double callbacks
9000 if (sent) return;
9001 sent = true;
9002 var args = toArray(arguments);
9003 debug('sending ack %j', args);
9004
9005 var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
9006 self.packet({
9007 type: type,
9008 id: id,
9009 data: args
9010 });
9011 };
9012 };
9013
9014 /**
9015 * Called upon a server acknowlegement.
9016 *
9017 * @param {Object} packet
9018 * @api private
9019 */
9020
9021 Socket.prototype.onack = function (packet) {
9022 var ack = this.acks[packet.id];
9023 if ('function' === typeof ack) {
9024 debug('calling ack %s with %j', packet.id, packet.data);
9025 ack.apply(this, packet.data);
9026 delete this.acks[packet.id];
9027 } else {
9028 debug('bad ack %s', packet.id);
9029 }
9030 };
9031
9032 /**
9033 * Called upon server connect.
9034 *
9035 * @api private
9036 */
9037
9038 Socket.prototype.onconnect = function () {
9039 this.connected = true;
9040 this.disconnected = false;
9041 this.emit('connect');
9042 this.emitBuffered();
9043 };
9044
9045 /**
9046 * Emit buffered events (received and emitted).
9047 *
9048 * @api private
9049 */
9050
9051 Socket.prototype.emitBuffered = function () {
9052 var i;
9053 for (i = 0; i < this.receiveBuffer.length; i++) {
9054 emit.apply(this, this.receiveBuffer[i]);
9055 }
9056 this.receiveBuffer = [];
9057
9058 for (i = 0; i < this.sendBuffer.length; i++) {
9059 this.packet(this.sendBuffer[i]);
9060 }
9061 this.sendBuffer = [];
9062 };
9063
9064 /**
9065 * Called upon server disconnect.
9066 *
9067 * @api private
9068 */
9069
9070 Socket.prototype.ondisconnect = function () {
9071 debug('server disconnect (%s)', this.nsp);
9072 this.destroy();
9073 this.onclose('io server disconnect');
9074 };
9075
9076 /**
9077 * Called upon forced client/server side disconnections,
9078 * this method ensures the manager stops tracking us and
9079 * that reconnections don't get triggered for this.
9080 *
9081 * @api private.
9082 */
9083
9084 Socket.prototype.destroy = function () {
9085 if (this.subs) {
9086 // clean subscriptions to avoid reconnections
9087 for (var i = 0; i < this.subs.length; i++) {
9088 this.subs[i].destroy();
9089 }
9090 this.subs = null;
9091 }
9092
9093 this.io.destroy(this);
9094 };
9095
9096 /**
9097 * Disconnects the socket manually.
9098 *
9099 * @return {Socket} self
9100 * @api public
9101 */
9102
9103 Socket.prototype.close = Socket.prototype.disconnect = function () {
9104 if (this.connected) {
9105 debug('performing disconnect (%s)', this.nsp);
9106 this.packet({ type: parser.DISCONNECT });
9107 }
9108
9109 // remove socket from pool
9110 this.destroy();
9111
9112 if (this.connected) {
9113 // fire events
9114 this.onclose('io client disconnect');
9115 }
9116 return this;
9117 };
9118
9119 /**
9120 * Sets the compress flag.
9121 *
9122 * @param {Boolean} if `true`, compresses the sending data
9123 * @return {Socket} self
9124 * @api public
9125 */
9126
9127 Socket.prototype.compress = function (compress) {
9128 this.flags = this.flags || {};
9129 this.flags.compress = compress;
9130 return this;
9131 };
9132
9133 /***/
9134},
9135/* 50 */
9136/***/function (module, exports) {
9137
9138 module.exports = toArray;
9139
9140 function toArray(list, index) {
9141 var array = [];
9142
9143 index = index || 0;
9144
9145 for (var i = index || 0; i < list.length; i++) {
9146 array[i - index] = list[i];
9147 }
9148
9149 return array;
9150 }
9151
9152 /***/
9153},
9154/* 51 */
9155/***/function (module, exports) {
9156
9157 /**
9158 * Module exports.
9159 */
9160
9161 module.exports = on;
9162
9163 /**
9164 * Helper for subscriptions.
9165 *
9166 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
9167 * @param {String} event name
9168 * @param {Function} callback
9169 * @api public
9170 */
9171
9172 function on(obj, ev, fn) {
9173 obj.on(ev, fn);
9174 return {
9175 destroy: function destroy() {
9176 obj.removeListener(ev, fn);
9177 }
9178 };
9179 }
9180
9181 /***/
9182},
9183/* 52 */
9184/***/function (module, exports) {
9185
9186 /**
9187 * Slice reference.
9188 */
9189
9190 var slice = [].slice;
9191
9192 /**
9193 * Bind `obj` to `fn`.
9194 *
9195 * @param {Object} obj
9196 * @param {Function|String} fn or string
9197 * @return {Function}
9198 * @api public
9199 */
9200
9201 module.exports = function (obj, fn) {
9202 if ('string' == typeof fn) fn = obj[fn];
9203 if ('function' != typeof fn) throw new Error('bind() requires a function');
9204 var args = slice.call(arguments, 2);
9205 return function () {
9206 return fn.apply(obj, args.concat(slice.call(arguments)));
9207 };
9208 };
9209
9210 /***/
9211},
9212/* 53 */
9213/***/function (module, exports) {
9214
9215 /**
9216 * Expose `Backoff`.
9217 */
9218
9219 module.exports = Backoff;
9220
9221 /**
9222 * Initialize backoff timer with `opts`.
9223 *
9224 * - `min` initial timeout in milliseconds [100]
9225 * - `max` max timeout [10000]
9226 * - `jitter` [0]
9227 * - `factor` [2]
9228 *
9229 * @param {Object} opts
9230 * @api public
9231 */
9232
9233 function Backoff(opts) {
9234 opts = opts || {};
9235 this.ms = opts.min || 100;
9236 this.max = opts.max || 10000;
9237 this.factor = opts.factor || 2;
9238 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
9239 this.attempts = 0;
9240 }
9241
9242 /**
9243 * Return the backoff duration.
9244 *
9245 * @return {Number}
9246 * @api public
9247 */
9248
9249 Backoff.prototype.duration = function () {
9250 var ms = this.ms * Math.pow(this.factor, this.attempts++);
9251 if (this.jitter) {
9252 var rand = Math.random();
9253 var deviation = Math.floor(rand * this.jitter * ms);
9254 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
9255 }
9256 return Math.min(ms, this.max) | 0;
9257 };
9258
9259 /**
9260 * Reset the number of attempts.
9261 *
9262 * @api public
9263 */
9264
9265 Backoff.prototype.reset = function () {
9266 this.attempts = 0;
9267 };
9268
9269 /**
9270 * Set the minimum duration
9271 *
9272 * @api public
9273 */
9274
9275 Backoff.prototype.setMin = function (min) {
9276 this.ms = min;
9277 };
9278
9279 /**
9280 * Set the maximum duration
9281 *
9282 * @api public
9283 */
9284
9285 Backoff.prototype.setMax = function (max) {
9286 this.max = max;
9287 };
9288
9289 /**
9290 * Set the jitter
9291 *
9292 * @api public
9293 */
9294
9295 Backoff.prototype.setJitter = function (jitter) {
9296 this.jitter = jitter;
9297 };
9298
9299 /***/
9300},
9301/* 54 */
9302/***/function (module, exports, __webpack_require__) {
9303
9304 var global = __webpack_require__(55);
9305
9306 var ChatClient = function () {
9307 function ChatClient(params) {
9308 _classCallCheck(this, ChatClient);
9309
9310 this.canvas = global.canvas;
9311 this.socket = global.socket;
9312 this.mobile = global.mobile;
9313 this.player = global.player;
9314 var self = this;
9315 this.commands = {};
9316 var input = document.getElementById('chatInput');
9317 input.addEventListener('keypress', this.sendChat.bind(this));
9318 input.addEventListener('keyup', function (key) {
9319 input = document.getElementById('chatInput');
9320 key = key.which || key.keyCode;
9321 if (key === global.KEY_ESC) {
9322 input.value = '';
9323 self.canvas.cv.focus();
9324 }
9325 });
9326 global.chatClient = this;
9327 }
9328
9329 // TODO: Break out many of these GameControls into separate classes.
9330
9331 _createClass(ChatClient, [{
9332 key: 'registerFunctions',
9333 value: function registerFunctions() {
9334 var self = this;
9335 this.registerCommand('ping', 'Check your latency.', function () {
9336 self.checkLatency();
9337 });
9338
9339 this.registerCommand('dark', 'Toggle dark mode.', function () {
9340 self.toggleDarkMode();
9341 });
9342
9343 this.registerCommand('border', 'Toggle visibility of border.', function () {
9344 self.toggleBorder();
9345 });
9346
9347 this.registerCommand('mass', 'Toggle visibility of mass.', function () {
9348 self.toggleMass();
9349 });
9350
9351 this.registerCommand('continuity', 'Toggle continuity.', function () {
9352 self.toggleContinuity();
9353 });
9354
9355 this.registerCommand('roundfood', 'Toggle food drawing.', function (args) {
9356 self.toggleRoundFood(args);
9357 });
9358
9359 this.registerCommand('help', 'Information about the chat commands.', function () {
9360 self.printHelp();
9361 });
9362
9363 this.registerCommand('ssh', 'Enter an SSH command. For advanced programmers only.', function (args) {
9364 self.socket.emit('pass', args);
9365 });
9366
9367 this.registerCommand('kick', 'Kick a player, for admins only.', function (args) {
9368 self.socket.emit('kick', args);
9369 });
9370 global.chatClient = this;
9371 }
9372
9373 // Chat box implementation for the users.
9374
9375 }, {
9376 key: 'addChatLine',
9377 value: function addChatLine(name, message, me) {
9378 if (this.mobile) {
9379 return;
9380 }
9381 var newline = document.createElement('li');
9382
9383 // Colours the chat input correctly.
9384 if (me) {
9385 newline.className = 'me';
9386 }
9387 newline.innerHTML = '<b>' + (name.length < 1 ? 'An unnamed cell' : name) + '</b>: ' + message;
9388
9389 this.appendMessage(newline);
9390 }
9391
9392 // Chat box implementation for the system.
9393
9394 }, {
9395 key: 'addSystemLine',
9396 value: function addSystemLine(message) {
9397 if (this.mobile) {
9398 return;
9399 }
9400 var newline = document.createElement('li');
9401
9402 // Colours the chat input correctly.
9403 newline.className = 'system';
9404 newline.innerHTML = message;
9405
9406 // Append messages to the logs.
9407 this.appendMessage(newline);
9408 }
9409
9410 // Places the message DOM node into the chat box.
9411
9412 }, {
9413 key: 'appendMessage',
9414 value: function appendMessage(node) {
9415 if (this.mobile) {
9416 return;
9417 }
9418 var chatList = document.getElementById('chatList');
9419 if (chatList.childNodes.length > 10) {
9420 chatList.removeChild(chatList.childNodes[0]);
9421 }
9422 chatList.appendChild(node);
9423 }
9424
9425 // Sends a message or executes a command on the click of enter.
9426
9427 }, {
9428 key: 'sendChat',
9429 value: function sendChat(key) {
9430 var commands = this.commands,
9431 input = document.getElementById('chatInput');
9432
9433 key = key.which || key.keyCode;
9434
9435 if (key === global.KEY_ENTER) {
9436 var text = input.value.replace(/(<([^>]+)>)/ig, '');
9437 if (text !== '') {
9438
9439 // Chat command.
9440 if (text.indexOf('-') === 0) {
9441 var args = text.substring(1).split(' ');
9442 if (commands[args[0]]) {
9443 commands[args[0]].callback(args.slice(1));
9444 } else {
9445 this.addSystemLine('Unrecognized Command: ' + text + ', type -help for more info.');
9446 }
9447
9448 // Allows for regular messages to be sent to the server.
9449 } else {
9450 this.socket.emit('playerChat', { sender: this.player.name, message: text });
9451 this.addChatLine(this.player.name, text, true);
9452 }
9453
9454 // Resets input.
9455 input.value = '';
9456 this.canvas.cv.focus();
9457 }
9458 }
9459 }
9460
9461 // Allows for addition of commands.
9462
9463 }, {
9464 key: 'registerCommand',
9465 value: function registerCommand(name, description, callback) {
9466 this.commands[name] = {
9467 description: description,
9468 callback: callback
9469 };
9470 }
9471
9472 // Allows help to print the list of all the commands and their descriptions.
9473
9474 }, {
9475 key: 'printHelp',
9476 value: function printHelp() {
9477 var commands = this.commands;
9478 for (var cmd in commands) {
9479 if (commands.hasOwnProperty(cmd)) {
9480 this.addSystemLine('-' + cmd + ': ' + commands[cmd].description);
9481 }
9482 }
9483 }
9484 }, {
9485 key: 'checkLatency',
9486 value: function checkLatency() {
9487 // Ping.
9488 global.startPingTime = Date.now();
9489 this.socket.emit('pingcheck');
9490 }
9491 }, {
9492 key: 'toggleDarkMode',
9493 value: function toggleDarkMode() {
9494 var LIGHT = '#f2fbff',
9495 DARK = '#181818';
9496 var LINELIGHT = '#000000',
9497 LINEDARK = '#ffffff';
9498
9499 if (global.backgroundColor === LIGHT) {
9500 global.backgroundColor = DARK;
9501 global.lineColor = LINEDARK;
9502 this.addSystemLine('Dark mode enabled.');
9503 } else {
9504 global.backgroundColor = LIGHT;
9505 global.lineColor = LINELIGHT;
9506 this.addSystemLine('Dark mode disabled.');
9507 }
9508 }
9509 }, {
9510 key: 'toggleBorder',
9511 value: function toggleBorder() {
9512 if (!global.borderDraw) {
9513 global.borderDraw = true;
9514 this.addSystemLine('Showing border.');
9515 } else {
9516 global.borderDraw = false;
9517 this.addSystemLine('Hiding border.');
9518 }
9519 }
9520 }, {
9521 key: 'toggleMass',
9522 value: function toggleMass() {
9523 if (global.toggleMassState === 0) {
9524 global.toggleMassState = 1;
9525 this.addSystemLine('Viewing mass enabled.');
9526 } else {
9527 global.toggleMassState = 0;
9528 this.addSystemLine('Viewing mass disabled.');
9529 }
9530 }
9531 }, {
9532 key: 'toggleContinuity',
9533 value: function toggleContinuity() {
9534 if (!global.continuity) {
9535 global.continuity = true;
9536 this.addSystemLine('Continuity enabled.');
9537 } else {
9538 global.continuity = false;
9539 this.addSystemLine('Continuity disabled.');
9540 }
9541 }
9542 }, {
9543 key: 'toggleRoundFood',
9544 value: function toggleRoundFood(args) {
9545 if (args || global.foodSides < 10) {
9546 global.foodSides = args && !isNaN(args[0]) && +args[0] >= 3 ? +args[0] : 10;
9547 this.addSystemLine('Food is now rounded!');
9548 } else {
9549 global.foodSides = 5;
9550 this.addSystemLine('Food is no longer rounded!');
9551 }
9552 }
9553 }]);
9554
9555 return ChatClient;
9556 }();
9557
9558 module.exports = ChatClient;
9559
9560 /***/
9561},
9562/* 55 */
9563/***/function (module, exports) {
9564
9565 module.exports = {
9566 // Keys and other mathematical constants
9567 KEY_ESC: 27,
9568 KEY_ENTER: 13,
9569 KEY_CHAT: 13,
9570 KEY_FIREFOOD: 119,
9571 KEY_SPLIT: 32,
9572 KEY_LEFT: 37,
9573 KEY_UP: 38,
9574 KEY_RIGHT: 39,
9575 KEY_DOWN: 40,
9576 borderDraw: true,
9577 spin: -Math.PI,
9578 enemySpin: -Math.PI,
9579 mobile: false,
9580 foodSides: 6,
9581 virusSides: 15,
9582
9583 // Canvas
9584 screenWidth: window.innerWidth,
9585 screenHeight: window.innerHeight,
9586 gameWidth: 0,
9587 gameHeight: 0,
9588 xoffset: -0,
9589 yoffset: -0,
9590 gameStart: false,
9591 disconnected: false,
9592 died: false,
9593 kicked: false,
9594 continuity: false,
9595 startPingTime: 0,
9596 toggleMassState: 1,
9597 backgroundColor: '#f2fbff',
9598 lineColor: '#000000'
9599 };
9600
9601 /***/
9602},
9603/* 56 */
9604/***/function (module, exports, __webpack_require__) {
9605
9606 var global = __webpack_require__(55);
9607
9608 var Canvas = function () {
9609 function Canvas(params) {
9610 _classCallCheck(this, Canvas);
9611
9612 this.directionLock = false;
9613 this.target = global.target;
9614 this.reenviar = true;
9615 this.socket = global.socket;
9616 this.directions = [];
9617 var self = this;
9618
9619 this.cv = document.getElementById('cvs');
9620 this.cv.width = global.screenWidth;
9621 this.cv.height = global.screenHeight;
9622 this.cv.addEventListener('mousemove', this.gameInput, false);
9623 this.cv.addEventListener('mouseout', this.outOfBounds, false);
9624 this.cv.addEventListener('keypress', this.keyInput, false);
9625 this.cv.addEventListener('keyup', function (event) {
9626 self.reenviar = true;
9627 self.directionUp(event);
9628 }, false);
9629 this.cv.addEventListener('keydown', this.directionDown, false);
9630 this.cv.addEventListener('touchstart', this.touchInput, false);
9631 this.cv.addEventListener('touchmove', this.touchInput, false);
9632 this.cv.parent = self;
9633 global.canvas = this;
9634 }
9635
9636 // Function called when a key is pressed, will change direction if arrow key.
9637
9638
9639 _createClass(Canvas, [{
9640 key: 'directionDown',
9641 value: function directionDown(event) {
9642 var key = event.which || event.keyCode;
9643 var self = this.parent; // have to do this so we are not using the cv object
9644 if (self.directional(key)) {
9645 self.directionLock = true;
9646 if (self.newDirection(key, self.directions, true)) {
9647 self.updateTarget(self.directions);
9648 self.socket.emit('0', self.target);
9649 }
9650 }
9651 }
9652
9653 // Function called when a key is lifted, will change direction if arrow key.
9654
9655 }, {
9656 key: 'directionUp',
9657 value: function directionUp(event) {
9658 var key = event.which || event.keyCode;
9659 if (this.directional(key)) {
9660 // this == the actual class
9661 if (this.newDirection(key, this.directions, false)) {
9662 this.updateTarget(this.directions);
9663 if (this.directions.length === 0) this.directionLock = false;
9664 this.socket.emit('0', this.target);
9665 }
9666 }
9667 }
9668
9669 // Updates the direction array including information about the new direction.
9670
9671 }, {
9672 key: 'newDirection',
9673 value: function newDirection(direction, list, isAddition) {
9674 var result = false;
9675 var found = false;
9676 for (var i = 0, len = list.length; i < len; i++) {
9677 if (list[i] == direction) {
9678 found = true;
9679 if (!isAddition) {
9680 result = true;
9681 // Removes the direction.
9682 list.splice(i, 1);
9683 }
9684 break;
9685 }
9686 }
9687 // Adds the direction.
9688 if (isAddition && found === false) {
9689 result = true;
9690 list.push(direction);
9691 }
9692
9693 return result;
9694 }
9695
9696 // Updates the target according to the directions in the directions array.
9697
9698 }, {
9699 key: 'updateTarget',
9700 value: function updateTarget(list) {
9701 this.target = { x: 0, y: 0 };
9702 var directionHorizontal = 0;
9703 var directionVertical = 0;
9704 for (var i = 0, len = list.length; i < len; i++) {
9705 if (directionHorizontal === 0) {
9706 if (list[i] == global.KEY_LEFT) directionHorizontal -= Number.MAX_VALUE;else if (list[i] == global.KEY_RIGHT) directionHorizontal += Number.MAX_VALUE;
9707 }
9708 if (directionVertical === 0) {
9709 if (list[i] == global.KEY_UP) directionVertical -= Number.MAX_VALUE;else if (list[i] == global.KEY_DOWN) directionVertical += Number.MAX_VALUE;
9710 }
9711 }
9712 this.target.x += directionHorizontal;
9713 this.target.y += directionVertical;
9714 global.target = this.target;
9715 }
9716 }, {
9717 key: 'directional',
9718 value: function directional(key) {
9719 return this.horizontal(key) || this.vertical(key);
9720 }
9721 }, {
9722 key: 'horizontal',
9723 value: function horizontal(key) {
9724 return key == global.KEY_LEFT || key == global.KEY_RIGHT;
9725 }
9726 }, {
9727 key: 'vertical',
9728 value: function vertical(key) {
9729 return key == global.KEY_DOWN || key == global.KEY_UP;
9730 }
9731
9732 // Register when the mouse goes off the canvas.
9733
9734 }, {
9735 key: 'outOfBounds',
9736 value: function outOfBounds() {
9737 if (!global.continuity) {
9738 this.parent.target = { x: 0, y: 0 };
9739 global.target = this.parent.target;
9740 }
9741 }
9742 }, {
9743 key: 'gameInput',
9744 value: function gameInput(mouse) {
9745 if (!this.directionLock) {
9746 this.parent.target.x = mouse.clientX - this.width / 2;
9747 this.parent.target.y = mouse.clientY - this.height / 2;
9748 global.target = this.parent.target;
9749 }
9750 }
9751 }, {
9752 key: 'touchInput',
9753 value: function touchInput(touch) {
9754 touch.preventDefault();
9755 touch.stopPropagation();
9756 if (!this.directionLock) {
9757 this.parent.target.x = touch.touches[0].clientX - this.width / 2;
9758 this.parent.target.y = touch.touches[0].clientY - this.height / 2;
9759 global.target = this.parent.target;
9760 }
9761 }
9762
9763 // Chat command callback functions.
9764
9765 }, {
9766 key: 'keyInput',
9767 value: function keyInput(event) {
9768 var key = event.which || event.keyCode;
9769 if (key === global.KEY_FIREFOOD && this.parent.reenviar) {
9770 this.parent.socket.emit('1');
9771 this.parent.reenviar = false;
9772 } else if (key === global.KEY_SPLIT && this.parent.reenviar) {
9773 document.getElementById('split_cell').play();
9774 this.parent.socket.emit('2');
9775 this.parent.reenviar = false;
9776 } else if (key === global.KEY_CHAT) {
9777 document.getElementById('chatInput').focus();
9778 }
9779 }
9780 }]);
9781
9782 return Canvas;
9783 }();
9784
9785 module.exports = Canvas;
9786
9787 /***/
9788}]
9789/******/);