(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],3:[function(require,module,exports){ function Color(h, s, l, a) { verifyRange(h, s, l); if (a === undefined) a = 1; else verifyRange(a); Object.defineProperties(this, { "hue": {value: h, enumerable: true}, "sat": {value: s, enumerable: true}, "lum": {value: l, enumerable: true}, "alpha": {value: a, enumerable: true}, }); } Color.fromData = function(data) { return new Color(data.hue, data.sat, data.lum, data.alpha); }; function verifyRange() { for (var i = 0; i < arguments.length; i++) { if (arguments[i] < 0 || arguments[i] > 1) throw new RangeError("H, S, L, and A parameters must be between the range [0, 1]"); } } Color.prototype.interpolateToString = function(color, amount) { var rgbThis = hslToRgb(this.hue, this.sat, this.lum); var rgbThat = hslToRgb(color.hue, color.sat, color.lum); var rgb = []; for (var i = 0; i < 3; i++) rgb[i] = Math.floor((rgbThat[i] - rgbThis[i]) * amount + rgbThis[i]); return {rgbString: function() {return 'rgb(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ')'}}; } Color.prototype.deriveLumination = function(amount) { var lum = this.lum + amount; lum = Math.min(Math.max(lum, 0), 1); return new Color(this.hue, this.sat, lum, this.alpha); }; Color.prototype.deriveHue = function(amount) { var hue = this.hue - amount; return new Color(hue - Math.floor(hue), this.sat, this.lum, this.alpha); }; Color.prototype.deriveSaturation = function(amount) { var sat = this.sat + amount; sat = Math.min(Math.max(sat, 0), 1); return new Color(this.hue, sat, this.lum, this.alpha); }; Color.prototype.deriveAlpha = function(newAlpha) { verifyRange(newAlpha); return new Color(this.hue, this.sat, this.lum, newAlpha); }; Color.prototype.rgbString = function() { var rgb = hslToRgb(this.hue, this.sat, this.lum); rgb[3] = this.a; return 'rgba(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ', ' + this.alpha + ')'; }; //http://stackoverflow.com/a/9493060/7344257 function hslToRgb(h, s, l){ var r, g, b; if(s == 0){ r = g = b = l; // achromatic }else{ var hue2rgb = function hue2rgb(p, q, t){ if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; }; var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } module.exports = Color; },{}],4:[function(require,module,exports){ /* global $ */ var Player = require("./player.js"); var renderer = require("./game-renderer.js"); var consts = require("./game-consts.js"); var core = require("./game-core.js"); var io = require('socket.io-client'); var GRID_SIZE = consts.GRID_SIZE; var CELL_WIDTH = consts.CELL_WIDTH; renderer.allowAnimation = true; /** * Provides requestAnimationFrame in a cross browser way. * @author paulirish / http://paulirish.com/ */ // window.requestAnimationFrame = function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) { // window.setTimeout( callback, 1000 / 60 ); // }; if ( !window.requestAnimationFrame ) { window.requestAnimationFrame = ( function() { return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) { window.setTimeout( callback, 1000 / 60 ); }; })(); } var user, socket, frame; //Event listeners $(document).keydown(function(e) { if (!user || user.dead) return; var newHeading = -1; switch (e.which) { case 37: newHeading = 3; break; //LEFT case 38: newHeading = 0; break; //UP case 39: newHeading = 1; break; //RIGHT case 40: newHeading = 2; break; //DOWN default: return; //exit handler for other keys. } if (newHeading === user.currentHeading || ((newHeading % 2 === 0) ^ (user.currentHeading % 2 === 0))) { //user.heading = newHeading; if (socket) socket.emit("frame", { frame: frame, heading: newHeading }, function(success, msg) { if (!success) console.error(msg); }); } e.preventDefault(); }); var norun = false; window.run = run; function run() { if (norun) return; //Prevent multiple clicks. norun = true; $("#begin").css("display: none"); $("#begin").animate({ opacity: 0 }, 1000); user = null; deadFrames = 0; //Socket connection. //, {transports: ['websocket'], upgrade: false} connectServer(); socket.emit('hello', { name: $("#name").val(), type: 0, //Free-for-all gameid: -1 //Requested game-id, or -1 for anyone. }, function(success) { if (success) console.info("Connected to game!"); else console.error("Unable to connect to game."); }); } var grid = renderer.grid; var timeout = undefined; var dirty = false; var deadFrames = 0; var requesting = -1; //frame that we are requesting at. var frameCache = []; //Frames after our request. //TODO: check if we can connect to server. function connectServer() { io.j = []; io.sockets = []; socket = io('http://paper-io-thekidofarcrania.c9users.io:8081', {'forceNew': true}); socket.on('connect', function(){ console.info("Connected to server."); }); socket.on('game', function(data) { if (timeout != undefined) clearTimeout(timeout); //Initialize game. //TODO: display data.gameid --- game id # frame = data.frame; renderer.reset(); //Load players. data.players.forEach(function(p) { var pl = new Player(grid, p); renderer.addPlayer(pl); }); user = renderer.getPlayerFromNum(data.num); if (!user) throw new Error(); renderer.setUser(user); //Load grid. var gridData = new Uint8Array(data.grid); for (var r = 0; r < grid.size; r++) for (var c = 0; c < grid.size; c++) { var ind = gridData[r * grid.size + c] - 1; grid.set(r, c, ind === -1 ? null : renderer.getPlayer(ind)); } renderer.paint(); frame = data.frame; if (requesting !== -1) { //Update those cache frames after we updated game. var minFrame = requesting; requesting = -1; while (frameCache.length > frame - minFrame) processFrame(frameCache[frame - minFrame]); frameCache = []; } }); socket.on('notifyFrame', processFrame); socket.on('dead', function() { socket.disconnect(); //In case we didn't get the disconnect call. }); socket.on('disconnect', function(){ if (!user) return; console.info("Server has disconnected. Creating new game."); socket.disconnect(); user.die(); dirty = true; paintLoop(); $("#begin").css("display: block"); $("#begin").animate({ opacity: .9999 }, 1000, function() { norun = false; }); }); } function processFrame(data) { if (timeout != undefined) clearTimeout(timeout); if (requesting !== -1 && requesting < data.frame) { frameCache.push(data); return; } if (data.frame - 1 !== frame) { console.error("Frames don't match up!"); socket.emit('requestFrame'); //Restore data. requesting = data.frame; frameCache.push(data); return; } frame++; if (data.newPlayers) { data.newPlayers.forEach(function(p) { if (p.num === user.num) return; var pl = new Player(grid, p); renderer.addPlayer(pl); core.initPlayer(grid, pl); }); } var found = new Array(renderer.playerSize()); data.moves.forEach(function(val, i) { var player = renderer.getPlayerFromNum(val.num); if (!player) return; if (val.left) player.die(); found[i] = true; player.heading = val.heading; }); for (var i = 0; i < renderer.playerSize(); i++) { //Implicitly leaving game. if (!found[i]) { var player = renderer.getPlayer(); player && player.die(); } } renderer.update(); var locs = {}; for (var i = 0; i < renderer.playerSize(); i++) { var p = renderer.getPlayer(i); locs[p.num] = [p.posX, p.posY, p.waitLag]; } socket.emit("verify", { frame: frame, locs: locs }, function(frame, success, adviceFix, msg) { if (!success && requesting === -1) { console.error(frame + ": " + msg); if (adviceFix) socket.emit('requestFrame'); } }.bind(this, frame)); dirty = true; requestAnimationFrame(function() { paintLoop(); }); timeout = setTimeout(function() { console.warn("Server has timed-out. Disconnecting."); socket.disconnect(); }, 3000); } function paintLoop() { if (!dirty) return; renderer.paint(); dirty = false; if (user.dead) { if (timeout) clearTimeout(timeout); if (deadFrames === 60) //One second of frame { var before = renderer.allowAnimation; renderer.allowAnimation = false; renderer.update(); renderer.paint(); renderer.allowAnimation = before; user = null; deadFrames = 0; return; } socket.disconnect(); deadFrames++; dirty = true; renderer.update(); requestAnimationFrame(paintLoop); } } },{"./game-consts.js":5,"./game-core.js":6,"./game-renderer.js":7,"./player.js":56,"socket.io-client":9}],5:[function(require,module,exports){ function constant(val) { return { value: val, enumerable: true }; } var consts = { GRID_SIZE: constant(80), CELL_WIDTH: constant(40), SPEED: constant(5), BORDER_WIDTH: constant(20), MAX_PLAYERS: constant(81) }; Object.defineProperties(module.exports, consts); },{}],6:[function(require,module,exports){ var ANIMATE_FRAMES = 24; var CELL_WIDTH = 40; //TODO: remove constants. exports.initPlayer = function(grid, player) { for (var dr = -1; dr <= 1; dr++) for (var dc = -1; dc <= 1; dc++) if (!grid.isOutOfBounds(dr + player.row, dc + player.col)) grid.set(dr + player.row, dc + player.col, player); }; exports.updateFrame = function(grid, players, dead, notifyKill) { var adead = []; if (dead instanceof Array) adead = dead; var kill; if (!notifyKill) kill = function() {}; else kill = function(killer, other) {if (!removing[other]) notifyKill(killer, other);}; //Move players. var tmp = players.filter(function(val) { val.move(); if (val.dead) adead.push(val); return !val.dead; }); //Remove players with collisions. var removing = new Array(players.length); for (var i = 0; i < players.length; i++) { for (var j = i; j < players.length; j++) { //Remove those players when other players have hit their tail. if (!removing[j] && players[j].tail.hitsTail(players[i])) { kill(i, j); removing[j] = true; //console.log("TAIL"); } if (!removing[i] && players[i].tail.hitsTail(players[j])) { kill(j, i); removing[i] = true; //console.log("TAIL"); } //Remove players with collisons... if (i !== j && squaresIntersect(players[i].posX, players[j].posX) && squaresIntersect(players[i].posY, players[j].posY)) { //...if one player is own his own territory, the other is out. if (grid.get(players[i].row, players[i].col) === players[i]) { kill(i, j); removing[j] = true; } else if (grid.get(players[j].row, players[j].col) === players[j]) { kill(j, i); removing[i] = true; } else { //...otherwise, the one that sustains most of the collision will be removed. var areaI = area(players[i]); var areaJ = area(players[j]); if (areaI === areaJ) { kill(i, j); kill(j, i); removing[i] = removing[j] = true; } else if (areaI > areaJ) { kill(j, i); removing[i] = true; } else { kill(i, j); removing[j] = true; } } } } } tmp = tmp.filter(function(val, i) { if (removing[i]) { adead.push(val); val.die(); } return !removing[i]; }); players.length = tmp.length; for (var i = 0; i < tmp.length; i++) players[i] = tmp[i]; //Remove dead squares. for (var r = 0; r < grid.size; r++) { for (var c = 0; c < grid.size; c++) { if (adead.indexOf(grid.get(r, c)) !== -1) grid.set(r, c, null); } } }; function squaresIntersect(a, b) { if (a < b) return b < a + CELL_WIDTH; else return a < b + CELL_WIDTH; } function area(player) { var xDest = player.col * CELL_WIDTH; var yDest = player.row * CELL_WIDTH; if (player.posX === xDest) return Math.abs(player.posY - yDest); else return Math.abs(player.posX - xDest); } },{}],7:[function(require,module,exports){ /* global $ */ var Rolling = require("./rolling.js"); var Color = require("./color.js"); var Grid = require("./grid.js"); var consts = require("./game-consts.js"); var core = require("./game-core.js"); var GRID_SIZE = consts.GRID_SIZE; var CELL_WIDTH = consts.CELL_WIDTH; var SPEED = consts.SPEED; var BORDER_WIDTH = consts.BORDER_WIDTH; var SHADOW_OFFSET = 5; var ANIMATE_FRAMES = 24; var BOUNCE_FRAMES = [8, 4]; var DROP_HEIGHT = 24; var DROP_SPEED = 2; var MIN_BAR_WIDTH = 65; var BAR_HEIGHT = SHADOW_OFFSET + CELL_WIDTH; var BAR_WIDTH = 400; var canvasWidth, canvasHeight, gameWidth, gameHeight, ctx, offctx, offscreenCanvas; $(function () { var canvas = $("#main-ui")[0]; ctx = canvas.getContext('2d'); offscreenCanvas = document.createElement("canvas"); offctx = offscreenCanvas.getContext('2d'); canvasWidth = offscreenCanvas.width = canvas.width = window.innerWidth; canvasHeight = offscreenCanvas.height = canvas.height = window.innerHeight - 20; canvas.style.marginTop = 20 / 2; gameWidth = canvasWidth; gameHeight = canvasHeight - BAR_HEIGHT; }); var allowAnimation = true; var animateGrid, players, allPlayers, playerPortion, portionsRolling, grid, animateTo, offset, user, lagPortion, portionSpeed, zoom, kills, showedDead; grid = new Grid(GRID_SIZE, function(row, col, before, after) { //Keep track of areas. if (before) playerPortion[before.num]--; if (after) playerPortion[after.num]++; //Queue animation if (before === after || !allowAnimation) return; animateGrid.set(row, col, { before: before, after: after, frame: 0 }); }); function init() { animateGrid = new Grid(GRID_SIZE); grid.reset(); players = []; allPlayers = []; playerPortion = []; portionsRolling = []; animateTo = [0, 0]; offset = [0, 0]; user = null; lagPortion = 0; portionSpeed = 0; zoom = 1; kills = 0; showedDead = false; } init(); //Paint methods. function paintGridBorder(ctx) { ctx.fillStyle = 'lightgray'; var gridWidth = CELL_WIDTH * GRID_SIZE; ctx.fillRect(-BORDER_WIDTH, 0, BORDER_WIDTH, gridWidth); ctx.fillRect(-BORDER_WIDTH, -BORDER_WIDTH, gridWidth + BORDER_WIDTH * 2, BORDER_WIDTH); ctx.fillRect(gridWidth, 0, BORDER_WIDTH, gridWidth); ctx.fillRect(-BORDER_WIDTH, gridWidth, gridWidth + BORDER_WIDTH * 2, BORDER_WIDTH); } function paintGrid(ctx) { //Paint background. ctx.fillStyle = "#e2ebf3"; ctx.fillRect(0, 0, CELL_WIDTH * GRID_SIZE, CELL_WIDTH * GRID_SIZE); paintGridBorder(ctx); //paintGridLines(ctx); //Get viewing limits var offsetX = (offset[0] - BORDER_WIDTH); var offsetY = (offset[1] - BORDER_WIDTH); var minRow = Math.max(Math.floor(offsetY / CELL_WIDTH), 0); var minCol = Math.max(Math.floor(offsetX / CELL_WIDTH), 0); var maxRow = Math.min(Math.ceil((offsetY + gameHeight / zoom) / CELL_WIDTH), grid.size); var maxCol = Math.min(Math.ceil((offsetX + gameWidth / zoom) / CELL_WIDTH), grid.size); //Paint occupied areas. (and fading ones). for (var r = minRow; r < maxRow; r++) { for (var c = minCol; c < maxCol; c++) { var p = grid.get(r, c); var x = c * CELL_WIDTH, y = r * CELL_WIDTH, baseColor, shadowColor; var animateSpec = animateGrid.get(r, c); if (allowAnimation && animateSpec) { if (animateSpec.before) //fading animation { var frac = (animateSpec.frame / ANIMATE_FRAMES); var back = new Color(.58, .41, .92, 1); baseColor = animateSpec.before.baseColor.interpolateToString(back, frac); shadowColor = animateSpec.before.shadowColor.interpolateToString(back, frac); } else continue; } else if (p) { baseColor = p.baseColor; shadowColor = p.shadowColor; } else //No animation nor is this player owned. continue; var hasBottom = !grid.isOutOfBounds(r + 1, c); var bottomAnimate = hasBottom && animateGrid.get(r + 1, c); var totalStatic = !bottomAnimate && !animateSpec; var bottomEmpty = totalStatic ? (hasBottom && !grid.get(r + 1, c)) : (!bottomAnimate || (bottomAnimate.after && bottomAnimate.before)); if (hasBottom && ((!!bottomAnimate ^ !!animateSpec) || bottomEmpty)) { ctx.fillStyle = shadowColor.rgbString(); ctx.fillRect(x, y + CELL_WIDTH, CELL_WIDTH + 1, SHADOW_OFFSET); } ctx.fillStyle = baseColor.rgbString(); ctx.fillRect(x, y, CELL_WIDTH + 1, CELL_WIDTH + 1); } } if (!allowAnimation) return; //Paint squares with drop in animation. for (var r = 0; r < grid.size; r++) { for (var c = 0; c < grid.size; c++) { animateSpec = animateGrid.get(r, c); x = c * CELL_WIDTH, y = r * CELL_WIDTH; if (animateSpec && allowAnimation) { var viewable = r >= minRow && r < maxRow && c >= minCol && c < maxCol; if (animateSpec.after && viewable) { //Bouncing the squares. var offsetBounce = getBounceOffset(animateSpec.frame); y -= offsetBounce; shadowColor = animateSpec.after.shadowColor; baseColor = animateSpec.after.baseColor.deriveLumination(-(offsetBounce / DROP_HEIGHT) * .1); ctx.fillStyle = shadowColor.rgbString(); ctx.fillRect(x, y + CELL_WIDTH, CELL_WIDTH, SHADOW_OFFSET); ctx.fillStyle = baseColor.rgbString(); ctx.fillRect(x, y, CELL_WIDTH + 1, CELL_WIDTH + 1); } animateSpec.frame++; if (animateSpec.frame >= ANIMATE_FRAMES) animateGrid.set(r, c, null); } } } } function paintUIBar(ctx) { //UI Bar background ctx.fillStyle = "#24422c"; ctx.fillRect(0, 0, canvasWidth, BAR_HEIGHT); var barOffset; ctx.fillStyle = "white"; ctx.font = "24px Changa"; barOffset = (user && user.name) ? (ctx.measureText(user.name).width + 20) : 0; ctx.fillText(user ? user.name : "", 5, CELL_WIDTH - 5); //Draw filled bar. ctx.fillStyle = "rgba(180, 180, 180, .3)"; ctx.fillRect(barOffset, 0, BAR_WIDTH, BAR_HEIGHT); var barSize = Math.ceil((BAR_WIDTH - MIN_BAR_WIDTH) * lagPortion + MIN_BAR_WIDTH); ctx.fillStyle = user ? user.baseColor.rgbString() : ""; ctx.fillRect(barOffset, 0, barSize, CELL_WIDTH); ctx.fillStyle = user ? user.shadowColor.rgbString() : ""; ctx.fillRect(barOffset, CELL_WIDTH, barSize, SHADOW_OFFSET); //TODO: dont reset kill count and zoom when we request frames. //Percentage ctx.fillStyle = "white"; ctx.font = "18px Changa"; ctx.fillText((lagPortion * 100).toFixed(3) + "%", 5 + barOffset, CELL_WIDTH - 5); //Number of kills var killsText = "Kills: " + kills; var killsOffset = 20 + BAR_WIDTH + barOffset; ctx.fillText(killsText, killsOffset, CELL_WIDTH - 5); //Calcuate rank var sorted = []; players.forEach(function(val) { sorted.push({player: val, portion: playerPortion[val.num]}); }); sorted.sort(function(a, b) { if (a.portion === b.portion) return a.player.num - b.player.num; else return b.portion - a.portion; }); var rank = sorted.findIndex(function(val) {return val.player === user}); ctx.fillText("Rank: " + (rank === -1 ? "--" : rank + 1) + " of " + sorted.length, ctx.measureText(killsText).width + killsOffset + 20, CELL_WIDTH - 5); //Show leaderboard. var maxPortion = sorted[0] ? sorted[0].portion : 0; var leaderboardNum = Math.min(5, sorted.length); for (var i = 0; i < leaderboardNum; i++) { var player = sorted[i].player; var name = player.name || "Unnamed"; var portion = sorted[i].portion / maxPortion; var nameWidth = ctx.measureText(name).width; barSize = Math.ceil((BAR_WIDTH - MIN_BAR_WIDTH) * portion + MIN_BAR_WIDTH); var barX = canvasWidth - barSize; var barY = BAR_HEIGHT * (i + 1); var offset = i == 0 ? 10 : 0; ctx.fillStyle = 'rgba(10, 10, 10, .3)'; ctx.fillRect(barX - 10, barY + 10 - offset, barSize + 10, BAR_HEIGHT + offset); ctx.fillStyle = player.baseColor.rgbString(); ctx.fillRect(barX, barY, barSize, CELL_WIDTH); ctx.fillStyle = player.shadowColor.rgbString(); ctx.fillRect(barX, barY + CELL_WIDTH, barSize, SHADOW_OFFSET); ctx.fillStyle = "black"; ctx.fillText(name, barX - nameWidth - 10, barY + 27); var percentage = (sorted[i].portion / GRID_SIZE / GRID_SIZE * 100).toFixed(3) + "%"; var metrics = ctx.measureText(percentage); ctx.fillStyle = "white"; ctx.fillText(percentage, barX + 5, barY + CELL_WIDTH - 5); } } function paint(ctx) { ctx.fillStyle = 'whitesmoke'; ctx.fillRect(0, 0, canvasWidth, canvasHeight); //Move grid to viewport as said with the offsets, below the stats ctx.save(); ctx.translate(0, BAR_HEIGHT); ctx.beginPath(); ctx.rect(0, 0, gameWidth, gameHeight); ctx.clip(); //Zoom in/out based on player stats. ctx.scale(zoom, zoom); ctx.translate(-offset[0] + BORDER_WIDTH, -offset[1] + BORDER_WIDTH); paintGrid(ctx); players.forEach(function (p) { var fr = p.waitLag; if (fr < ANIMATE_FRAMES) p.render(ctx, fr / ANIMATE_FRAMES); else p.render(ctx); }); //Reset transform to paint fixed UI elements ctx.restore(); paintUIBar(ctx); if ((!user || user.dead) && !showedDead) { showedDead = true; console.log("You died!"); //return; } } function paintDoubleBuff() { paint(offctx); ctx.drawImage(offscreenCanvas, 0, 0); } function update() { //Change grid offsets. for (var i = 0; i <= 1; i++) { if (animateTo[i] !== offset[i]) { if (allowAnimation) { var delta = animateTo[i] - offset[i]; var dir = Math.sign(delta); var mag = Math.min(SPEED, Math.abs(delta)); offset[i] += dir * mag; } else offset[i] = animateTo[i]; } } //Change area percentage var userPortion; if (user) userPortion = playerPortion[user.num] / (GRID_SIZE * GRID_SIZE); else userPortion = 0; if (lagPortion !== userPortion) { if (allowAnimation) { delta = userPortion - lagPortion; dir = Math.sign(delta); mag = Math.min(Math.abs(portionSpeed), Math.abs(delta)); lagPortion += dir * mag; } else lagPortion = userPortion; } //Zoom goes from 1 to .5, decreasing as portion goes up. TODO: maybe can modify this? zoom = 1 / (lagPortion + 1); //Update user's portions and top ranks. portionSpeed = Math.abs(userPortion - lagPortion) / ANIMATE_FRAMES; var dead = []; core.updateFrame(grid, players, dead, function addKill(killer, other) { if (players[killer] === user && killer !== other) kills++; }); dead.forEach(function(val) { console.log(val.name || "Unnamed" + " is dead"); delete allPlayers[val.num]; delete portionsRolling[val.num]; }); //TODO: animate player is dead. (maybe explosion?), and tail rewinds itself. if (user) centerOnPlayer(user, animateTo); } //Helper methods. function centerOnPlayer(player, pos) { var xOff = Math.floor(player.posX - (gameWidth / zoom - CELL_WIDTH) / 2); var yOff = Math.floor(player.posY - (gameHeight / zoom - CELL_WIDTH) / 2); var gridWidth = grid.size * CELL_WIDTH + BORDER_WIDTH * 2; pos[0] = Math.max(Math.min(xOff, gridWidth + BAR_WIDTH + 100 - gameWidth / zoom), 0); pos[1] = Math.max(Math.min(yOff, gridWidth - gameHeight / zoom), 0); } function getBounceOffset(frame) { var offsetBounce = ANIMATE_FRAMES; var bounceNum = BOUNCE_FRAMES.length - 1; while (bounceNum >= 0 && frame < offsetBounce - BOUNCE_FRAMES[bounceNum]) { offsetBounce -= BOUNCE_FRAMES[bounceNum]; bounceNum--; } if (bounceNum === -1) { return (offsetBounce - frame) * DROP_SPEED; } else { offsetBounce -= BOUNCE_FRAMES[bounceNum]; frame = frame - offsetBounce; var midFrame = BOUNCE_FRAMES[bounceNum] / 2; if (frame >= midFrame) return (BOUNCE_FRAMES[bounceNum] - frame) * DROP_SPEED; else return frame * DROP_SPEED; } } module.exports = exports = { addPlayer: function(player) { if (allPlayers[player.num]) return; //Already added. allPlayers[player.num] = players[players.length] = player; playerPortion[player.num] = 0; portionsRolling = new Rolling(0, .2); return players.length - 1; }, getPlayer: function(ind) { if (ind < 0 || ind >= players.length) throw new RangeError("Player index out of bounds (" + ind + ")."); return players[ind]; }, getPlayerFromNum: function(num) { return allPlayers[num]; }, playerSize: function() { return players.length; }, setUser: function(player) { user = player; centerOnPlayer(user, offset); }, incrementKill: function() { kills++; }, reset: function() { init(); }, paint: paintDoubleBuff, update: update }; Object.defineProperties(exports, { allowAnimation: { get: function() { return allowAnimation; }, set: function(val) { allowAnimation = !!val; }, enumerable: true }, grid: { get: function() { return grid; }, enumerable: true } }); },{"./color.js":3,"./game-consts.js":5,"./game-core.js":6,"./grid.js":8,"./rolling.js":57}],8:[function(require,module,exports){ function Grid(size, changeCallback) { var grid = new Array(size); var modified = false; var data = { grid: grid, size: size }; this.get = function(row, col) { if (isOutOfBounds(data, row, col)) throw new RangeError("Row or Column value out of bounds"); return grid[row] && grid[row][col]; } this.set = function(row, col, value) { if (isOutOfBounds(data, row, col)) throw new RangeError("Row or Column value out of bounds"); if (!grid[row]) grid[row] = new Array(size); var before = grid[row][col]; grid[row][col] = value; if (typeof changeCallback === "function") changeCallback(row, col, before, value); modified = true; return before; } this.reset = function() { if (modified) { grid = new Array(size); modified = false; } } this.isOutOfBounds = isOutOfBounds.bind(this, data); Object.defineProperty(this, "size", { get: function() {return size; }, enumerable: true }); } function isOutOfBounds(data, row, col) { return row < 0 || row >= data.size || col < 0 || col >= data.size; } module.exports = Grid; },{}],9:[function(require,module,exports){ /** * Module dependencies. */ var url = require('./url'); var parser = require('socket.io-parser'); var Manager = require('./manager'); var debug = require('debug')('socket.io-client'); /** * Module exports. */ module.exports = exports = lookup; /** * Managers cache. */ var cache = exports.managers = {}; /** * Looks up an existing `Manager` for multiplexing. * If the user summons: * * `io('http://localhost/a');` * `io('http://localhost/b');` * * We reuse the existing instance based on same scheme/port/host, * and we initialize sockets for each namespace. * * @api public */ function lookup (uri, opts) { if (typeof uri === 'object') { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url(uri); var source = parsed.source; var id = parsed.id; var path = parsed.path; var sameNamespace = cache[id] && path in cache[id].nsps; var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace; var io; if (newConnection) { debug('ignoring socket cache for %s', source); io = Manager(source, opts); } else { if (!cache[id]) { debug('new io instance for %s', source); cache[id] = Manager(source, opts); } io = cache[id]; } if (parsed.query && !opts.query) { opts.query = parsed.query; } else if (opts && 'object' === typeof opts.query) { opts.query = encodeQueryString(opts.query); } return io.socket(parsed.path, opts); } /** * Helper method to parse query objects to string. * @param {object} query * @returns {string} */ function encodeQueryString (obj) { var str = []; for (var p in obj) { if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } } return str.join('&'); } /** * Protocol version. * * @api public */ exports.protocol = parser.protocol; /** * `connect`. * * @param {String} uri * @api public */ exports.connect = lookup; /** * Expose constructors for standalone build. * * @api public */ exports.Manager = require('./manager'); exports.Socket = require('./socket'); },{"./manager":10,"./socket":12,"./url":13,"debug":17,"socket.io-parser":47}],10:[function(require,module,exports){ /** * Module dependencies. */ var eio = require('engine.io-client'); var Socket = require('./socket'); var Emitter = require('component-emitter'); var parser = require('socket.io-parser'); var on = require('./on'); var bind = require('component-bind'); var debug = require('debug')('socket.io-client:manager'); var indexOf = require('indexof'); var Backoff = require('backo2'); /** * IE6+ hasOwnProperty */ var has = Object.prototype.hasOwnProperty; /** * Module exports */ module.exports = Manager; /** * `Manager` constructor. * * @param {String} engine instance or engine uri/opts * @param {Object} options * @api public */ function Manager (uri, opts) { if (!(this instanceof Manager)) return new Manager(uri, opts); if (uri && ('object' === typeof uri)) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || '/socket.io'; this.nsps = {}; this.subs = []; this.opts = opts; this.reconnection(opts.reconnection !== false); this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); this.reconnectionDelay(opts.reconnectionDelay || 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); this.randomizationFactor(opts.randomizationFactor || 0.5); this.backoff = new Backoff({ min: this.reconnectionDelay(), max: this.reconnectionDelayMax(), jitter: this.randomizationFactor() }); this.timeout(null == opts.timeout ? 20000 : opts.timeout); this.readyState = 'closed'; this.uri = uri; this.connecting = []; this.lastPing = null; this.encoding = false; this.packetBuffer = []; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); this.autoConnect = opts.autoConnect !== false; if (this.autoConnect) this.open(); } /** * Propagate given event to sockets and emit on `this` * * @api private */ Manager.prototype.emitAll = function () { this.emit.apply(this, arguments); for (var nsp in this.nsps) { if (has.call(this.nsps, nsp)) { this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); } } }; /** * Update `socket.id` of all sockets * * @api private */ Manager.prototype.updateSocketIds = function () { for (var nsp in this.nsps) { if (has.call(this.nsps, nsp)) { this.nsps[nsp].id = this.engine.id; } } }; /** * Mix in `Emitter`. */ Emitter(Manager.prototype); /** * Sets the `reconnection` config. * * @param {Boolean} true/false if it should automatically reconnect * @return {Manager} self or value * @api public */ Manager.prototype.reconnection = function (v) { if (!arguments.length) return this._reconnection; this._reconnection = !!v; return this; }; /** * Sets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionAttempts = function (v) { if (!arguments.length) return this._reconnectionAttempts; this._reconnectionAttempts = v; return this; }; /** * Sets the delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelay = function (v) { if (!arguments.length) return this._reconnectionDelay; this._reconnectionDelay = v; this.backoff && this.backoff.setMin(v); return this; }; Manager.prototype.randomizationFactor = function (v) { if (!arguments.length) return this._randomizationFactor; this._randomizationFactor = v; this.backoff && this.backoff.setJitter(v); return this; }; /** * Sets the maximum delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelayMax = function (v) { if (!arguments.length) return this._reconnectionDelayMax; this._reconnectionDelayMax = v; this.backoff && this.backoff.setMax(v); return this; }; /** * Sets the connection timeout. `false` to disable * * @return {Manager} self or value * @api public */ Manager.prototype.timeout = function (v) { if (!arguments.length) return this._timeout; this._timeout = v; return this; }; /** * Starts trying to reconnect if reconnection is enabled and we have not * started reconnecting yet * * @api private */ Manager.prototype.maybeReconnectOnOpen = function () { // Only try to reconnect if it's the first time we're connecting if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { // keeps reconnection from firing twice for the same reconnection loop this.reconnect(); } }; /** * Sets the current transport `socket`. * * @param {Function} optional, callback * @return {Manager} self * @api public */ Manager.prototype.open = Manager.prototype.connect = function (fn, opts) { debug('readyState %s', this.readyState); if (~this.readyState.indexOf('open')) return this; debug('opening %s', this.uri); this.engine = eio(this.uri, this.opts); var socket = this.engine; var self = this; this.readyState = 'opening'; this.skipReconnect = false; // emit `open` var openSub = on(socket, 'open', function () { self.onopen(); fn && fn(); }); // emit `connect_error` var errorSub = on(socket, 'error', function (data) { debug('connect_error'); self.cleanup(); self.readyState = 'closed'; self.emitAll('connect_error', data); if (fn) { var err = new Error('Connection error'); err.data = data; fn(err); } else { // Only do this if there is no fn to handle the error self.maybeReconnectOnOpen(); } }); // emit `connect_timeout` if (false !== this._timeout) { var timeout = this._timeout; debug('connect attempt will timeout after %d', timeout); // set timer var timer = setTimeout(function () { debug('connect attempt timed out after %d', timeout); openSub.destroy(); socket.close(); socket.emit('error', 'timeout'); self.emitAll('connect_timeout', timeout); }, timeout); this.subs.push({ destroy: function () { clearTimeout(timer); } }); } this.subs.push(openSub); this.subs.push(errorSub); return this; }; /** * Called upon transport open. * * @api private */ Manager.prototype.onopen = function () { debug('open'); // clear old subs this.cleanup(); // mark as open this.readyState = 'open'; this.emit('open'); // add new subs var socket = this.engine; this.subs.push(on(socket, 'data', bind(this, 'ondata'))); this.subs.push(on(socket, 'ping', bind(this, 'onping'))); this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); this.subs.push(on(socket, 'error', bind(this, 'onerror'))); this.subs.push(on(socket, 'close', bind(this, 'onclose'))); this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); }; /** * Called upon a ping. * * @api private */ Manager.prototype.onping = function () { this.lastPing = new Date(); this.emitAll('ping'); }; /** * Called upon a packet. * * @api private */ Manager.prototype.onpong = function () { this.emitAll('pong', new Date() - this.lastPing); }; /** * Called with data. * * @api private */ Manager.prototype.ondata = function (data) { this.decoder.add(data); }; /** * Called when parser fully decodes a packet. * * @api private */ Manager.prototype.ondecoded = function (packet) { this.emit('packet', packet); }; /** * Called upon socket error. * * @api private */ Manager.prototype.onerror = function (err) { debug('error', err); this.emitAll('error', err); }; /** * Creates a new socket for the given `nsp`. * * @return {Socket} * @api public */ Manager.prototype.socket = function (nsp, opts) { var socket = this.nsps[nsp]; if (!socket) { socket = new Socket(this, nsp, opts); this.nsps[nsp] = socket; var self = this; socket.on('connecting', onConnecting); socket.on('connect', function () { socket.id = self.engine.id; }); if (this.autoConnect) { // manually call here since connecting evnet is fired before listening onConnecting(); } } function onConnecting () { if (!~indexOf(self.connecting, socket)) { self.connecting.push(socket); } } return socket; }; /** * Called upon a socket close. * * @param {Socket} socket */ Manager.prototype.destroy = function (socket) { var index = indexOf(this.connecting, socket); if (~index) this.connecting.splice(index, 1); if (this.connecting.length) return; this.close(); }; /** * Writes a packet. * * @param {Object} packet * @api private */ Manager.prototype.packet = function (packet) { debug('writing packet %j', packet); var self = this; if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; if (!self.encoding) { // encode, then write to engine with result self.encoding = true; this.encoder.encode(packet, function (encodedPackets) { for (var i = 0; i < encodedPackets.length; i++) { self.engine.write(encodedPackets[i], packet.options); } self.encoding = false; self.processPacketQueue(); }); } else { // add packet to the queue self.packetBuffer.push(packet); } }; /** * If packet buffer is non-empty, begins encoding the * next packet in line. * * @api private */ Manager.prototype.processPacketQueue = function () { if (this.packetBuffer.length > 0 && !this.encoding) { var pack = this.packetBuffer.shift(); this.packet(pack); } }; /** * Clean up transport subscriptions and packet buffer. * * @api private */ Manager.prototype.cleanup = function () { debug('cleanup'); var subsLength = this.subs.length; for (var i = 0; i < subsLength; i++) { var sub = this.subs.shift(); sub.destroy(); } this.packetBuffer = []; this.encoding = false; this.lastPing = null; this.decoder.destroy(); }; /** * Close the current socket. * * @api private */ Manager.prototype.close = Manager.prototype.disconnect = function () { debug('disconnect'); this.skipReconnect = true; this.reconnecting = false; if ('opening' === this.readyState) { // `onclose` will not fire because // an open event never happened this.cleanup(); } this.backoff.reset(); this.readyState = 'closed'; if (this.engine) this.engine.close(); }; /** * Called upon engine close. * * @api private */ Manager.prototype.onclose = function (reason) { debug('onclose'); this.cleanup(); this.backoff.reset(); this.readyState = 'closed'; this.emit('close', reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } }; /** * Attempt a reconnection. * * @api private */ Manager.prototype.reconnect = function () { if (this.reconnecting || this.skipReconnect) return this; var self = this; if (this.backoff.attempts >= this._reconnectionAttempts) { debug('reconnect failed'); this.backoff.reset(); this.emitAll('reconnect_failed'); this.reconnecting = false; } else { var delay = this.backoff.duration(); debug('will wait %dms before reconnect attempt', delay); this.reconnecting = true; var timer = setTimeout(function () { if (self.skipReconnect) return; debug('attempting reconnect'); self.emitAll('reconnect_attempt', self.backoff.attempts); self.emitAll('reconnecting', self.backoff.attempts); // check again for the case socket closed in above events if (self.skipReconnect) return; self.open(function (err) { if (err) { debug('reconnect attempt error'); self.reconnecting = false; self.reconnect(); self.emitAll('reconnect_error', err.data); } else { debug('reconnect success'); self.onreconnect(); } }); }, delay); this.subs.push({ destroy: function () { clearTimeout(timer); } }); } }; /** * Called upon successful reconnect. * * @api private */ Manager.prototype.onreconnect = function () { var attempt = this.backoff.attempts; this.reconnecting = false; this.backoff.reset(); this.updateSocketIds(); this.emitAll('reconnect', attempt); }; },{"./on":11,"./socket":12,"backo2":14,"component-bind":15,"component-emitter":16,"debug":17,"engine.io-client":20,"indexof":44,"socket.io-parser":47}],11:[function(require,module,exports){ /** * Module exports. */ module.exports = on; /** * Helper for subscriptions. * * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` * @param {String} event name * @param {Function} callback * @api public */ function on (obj, ev, fn) { obj.on(ev, fn); return { destroy: function () { obj.removeListener(ev, fn); } }; } },{}],12:[function(require,module,exports){ /** * Module dependencies. */ var parser = require('socket.io-parser'); var Emitter = require('component-emitter'); var toArray = require('to-array'); var on = require('./on'); var bind = require('component-bind'); var debug = require('debug')('socket.io-client:socket'); var hasBin = require('has-binary'); /** * Module exports. */ module.exports = exports = Socket; /** * Internal events (blacklisted). * These events can't be emitted by the user. * * @api private */ var events = { connect: 1, connect_error: 1, connect_timeout: 1, connecting: 1, disconnect: 1, error: 1, reconnect: 1, reconnect_attempt: 1, reconnect_failed: 1, reconnect_error: 1, reconnecting: 1, ping: 1, pong: 1 }; /** * Shortcut to `Emitter#emit`. */ var emit = Emitter.prototype.emit; /** * `Socket` constructor. * * @api public */ function Socket (io, nsp, opts) { this.io = io; this.nsp = nsp; this.json = this; // compat this.ids = 0; this.acks = {}; this.receiveBuffer = []; this.sendBuffer = []; this.connected = false; this.disconnected = true; if (opts && opts.query) { this.query = opts.query; } if (this.io.autoConnect) this.open(); } /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Subscribe to open, close and packet events * * @api private */ Socket.prototype.subEvents = function () { if (this.subs) return; var io = this.io; this.subs = [ on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose')) ]; }; /** * "Opens" the socket. * * @api public */ Socket.prototype.open = Socket.prototype.connect = function () { if (this.connected) return this; this.subEvents(); this.io.open(); // ensure open if ('open' === this.io.readyState) this.onopen(); this.emit('connecting'); return this; }; /** * Sends a `message` event. * * @return {Socket} self * @api public */ Socket.prototype.send = function () { var args = toArray(arguments); args.unshift('message'); this.emit.apply(this, args); return this; }; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self * @api public */ Socket.prototype.emit = function (ev) { if (events.hasOwnProperty(ev)) { emit.apply(this, arguments); return this; } var args = toArray(arguments); var parserType = parser.EVENT; // default if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary var packet = { type: parserType, data: args }; packet.options = {}; packet.options.compress = !this.flags || false !== this.flags.compress; // event ack callback if ('function' === typeof args[args.length - 1]) { debug('emitting packet with ack id %d', this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } if (this.connected) { this.packet(packet); } else { this.sendBuffer.push(packet); } delete this.flags; return this; }; /** * Sends a packet. * * @param {Object} packet * @api private */ Socket.prototype.packet = function (packet) { packet.nsp = this.nsp; this.io.packet(packet); }; /** * Called upon engine `open`. * * @api private */ Socket.prototype.onopen = function () { debug('transport is open - connecting'); // write connect packet if necessary if ('/' !== this.nsp) { if (this.query) { this.packet({type: parser.CONNECT, query: this.query}); } else { this.packet({type: parser.CONNECT}); } } }; /** * Called upon engine `close`. * * @param {String} reason * @api private */ Socket.prototype.onclose = function (reason) { debug('close (%s)', reason); this.connected = false; this.disconnected = true; delete this.id; this.emit('disconnect', reason); }; /** * Called with socket packet. * * @param {Object} packet * @api private */ Socket.prototype.onpacket = function (packet) { if (packet.nsp !== this.nsp) return; switch (packet.type) { case parser.CONNECT: this.onconnect(); break; case parser.EVENT: this.onevent(packet); break; case parser.BINARY_EVENT: this.onevent(packet); break; case parser.ACK: this.onack(packet); break; case parser.BINARY_ACK: this.onack(packet); break; case parser.DISCONNECT: this.ondisconnect(); break; case parser.ERROR: this.emit('error', packet.data); break; } }; /** * Called upon a server event. * * @param {Object} packet * @api private */ Socket.prototype.onevent = function (packet) { var args = packet.data || []; debug('emitting event %j', args); if (null != packet.id) { debug('attaching ack callback to event'); args.push(this.ack(packet.id)); } if (this.connected) { emit.apply(this, args); } else { this.receiveBuffer.push(args); } }; /** * Produces an ack callback to emit with an event. * * @api private */ Socket.prototype.ack = function (id) { var self = this; var sent = false; return function () { // prevent double callbacks if (sent) return; sent = true; var args = toArray(arguments); debug('sending ack %j', args); var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK; self.packet({ type: type, id: id, data: args }); }; }; /** * Called upon a server acknowlegement. * * @param {Object} packet * @api private */ Socket.prototype.onack = function (packet) { var ack = this.acks[packet.id]; if ('function' === typeof ack) { debug('calling ack %s with %j', packet.id, packet.data); ack.apply(this, packet.data); delete this.acks[packet.id]; } else { debug('bad ack %s', packet.id); } }; /** * Called upon server connect. * * @api private */ Socket.prototype.onconnect = function () { this.connected = true; this.disconnected = false; this.emit('connect'); this.emitBuffered(); }; /** * Emit buffered events (received and emitted). * * @api private */ Socket.prototype.emitBuffered = function () { var i; for (i = 0; i < this.receiveBuffer.length; i++) { emit.apply(this, this.receiveBuffer[i]); } this.receiveBuffer = []; for (i = 0; i < this.sendBuffer.length; i++) { this.packet(this.sendBuffer[i]); } this.sendBuffer = []; }; /** * Called upon server disconnect. * * @api private */ Socket.prototype.ondisconnect = function () { debug('server disconnect (%s)', this.nsp); this.destroy(); this.onclose('io server disconnect'); }; /** * Called upon forced client/server side disconnections, * this method ensures the manager stops tracking us and * that reconnections don't get triggered for this. * * @api private. */ Socket.prototype.destroy = function () { if (this.subs) { // clean subscriptions to avoid reconnections for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } this.subs = null; } this.io.destroy(this); }; /** * Disconnects the socket manually. * * @return {Socket} self * @api public */ Socket.prototype.close = Socket.prototype.disconnect = function () { if (this.connected) { debug('performing disconnect (%s)', this.nsp); this.packet({ type: parser.DISCONNECT }); } // remove socket from pool this.destroy(); if (this.connected) { // fire events this.onclose('io client disconnect'); } return this; }; /** * Sets the compress flag. * * @param {Boolean} if `true`, compresses the sending data * @return {Socket} self * @api public */ Socket.prototype.compress = function (compress) { this.flags = this.flags || {}; this.flags.compress = compress; return this; }; },{"./on":11,"component-bind":15,"component-emitter":16,"debug":17,"has-binary":42,"socket.io-parser":47,"to-array":55}],13:[function(require,module,exports){ (function (global){ /** * Module dependencies. */ var parseuri = require('parseuri'); var debug = require('debug')('socket.io-client:url'); /** * Module exports. */ module.exports = url; /** * URL parser. * * @param {String} url * @param {Object} An object meant to mimic window.location. * Defaults to window.location. * @api public */ function url (uri, loc) { var obj = uri; // default to window.location loc = loc || global.location; if (null == uri) uri = loc.protocol + '//' + loc.host; // relative path support if ('string' === typeof uri) { if ('/' === uri.charAt(0)) { if ('/' === uri.charAt(1)) { uri = loc.protocol + uri; } else { uri = loc.host + uri; } } if (!/^(https?|wss?):\/\//.test(uri)) { debug('protocol-less url %s', uri); if ('undefined' !== typeof loc) { uri = loc.protocol + '//' + uri; } else { uri = 'https://' + uri; } } // parse debug('parse %s', uri); obj = parseuri(uri); } // make sure we treat `localhost:80` and `localhost` equally if (!obj.port) { if (/^(http|ws)$/.test(obj.protocol)) { obj.port = '80'; } else if (/^(http|ws)s$/.test(obj.protocol)) { obj.port = '443'; } } obj.path = obj.path || '/'; var ipv6 = obj.host.indexOf(':') !== -1; var host = ipv6 ? '[' + obj.host + ']' : obj.host; // define unique id obj.id = obj.protocol + '://' + host + ':' + obj.port; // define href obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port)); return obj; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"debug":17,"parseuri":45}],14:[function(require,module,exports){ /** * Expose `Backoff`. */ module.exports = Backoff; /** * Initialize backoff timer with `opts`. * * - `min` initial timeout in milliseconds [100] * - `max` max timeout [10000] * - `jitter` [0] * - `factor` [2] * * @param {Object} opts * @api public */ function Backoff(opts) { opts = opts || {}; this.ms = opts.min || 100; this.max = opts.max || 10000; this.factor = opts.factor || 2; this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; this.attempts = 0; } /** * Return the backoff duration. * * @return {Number} * @api public */ Backoff.prototype.duration = function(){ var ms = this.ms * Math.pow(this.factor, this.attempts++); if (this.jitter) { var rand = Math.random(); var deviation = Math.floor(rand * this.jitter * ms); ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; } return Math.min(ms, this.max) | 0; }; /** * Reset the number of attempts. * * @api public */ Backoff.prototype.reset = function(){ this.attempts = 0; }; /** * Set the minimum duration * * @api public */ Backoff.prototype.setMin = function(min){ this.ms = min; }; /** * Set the maximum duration * * @api public */ Backoff.prototype.setMax = function(max){ this.max = max; }; /** * Set the jitter * * @api public */ Backoff.prototype.setJitter = function(jitter){ this.jitter = jitter; }; },{}],15:[function(require,module,exports){ /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; },{}],16:[function(require,module,exports){ /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],17:[function(require,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } }).call(this,require('_process')) },{"./debug":18,"_process":2}],18:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":19}],19:[function(require,module,exports){ /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } },{}],20:[function(require,module,exports){ module.exports = require('./lib/index'); },{"./lib/index":21}],21:[function(require,module,exports){ module.exports = require('./socket'); /** * Exports parser * * @api public * */ module.exports.parser = require('engine.io-parser'); },{"./socket":22,"engine.io-parser":31}],22:[function(require,module,exports){ (function (global){ /** * Module dependencies. */ var transports = require('./transports/index'); var Emitter = require('component-emitter'); var debug = require('debug')('engine.io-client:socket'); var index = require('indexof'); var parser = require('engine.io-parser'); var parseuri = require('parseuri'); var parsejson = require('parsejson'); var parseqs = require('parseqs'); /** * Module exports. */ module.exports = Socket; /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; this.forceNode = !!opts.forceNode; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } if (opts.localAddress) { this.localAddress = opts.localAddress; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = require('./transport'); Socket.transports = require('./transports/index'); Socket.parser = require('engine.io-parser'); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized, perMessageDeflate: this.perMessageDeflate, extraHeaders: this.extraHeaders, forceNode: this.forceNode, localAddress: this.localAddress }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function () { self.onDrain(); }) .on('packet', function (packet) { self.onPacket(packet); }) .on('error', function (e) { self.onError(e); }) .on('close', function () { self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose () { onerror('transport closed'); } // When the socket is closed while we're probing function onclose () { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api private */ Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); }); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close () { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose () { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade () { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transport":23,"./transports/index":24,"component-emitter":16,"debug":17,"engine.io-parser":31,"indexof":44,"parsejson":39,"parseqs":40,"parseuri":45}],23:[function(require,module,exports){ /** * Module dependencies. */ var parser = require('engine.io-parser'); var Emitter = require('component-emitter'); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.forceNode = opts.forceNode; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.localAddress = opts.localAddress; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' === this.readyState || '' === this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function (packets) { if ('open' === this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; },{"component-emitter":16,"engine.io-parser":31}],24:[function(require,module,exports){ (function (global){ /** * Module dependencies */ var XMLHttpRequest = require('xmlhttprequest-ssl'); var XHR = require('./polling-xhr'); var JSONP = require('./polling-jsonp'); var websocket = require('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling-jsonp":25,"./polling-xhr":26,"./websocket":28,"xmlhttprequest-ssl":29}],25:[function(require,module,exports){ (function (global){ /** * Module requirements. */ var Polling = require('./polling'); var inherit = require('component-inherit'); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function (e) { self.onError('jsonp poll error', e); }; var insertAt = document.getElementsByTagName('script')[0]; if (insertAt) { insertAt.parentNode.insertBefore(script, insertAt); } else { (document.head || document.body).appendChild(script); } this.script = script; var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '