Skip to content

Instantly share code, notes, and snippets.

@kumavis kumavis/index.js
Last active Aug 29, 2015

Embed
What would you like to do?
requirebin sketch
var rtcDataStream = require('rtc-data-stream')
var quickconnect = require('rtc-quickconnect')
var generateName = require('sillyname');
// setup DOM
var output = document.createElement('textarea')
output.style.width = "100%"
output.style.height = "80%"
output.style.resize = "none"
document.body.appendChild(output)
document.body.appendChild(document.createElement('br'))
var input = document.createElement('input')
input.style.width = "100%"
input.style.height = "20%"
input.placeholder = "type here to chat..."
document.body.appendChild(input)
input.addEventListener('keydown', function() {
if (event.keyCode == 13) {
var message = input.value
input.value = ""
broadcast(message)
showMessage("me", message)
event.preventDefault()
event.stopPropagation()
}
});
function showMessage(origin, message) {
if (output.value) output.value += '\n'
if (origin) output.value += origin + ': '
output.value += message
output.scrollTop = 99999
}
// setup Network
var peers = []
quickconnect('http://rtc.io/switchboard', { room: 'rtc-data-stream-demo' })
.createDataChannel('chat')
.on('channel:opened:chat', function(id, dc) {
var username = generateName()
username = username.split(' ').join('_')
showMessage(null, username + ' joined...')
var rtc = rtcDataStream(dc);
rtc.on('data', function(data) {
showMessage(username, data)
})
peers.push(rtc)
});
function broadcast(message) {
console.log(message)
peers.forEach(function(rtc){
rtc.write(message)
})
}
require=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<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new Error("First argument needs to be a number, array or string.");var buf;if(TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.byteLength=function(str,encoding){var ret;str=str.toString();switch(encoding||"utf8"){case"hex":ret=str.length/2;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"ascii":case"binary":case"raw":ret=str.length;break;case"base64":ret=base64ToBytes(str).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;default:throw new Error("Unknown encoding")}return ret};Buffer.concat=function(list,totalLength){assert(isArray(list),"Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.compare=function(a,b){assert(Buffer.isBuffer(a)&&Buffer.isBuffer(b),"Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y){return-1}if(y<x){return 1}return 0};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;assert(strLen%2===0,"Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);assert(!isNaN(byte),"Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toString=function(encoding,start,end){var self=this;encoding=String(encoding||"utf8").toLowerCase();start=Number(start)||0;end=end===undefined?self.length:Number(end);if(end===start)return"";var ret;switch(encoding){case"hex":ret=hexSlice(self,start,end);break;case"utf8":case"utf-8":ret=utf8Slice(self,start,end);break;case"ascii":ret=asciiSlice(self,start,end);break;case"binary":ret=binarySlice(self,start,end);break;case"base64":ret=base64Slice(self,start,end);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leSlice(self,start,end);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.equals=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.compare=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;assert(end>=start,"sourceEnd < sourceStart");assert(target_start>=0&&target_start<target.length,"targetStart out of bounds");assert(start>=0&&start<source.length,"sourceStart out of bounds");assert(end>=0&&end<=source.length,"sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<100||!TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;return this[offset]};function readUInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){val=buf[offset];if(offset+1<len)val|=buf[offset+1]<<8}else{val=buf[offset]<<8;if(offset+1<len)val|=buf[offset+1]}return val}Buffer.prototype.readUInt16LE=function(offset,noAssert){return readUInt16(this,offset,true,noAssert)};Buffer.prototype.readUInt16BE=function(offset,noAssert){return readUInt16(this,offset,false,noAssert)};function readUInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){if(offset+2<len)val=buf[offset+2]<<16;if(offset+1<len)val|=buf[offset+1]<<8;val|=buf[offset];if(offset+3<len)val=val+(buf[offset+3]<<24>>>0)}else{if(offset+1<len)val=buf[offset+1]<<16;if(offset+2<len)val|=buf[offset+2]<<8;if(offset+3<len)val|=buf[offset+3];val=val+(buf[offset]<<24>>>0)}return val}Buffer.prototype.readUInt32LE=function(offset,noAssert){return readUInt32(this,offset,true,noAssert)};Buffer.prototype.readUInt32BE=function(offset,noAssert){return readUInt32(this,offset,false,noAssert)};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;var neg=this[offset]&128;if(neg)return(255-this[offset]+1)*-1;else return this[offset]};function readInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt16(buf,offset,littleEndian,true);var neg=val&32768;if(neg)return(65535-val+1)*-1;else return val}Buffer.prototype.readInt16LE=function(offset,noAssert){return readInt16(this,offset,true,noAssert)};Buffer.prototype.readInt16BE=function(offset,noAssert){return readInt16(this,offset,false,noAssert)};function readInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt32(buf,offset,littleEndian,true);var neg=val&2147483648;if(neg)return(4294967295-val+1)*-1;else return val}Buffer.prototype.readInt32LE=function(offset,noAssert){return readInt32(this,offset,true,noAssert)};Buffer.prototype.readInt32BE=function(offset,noAssert){return readInt32(this,offset,false,noAssert)};function readFloat(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+3<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,23,4)}Buffer.prototype.readFloatLE=function(offset,noAssert){return readFloat(this,offset,true,noAssert)};Buffer.prototype.readFloatBE=function(offset,noAssert){return readFloat(this,offset,false,noAssert)};function readDouble(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+7<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,52,8)}Buffer.prototype.readDoubleLE=function(offset,noAssert){return readDouble(this,offset,true,noAssert)};Buffer.prototype.readDoubleBE=function(offset,noAssert){return readDouble(this,offset,false,noAssert)};Buffer.prototype.writeUInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"trying to write beyond buffer length");verifuint(value,255)}if(offset>=this.length)return;this[offset]=value;return offset+1};function writeUInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"trying to write beyond buffer length");verifuint(value,65535)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}return offset+2}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return writeUInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return writeUInt16(this,value,offset,false,noAssert)};function writeUInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"trying to write beyond buffer length");verifuint(value,4294967295)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}return offset+4}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return writeUInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return writeUInt32(this,value,offset,false,noAssert)};Buffer.prototype.writeInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to write beyond buffer length");verifsint(value,127,-128)}if(offset>=this.length)return;if(value>=0)this.writeUInt8(value,offset,noAssert);else this.writeUInt8(255+value+1,offset,noAssert);return offset+1};function writeInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to write beyond buffer length");verifsint(value,32767,-32768)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt16(buf,value,offset,littleEndian,noAssert);else writeUInt16(buf,65535+value+1,offset,littleEndian,noAssert);return offset+2}Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return writeInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return writeInt16(this,value,offset,false,noAssert)};function writeInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifsint(value,2147483647,-2147483648)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt32(buf,value,offset,littleEndian,noAssert);else writeUInt32(buf,4294967295+value+1,offset,littleEndian,noAssert);return offset+4}Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return writeInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return writeInt32(this,value,offset,false,noAssert)};function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,3.4028234663852886e38,-3.4028234663852886e38)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+7<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,1.7976931348623157e308,-1.7976931348623157e308)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;assert(end>=start,"end < start");if(end===start)return;if(this.length===0)return;assert(start>=0&&start<this.length,"start out of bounds");assert(end>=0&&end<=this.length,"end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.inspect=function(){var out=[];var len=this.length;for(var i=0;i<len;i++){out[i]=toHex(this[i]);if(i===exports.INSPECT_MAX_BYTES){out[i+1]="...";break}}return"<Buffer "+out.join(" ")+">"};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new Error("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArray(subject){return(Array.isArray||function(subject){return Object.prototype.toString.call(subject)==="[object Array]"})(subject)}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}function verifuint(value,max){assert(typeof value==="number","cannot write a non-number as a number");assert(value>=0,"specified a negative value for writing an unsigned value");assert(value<=max,"value is larger than maximum value for type");assert(Math.floor(value)===value,"value has a fractional component")}function verifsint(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value");assert(Math.floor(value)===value,"value has a fractional component")}function verifIEEE754(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value")}function assert(test,message){if(!test)throw new Error(message||"Failed assertion")}},{"base64-js":2,ieee754:3}],2:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],3:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],4:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],5:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],6:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"
}},{}],7:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],8:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":9}],9:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":11,"./_stream_writable":13,_process:7,"core-util-is":14,inherits:5}],10:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":12,"core-util-is":14,inherits:5}],11:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:7,buffer:1,"core-util-is":14,events:4,inherits:5,isarray:6,stream:20,"string_decoder/":15}],12:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":9,"core-util-is":14,inherits:5}],13:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":9,_process:7,buffer:1,"core-util-is":14,inherits:5,stream:20}],14:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:1}],15:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";var offset=0;while(this.charLength){var i=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,offset,i);this.charReceived+=i-offset;offset=i;if(this.charReceived<this.charLength){return""}charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(i==buffer.length)return charStr;buffer=buffer.slice(i,buffer.length);break}var lenIncomplete=this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-lenIncomplete,end);this.charReceived=lenIncomplete;end-=lenIncomplete}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);this.charBuffer.write(charStr.charAt(charStr.length-1),this.encoding);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}return i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){var incomplete=this.charReceived=buffer.length%2;this.charLength=incomplete?2:0;return incomplete}function base64DetectIncompleteChar(buffer){var incomplete=this.charReceived=buffer.length%3;this.charLength=incomplete?3:0;return incomplete}},{buffer:1}],16:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":10}],17:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":9,"./lib/_stream_passthrough.js":10,"./lib/_stream_readable.js":11,"./lib/_stream_transform.js":12,"./lib/_stream_writable.js":13}],18:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":12}],19:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":13}],20:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:4,inherits:5,"readable-stream/duplex.js":8,"readable-stream/passthrough.js":16,"readable-stream/readable.js":17,"readable-stream/transform.js":18,"readable-stream/writable.js":19}],21:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],22:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";
set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":21,_process:7,inherits:5}],"rtc-data-stream":[function(require,module,exports){var stream=require("stream");var util=require("util");function RtcDataStream(rtcChannel,options){if(!(this instanceof RtcDataStream))return new RtcDataStream(rtcChannel,options);stream.Stream.call(this);this.options=options||{};this.readable=true;this.writable=true;this._buffer=[];this.rtc=rtcChannel;this.rtc.addEventListener("message",this.onMessage.bind(this));this.rtc.onerror=this.onError.bind(this);this.rtc.onclose=this.onClose.bind(this);this.rtc.onopen=this.onOpen.bind(this);if(this.rtc.readyState==="open")this._open=true}util.inherits(RtcDataStream,stream.Stream);module.exports=RtcDataStream;module.exports.RtcDataStream=RtcDataStream;RtcDataStream.prototype.onMessage=function(e,flags){var data=e;if(data.data)data=data.data;var type=this.options.type;if(type&&data instanceof ArrayBuffer)data=new type(data);this.emit("data",data,flags)};RtcDataStream.prototype.onError=function(err){this.emit("error",err)};RtcDataStream.prototype.onClose=function(err){if(this._destroy)return;this.emit("end");this.emit("close")};RtcDataStream.prototype.onOpen=function(err){if(this._destroy)return;this._open=true;for(var i=0;i<this._buffer.length;i++){this._write(this._buffer[i])}this._buffer=undefined;this.emit("open");this.emit("connect");if(this._end)this.rtc.close()};RtcDataStream.prototype.write=function(data){if(!this._open){this._buffer.push(data)}else{this._write(data)}};RtcDataStream.prototype._write=function(data){try{this.rtc.send(data)}catch(e){if(e.name=="NetworkError"){this.onClose(e)}else{this.onError(e)}}};RtcDataStream.prototype.end=function(data){if(data!==undefined)this.write(data);if(this._open)this.rtc.close();this._end=true};RtcDataStream.prototype.destroy=function(){this._destroy=true;this.rtc.close()}},{stream:20,util:22}]},{},[]);require=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<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],2:[function(require,module,exports){"use strict";module.exports=function(target){target=target||{};[].slice.call(arguments,1).forEach(function(source){if(!source){return}for(var prop in source){if(target[prop]===void 0){target[prop]=source[prop]}}});return target}},{}],3:[function(require,module,exports){"use strict";module.exports=function(target){[].slice.call(arguments,1).forEach(function(source){if(!source){return}for(var prop in source){target[prop]=source[prop]}});return target}},{}],4:[function(require,module,exports){module.exports=function(target){function get(key){return target[key]}function set(key,value){target[key]=value}function remove(key){return delete target[key]}function keys(){return Object.keys(target)}function values(){return Object.keys(target).map(function(key){return target[key]})}if(typeof target!="object"){return target}return{get:get,set:set,remove:remove,"delete":remove,keys:keys,values:values}}},{}],5:[function(require,module,exports){"use strict";module.exports=function(input){var isString=typeof input=="string"||input instanceof String;var reNumeric=/^\-?\d+\.?\d*$/;var shouldParse;var firstChar;var lastChar;if(!isString||input.length<2){if(isString&&reNumeric.test(input)){return parseFloat(input)}return input}if(input==="true"||input==="false"){return input==="true"}if(input==="null"){return null}firstChar=input.charAt(0);lastChar=input.charAt(input.length-1);shouldParse=firstChar=="{"&&lastChar=="}"||firstChar=="["&&lastChar=="]"||firstChar=='"'&&lastChar=='"';if(shouldParse){try{return JSON.parse(input)}catch(e){}}return reNumeric.test(input)?parseFloat(input):input}},{}],6:[function(require,module,exports){"use strict";var active=[];var unleashListeners=[];var targets=[console];var logger=module.exports=function(name){var enabled=checkActive();function checkActive(){return enabled=active.indexOf("*")>=0||active.indexOf(name)>=0}unleashListeners[unleashListeners.length]=checkActive;return function(){var args=[].slice.call(arguments);if(typeof args[0]=="string"||args[0]instanceof String){args[0]=name+": "+args[0]}if(!enabled){return}targets.forEach(function(target){target.log.apply(target,args)})}};logger.reset=function(){targets=[];active=[];return logger.enable()};logger.to=function(target){targets=targets.concat(target||[]);return logger};logger.enable=function(){active=active.concat([].slice.call(arguments));unleashListeners.forEach(function(listener){listener()});return logger}},{}],7:[function(require,module,exports){"use strict";module.exports=function(fn,delay,opts){var lastExec=(opts||{}).leading!==false?0:Date.now();var trailing=(opts||{}).trailing;var timer;var queuedArgs;var queuedScope;trailing=trailing||trailing===undefined;function invokeDefered(){fn.apply(queuedScope,queuedArgs||[]);lastExec=Date.now()}return function(){var tick=Date.now();var elapsed=tick-lastExec;clearTimeout(timer);if(elapsed<delay){queuedArgs=[].slice.call(arguments,0);queuedScope=this;return trailing&&(timer=setTimeout(invokeDefered,delay-elapsed))}lastExec=tick;fn.apply(this,arguments)}}},{}],8:[function(require,module,exports){"use strict";var browser=require("detect-browser");var detect=module.exports=function(target,prefixes){var prefixIdx;var prefix;var testName;var hostObject=this||(typeof window!="undefined"?window:undefined);if(!hostObject){return}prefixes=(prefixes||["ms","o","moz","webkit"]).concat("");for(prefixIdx=prefixes.length;prefixIdx--;){prefix=prefixes[prefixIdx];testName=prefix+(prefix?target.charAt(0).toUpperCase()+target.slice(1):target);if(typeof hostObject[testName]!="undefined"){detect.browser=detect.browser||prefix.toLowerCase();return hostObject[target]=hostObject[testName]}}};detect.moz=typeof navigator!="undefined"&&!!navigator.mozGetUserMedia;detect.browser=browser.name;detect.browserVersion=detect.version=browser.version},{"detect-browser":9}],9:[function(require,module,exports){var browsers=[["chrome",/Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+)\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-6].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/iPad\;\sCPU\sOS\s([0-9\._]+)/],["ios",/iPhone\;\sCPU\siPhone\sOS\s([0-9\._]+)/]];var match=browsers.map(match).filter(isMatch)[0];var parts=match&&match[3].split(/[._]/).slice(0,3);while(parts&&parts.length<3){parts.push("0")}exports.name=match&&match[0];exports.version=parts&&parts.join(".");function match(pair){return pair.concat(pair[1].exec(navigator.userAgent))}function isMatch(pair){return!!pair[2]}},{}],10:[function(require,module,exports){var detect=require("./detect");var requiredFunctions=["init"];function isSupported(plugin){return plugin&&typeof plugin.supported=="function"&&plugin.supported(detect)}function isValid(plugin){var supportedFunctions=requiredFunctions.filter(function(fn){return typeof plugin[fn]=="function"});return supportedFunctions.length===requiredFunctions.length}module.exports=function(plugins){return[].concat(plugins||[]).filter(isSupported).filter(isValid)[0]}},{"./detect":8}],11:[function(require,module,exports){var extend=require("cog/extend");module.exports=function(messenger,opts){return require("./index.js")(messenger,extend({connect:require("./primus-loader")},opts))}},{"./index.js":16,"./primus-loader":20,"cog/extend":3}],12:[function(require,module,exports){module.exports={dataEvent:"data",openEvent:"open",closeEvent:"close",writeMethod:"write",closeMethod:"close",leaveTimeout:3e3}},{}],13:[function(require,module,exports){"use strict";var debug=require("cog/logger")("rtc-signaller");var extend=require("cog/extend");var roles=["a","b"];module.exports=function(signaller){function copyData(target,source){if(target&&source){for(var key in source){target[key]=source[key]}}return target}function dataAllowed(data){var evt={data:data,allow:true};signaller.emit("peer:filter",evt);return evt.allow}return function(args,messageType,srcData,srcState,isDM){var data=args[0];var peer;debug("announce handler invoked, received data: ",data);if(data&&data.id&&data.id!==signaller.id){if(!dataAllowed(data)){return}peer=signaller.peers.get(data.id);signaller.emit("peer:connected",data.id,data);if(peer&&!peer.inactive){debug("signaller: "+signaller.id+" received update, data: ",data);copyData(peer.data,data);return signaller.emit("peer:update",data,srcData)}peer={id:data.id,roleIdx:[data.id,signaller.id].sort().indexOf(data.id),data:{}};copyData(peer.data,data);clearTimeout(peer.leaveTimer);peer.inactive=false;signaller.peers.set(data.id,peer);if(signaller.autoreply&&!isDM){signaller.to(data.id).send("/announce",signaller.attributes)}return signaller.emit("peer:announce",data,peer)}}}},{"cog/extend":3,"cog/logger":6}],14:[function(require,module,exports){"use strict";module.exports=function(signaller,opts){return{announce:require("./announce")(signaller,opts),leave:require("./leave")(signaller,opts)}}},{"./announce":13,"./leave":15}],15:[function(require,module,exports){"use strict";module.exports=function(signaller,opts){return function(args){var data=args[0];var peer=signaller.peers.get(data&&data.id);if(peer){peer.leaveTimer=setTimeout(function(){peer.inactive=true;signaller.emit("peer:leave",data.id,peer)},opts.leaveTimeout)}signaller.emit("peer:disconnected",data.id,peer)}}},{}],16:[function(require,module,exports){"use strict";var debug=require("cog/logger")("rtc-signaller");var detect=require("rtc-core/detect");var EventEmitter=require("eventemitter3");var defaults=require("cog/defaults");var extend=require("cog/extend");var throttle=require("cog/throttle");var getable=require("cog/getable");var uuid=require("./uuid");var WRITE_METHODS=["write","send"];var CLOSE_METHODS=["close","end"];var metadata={version:"2.5.0"};module.exports=function(messenger,opts){var autoreply=(opts||{}).autoreply;var connect=(opts||{}).connect;var localMeta={};var signaller=new EventEmitter;var id=signaller.id=(opts||{}).id||uuid();var attributes=signaller.attributes={browser:detect.browser,browserVersion:detect.browserVersion,id:id,agent:"signaller@"+metadata.version};var peers=signaller.peers=getable({});var connected=false;var write;var close;var processor;var announceTimer=0;function announceOnReconnect(){signaller.announce()}function bindBrowserEvents(){messenger.addEventListener("message",function(evt){processor(evt.data)});messenger.addEventListener("open",function(evt){connected=true;signaller.emit("open");signaller.emit("connected")});messenger.addEventListener("close",function(evt){connected=false;signaller.emit("disconnected")})}function bindEvents(){if(typeof messenger.on!="function"){return}messenger.on(opts.dataEvent,processor);messenger.on(opts.openEvent,function(){connected=true;signaller.emit("open");signaller.emit("connected")});messenger.on(opts.closeEvent,function(){connected=false;signaller.emit("disconnected")})}function connectToHost(url){if(typeof connect!="function"){return signaller.emit("error",new Error("no connect function"))}connect(url,opts,function(err,socket){if(err){return signaller.emit("error",err)}signaller._messenger=messenger=socket.connect(url);init()})}function createDataLine(args){return args.map(prepareArg).join("|")}function createMetadata(){return extend({},localMeta,{id:signaller.id})}function extractProp(name){return messenger[name]}function isClosing(){var isAbstraction=messenger&&typeof messenger.socket!="undefined";return isAbstraction?false:messenger&&typeof messenger.readyState!="undefined"&&messenger.readyState>=2}function isF(target){return typeof target=="function"}function init(){write=[opts.writeMethod].concat(WRITE_METHODS).map(extractProp).filter(isF)[0];close=[opts.closeMethod].concat(CLOSE_METHODS).map(extractProp).filter(isF)[0];signaller.process=processor=require("./processor")(signaller,opts);if(typeof write!="function"){throw new Error('provided messenger does not implement a "'+writeMethod+'" write method')}if(typeof messenger.addEventListener=="function"){bindBrowserEvents()}else{bindEvents()}connected=messenger.connected||false;if(!connected){signaller.once("connected",function(){signaller.on("connected",announceOnReconnect)})}setTimeout(signaller.emit.bind(signaller,"init"),0)}function prepareArg(arg){if(typeof arg=="object"&&!(arg instanceof String)){return JSON.stringify(arg)}else if(typeof arg=="function"){return null}return arg}var send=signaller.send=function(){var args=[].slice.call(arguments);var dataline;args.splice(1,0,createMetadata());dataline=createDataLine(args);if(isClosing()){return}if(!connected){return signaller.once("connected",function(){write.call(messenger,dataline)})}return write.call(messenger,dataline)};signaller.announce=function(data,sender){function sendAnnounce(){(sender||send)("/announce",attributes);signaller.emit("local:announce",attributes)}clearTimeout(announceTimer);extend(attributes,data,{id:signaller.id});if(connected){signaller.removeListener("connected",announceOnReconnect);signaller.on("connected",announceOnReconnect)}return announceTimer=setTimeout(function(){if(!connected){return signaller.once("connected",sendAnnounce)}sendAnnounce()},(opts||{}).announceDelay||10)};signaller.isMaster=function(targetId){var peer=peers.get(targetId);return peer&&peer.roleIdx!==0};signaller.leave=signaller.close=function(){send("/leave",{id:id});signaller.removeListener("connected",announceOnReconnect);if(typeof close=="function"){close.call(messenger)}};signaller.metadata=function(data){if(arguments.length===0){return extend({},localMeta)}localMeta=extend({},data)};signaller.to=function(targetId){var sender=function(){var peer=signaller.peers.get(targetId);var args;if(!peer){throw new Error("Unknown peer: "+targetId)}if(peer.inactive){return}args=["/to",targetId].concat([].slice.call(arguments));args.splice(3,0,createMetadata());setTimeout(function(){var msg=createDataLine(args);debug("TX ("+targetId+"): "+msg);write.call(messenger,msg)},0)};return{announce:function(data){return signaller.announce(data,sender)},send:sender}};signaller.setMaxListeners(0);opts=defaults({},opts,require("./defaults"));signaller.autoreply=autoreply===undefined||autoreply;if(typeof messenger=="string"||messenger instanceof String){connectToHost(messenger)}else{init()}signaller._messenger=messenger;signaller.process=processor;return signaller}},{"./defaults":12,"./processor":21,"./uuid":22,"cog/defaults":2,"cog/extend":3,"cog/getable":4,"cog/logger":6,"cog/throttle":7,eventemitter3:17,"rtc-core/detect":8}],17:[function(require,module,exports){"use strict";function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function EventEmitter(){}EventEmitter.prototype._events=undefined;EventEmitter.prototype.listeners=function listeners(event){if(!this._events||!this._events[event])return[];for(var i=0,l=this._events[event].length,ee=[];i<l;i++){ee.push(this._events[event][i].fn)}return ee};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){if(!this._events||!this._events[event])return false;var listeners=this._events[event],length=listeners.length,len=arguments.length,ee=listeners[0],args,i,j;if(1===length){if(ee.once)this.removeListener(event,ee.fn,true);switch(len){case 1:return ee.fn.call(ee.context),true;case 2:return ee.fn.call(ee.context,a1),true;case 3:return ee.fn.call(ee.context,a1,a2),true;case 4:return ee.fn.call(ee.context,a1,a2,a3),true;case 5:return ee.fn.call(ee.context,a1,a2,a3,a4),true;case 6:return ee.fn.call(ee.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}ee.fn.apply(ee.context,args)}else{for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){if(!this._events)this._events={};if(!this._events[event])this._events[event]=[];this._events[event].push(new EE(fn,context||this));return this};EventEmitter.prototype.once=function once(event,fn,context){if(!this._events)this._events={};if(!this._events[event])this._events[event]=[];this._events[event].push(new EE(fn,context||this,true));return this};EventEmitter.prototype.removeListener=function removeListener(event,fn,once){if(!this._events||!this._events[event])return this;var listeners=this._events[event],events=[];if(fn)for(var i=0,length=listeners.length;i<length;i++){if(listeners[i].fn!==fn&&listeners[i].once!==once){events.push(listeners[i])}}if(events.length)this._events[event]=events;else this._events[event]=null;return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){if(!this._events)return this;if(event)this._events[event]=null;else this._events={};return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prototype.setMaxListeners=function setMaxListeners(){return this};EventEmitter.EventEmitter=EventEmitter;EventEmitter.EventEmitter2=EventEmitter;EventEmitter.EventEmitter3=EventEmitter;if("object"===typeof module&&module.exports){module.exports=EventEmitter}},{}],18:[function(require,module,exports){"use strict";var reVariable=/\{\{\s*([^\}]+?)\s*\}\}/;var mods=require("./mods");var formatter=module.exports=function(format,opts){var parts=[];var output=[];var chunk;var varname;var varParts;var match=reVariable.exec(format);var isNumeric;var outputIdx=0;var ignoreNumeric=(opts||{}).ignoreNumeric;while(match){chunk=format.slice(0,match.index);if(chunk){output[outputIdx++]=chunk}varParts=match[1].split(/\s*\|\s*/);match[1]=varParts[0];varname=parseInt(match[1],10);isNumeric=!isNaN(varname);if(ignoreNumeric&&isNumeric){output[outputIdx++]=match[0]}else{parts[parts.length]={idx:outputIdx++,numeric:isNumeric,varname:isNumeric?varname:match[1],modifiers:varParts.length>1?createModifiers(varParts.slice(1)):[]}}format=format.slice(match.index+match[0].length);match=reVariable.exec(format)}if(format){output[outputIdx++]=format}return collect(parts,output)};formatter.error=function(message){var format=formatter(message);return function(err){var output;if(!err){return}output=new Error(format.apply(null,Array.prototype.slice.call(arguments,1)));output._original=err;return output}};function collect(parts,resolved,indexShift){indexShift=indexShift||0;return function(){var output=[].concat(resolved);var unresolved;var ii;var part;var partIdx;var propNames;var val;var numericResolved=[];unresolved=parts.filter(function(part){return typeof output[part.idx]=="undefined"});ii=unresolved.length;for(;ii--;){part=unresolved[ii];if(typeof part=="object"){if(part.numeric){partIdx=part.varname-indexShift;if(arguments.length>partIdx){output[part.idx]=arguments[partIdx];if(numericResolved.indexOf(part.varname)<0){numericResolved[numericResolved.length]=part.varname}}}else if(arguments.length>0){propNames=(part.varname||"").split(".");output[part.idx]=arguments[arguments.length-1]||{};while(output[part.idx]&&propNames.length>0){val=output[part.idx][propNames.shift()];output[part.idx]=typeof val!="undefined"?val:""}}if(typeof output[part.idx]!="undefined"&&part.modifiers){output[part.idx]=applyModifiers(part.modifiers,output[part.idx])}}}unresolved=parts.filter(function(part){return part.numeric&&typeof output[part.idx]=="undefined"});if(unresolved.length===0){return output.join("")}return collect(parts,output,indexShift+numericResolved.length)}}function applyModifiers(modifiers,value){for(var ii=0,count=modifiers.length;ii<count;ii++){value=modifiers[ii](value)}return value}function createModifiers(modifierStrings){var modifiers=[];var parts;var fn;for(var ii=0,count=modifierStrings.length;ii<count;ii++){parts=modifierStrings[ii].split(":");fn=mods[parts[0].toLowerCase()];if(fn){modifiers[modifiers.length]=fn.apply(null,parts.slice(1))}}return modifiers}},{"./mods":19}],19:[function(require,module,exports){"use strict";exports.len=function(length,padder){var testInt=parseInt(padder,10);var isNumber;padder=!isNaN(testInt)?testInt:padder||" ";isNumber=typeof padder=="number";return function(input){var output=input.toString().slice(0,length);while(output.length<length){output=isNumber?padder+output:output+padder}return output}}},{}],20:[function(require,module,exports){"use strict";var reTrailingSlash=/\/$/;var formatter=require("formatter");var primusUrl=formatter("{{ signalhost }}{{ primusPath }}");module.exports=function(signalhost,opts,callback){var anchor=document.createElement("a");var script;var scriptSrc;if(typeof opts=="function"){callback=opts;opts={}}anchor.href=signalhost;scriptSrc=primusUrl({signalhost:signalhost.replace(reTrailingSlash,""),primusPath:(opts||{}).primusPath||"/rtc.io/primus.js"});script=document.querySelector('script[src="'+scriptSrc+'"]');if(script&&typeof Primus!="undefined"){return callback(null,Primus)}else if(script){script.addEventListener("load",function(){callback(null,Primus)});return}script=document.createElement("script");script.src=scriptSrc;script.onerror=callback;script.addEventListener("load",function(){if(anchor.pathname!=="/"){Primus.prototype.pathname=anchor.pathname.replace(reTrailingSlash,"")+Primus.prototype.pathname}callback(null,Primus)});document.body.appendChild(script)}},{formatter:18}],21:[function(require,module,exports){"use strict";var debug=require("cog/logger")("rtc-signaller");var jsonparse=require("cog/jsonparse");module.exports=function(signaller,opts){var handlers=require("./handlers")(signaller,opts);function sendEvent(parts,srcState,data){var evtName=parts[0].slice(1);var args=parts.slice(2).map(jsonparse);signaller.emit.apply(signaller,[evtName].concat(args).concat([srcState,data]))}return function(originalData){var data=originalData;var isMatch=true;var parts;var handler;var srcData;var srcState;var isDirectMessage=false;var id=signaller.id+"";debug("signaller "+id+" received data: "+originalData);if(data.slice(0,3)==="/to"){isMatch=data.slice(4,id.length+4)===id;if(isMatch){parts=data.slice(5+id.length).split("|").map(jsonparse);isDirectMessage=true;parts=parts.map(jsonparse)}}if(!isMatch){return}parts=parts||data.split("|").map(jsonparse);if(typeof parts[0]=="string"){srcData=parts[1];if(srcData&&srcData.id===signaller.id){return console.warn("got data from ourself, discarding")
}srcState=signaller.peers.get(srcData&&srcData.id)||srcData;if(parts[0].charAt(0)==="/"){handler=handlers[parts[0].slice(1)];if(typeof handler=="function"){handler(parts.slice(2),parts[0].slice(1),srcData,srcState,isDirectMessage)}else{sendEvent(parts,srcState,originalData)}}else{signaller.emit("data",parts.slice(0,1).concat(parts.slice(2)),srcData,srcState,isDirectMessage)}}}}},{"./handlers":14,"cog/jsonparse":5,"cog/logger":6}],22:[function(require,module,exports){module.exports=function(a,b){for(b=a="";a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):"-");return b}},{}],23:[function(require,module,exports){"use strict";var debug=require("cog/logger")("rtc/cleanup");var CANNOT_CLOSE_STATES=["closed"];var EVENTS_DECOUPLE_BC=["addstream","datachannel","icecandidate","negotiationneeded","removestream","signalingstatechange"];var EVENTS_DECOUPLE_AC=["iceconnectionstatechange"];module.exports=function(pc){var currentState=pc.iceConnectionState;var canClose=CANNOT_CLOSE_STATES.indexOf(currentState)<0;function decouple(events){events.forEach(function(evtName){if(pc["on"+evtName]){pc["on"+evtName]=null}})}decouple(EVENTS_DECOUPLE_BC);if(canClose){debug("attempting connection close, current state: "+pc.iceConnectionState);pc.close()}setTimeout(function(){decouple(EVENTS_DECOUPLE_AC)},100)}},{"cog/logger":6}],24:[function(require,module,exports){"use strict";var async=require("async");var cleanup=require("./cleanup");var monitor=require("./monitor");var detect=require("./detect");var findPlugin=require("rtc-core/plugin");var CLOSED_STATES=["closed","failed"];var OFFER_ANSWER_CONSTRAINTS=["offerToReceiveVideo","offerToReceiveAudio","voiceActivityDetection","iceRestart"];function couple(pc,targetId,signaller,opts){var debugLabel=(opts||{}).debugLabel||"rtc";var debug=require("cog/logger")(debugLabel+"/couple");var mon=monitor(pc,targetId,signaller,opts);var queuedCandidates=[];var sdpFilter=(opts||{}).sdpfilter;var reactive=(opts||{}).reactive;var offerTimeout;var endOfCandidates=true;var plugin=findPlugin((opts||{}).plugins);var disconnectTimeout=(opts||{}).disconnectTimeout||1e4;var disconnectTimer;if(typeof signaller.isMaster!="function"){throw new Error("rtc-signaller instance >= 0.14.0 required")}var isMaster=signaller.isMaster(targetId);var createOffer=prepNegotiate("createOffer",isMaster,[checkStable]);var createAnswer=prepNegotiate("createAnswer",true,[]);var q=async.queue(function(task,cb){if(typeof task.op!="function"){return cb()}task.op(task,cb)},1);var RTCSessionDescription=(opts||{}).RTCSessionDescription||detect("RTCSessionDescription");var RTCIceCandidate=(opts||{}).RTCIceCandidate||detect("RTCIceCandidate");function abort(stage,sdp,cb){return function(err){mon.emit("negotiate:abort",stage,sdp);console.error("rtc/couple error ("+stage+"): ",err);if(typeof cb=="function"){cb(err)}}}function applyCandidatesWhenStable(){if(pc.signalingState=="stable"&&pc.remoteDescription){debug("signaling state = stable, applying queued candidates");mon.removeListener("change",applyCandidatesWhenStable);queuedCandidates.splice(0).forEach(function(data){debug("applying queued candidate",data);addIceCandidate(data)})}}function checkNotConnecting(negotiate){if(pc.iceConnectionState!="checking"){return true}debug("connection state is checking, will wait to create a new offer");mon.once("connected",function(){q.push({op:negotiate})});return false}function checkStable(negotiate){if(pc.signalingState==="stable"){return true}debug("cannot create offer, signaling state != stable, will retry");mon.on("change",function waitForStable(){if(pc.signalingState==="stable"){q.push({op:negotiate})}mon.removeListener("change",waitForStable)});return false}function createIceCandidate(data){if(plugin&&typeof plugin.createIceCandidate=="function"){return plugin.createIceCandidate(data)}return new RTCIceCandidate(data)}function createSessionDescription(data){if(plugin&&typeof plugin.createSessionDescription=="function"){return plugin.createSessionDescription(data)}return new RTCSessionDescription(data)}function decouple(){debug("decoupling "+signaller.id+" from "+targetId);mon.removeAllListeners();mon.stop();cleanup(pc);signaller.removeListener("sdp",handleSdp);signaller.removeListener("candidate",handleRemoteCandidate);signaller.removeListener("negotiate",handleNegotiateRequest)}function generateConstraints(methodName){var constraints={};function reformatConstraints(){var tweaked={};Object.keys(constraints).forEach(function(param){var sentencedCased=param.charAt(0).toUpperCase()+param.substr(1);tweaked[sentencedCased]=constraints[param]});constraints={mandatory:tweaked}}OFFER_ANSWER_CONSTRAINTS.forEach(function(param){var sentencedCased=param.charAt(0).toUpperCase()+param.substr(1);if(!opts){return}else if(opts[param]!==undefined){constraints[param]=opts[param]}else if(opts[sentencedCased]!==undefined){constraints[param]=opts[sentencedCased]}});reformatConstraints();return constraints}function prepNegotiate(methodName,allowed,preflightChecks){var constraints=generateConstraints(methodName);preflightChecks=[].concat(preflightChecks||[]);return function negotiate(task,cb){var checksOK=true;if(!allowed){signaller.to(targetId).send("/negotiate");return cb()}if(isClosed()){return cb(new Error("connection closed, cannot negotiate"))}preflightChecks.forEach(function(check){checksOK=checksOK&&check(negotiate)});if(!checksOK){debug("preflight checks did not pass, aborting "+methodName);return cb()}debug("calling "+methodName);mon.emit("negotiate:"+methodName);pc[methodName](function(desc){if(typeof sdpFilter=="function"){desc.sdp=sdpFilter(desc.sdp,pc,methodName)}mon.emit("negotiate:"+methodName+":created",desc);q.push({op:queueLocalDesc(desc)});cb()},abort(methodName,"",cb),constraints)}}function handleConnectionClose(){debug("captured pc close, iceConnectionState = "+pc.iceConnectionState);decouple()}function handleDisconnect(){debug("captured pc disconnect, monitoring connection status");disconnectTimer=setTimeout(function(){debug("manually closing connection after disconnect timeout");pc.close()},disconnectTimeout);mon.on("change",handleDisconnectAbort)}function handleDisconnectAbort(){debug("connection state changed to: "+pc.iceConnectionState);resetDisconnectTimer();if(CLOSED_STATES.indexOf(pc.iceConnectionState)>=0){return mon.emit("closed")}mon.once("disconnect",handleDisconnect)}function handleLocalCandidate(evt){if(evt.candidate){resetDisconnectTimer();mon.emit("icecandidate:local",evt.candidate);signaller.to(targetId).send("/candidate",evt.candidate);endOfCandidates=false}else if(!endOfCandidates){endOfCandidates=true;debug("ice gathering state complete");mon.emit("icecandidate:gathered");signaller.to(targetId).send("/endofcandidates",{})}}function handleNegotiateRequest(src){if(src.id===targetId){debug("got negotiate request from "+targetId+", creating offer");mon.emit("negotiate:request",src.id);q.push({op:createOffer})}}function handleRemoteCandidate(data,src){if(!src||src.id!==targetId){return}if(pc.signalingState!="stable"||!pc.remoteDescription){debug("queuing candidate");queuedCandidates.push(data);mon.emit("icecandidate:remote",data);mon.removeListener("change",applyCandidatesWhenStable);mon.on("change",applyCandidatesWhenStable);return}addIceCandidate(data)}function handleSdp(data,src){var abortType=data.type==="offer"?"createAnswer":"createOffer";mon.emit("sdp:received",data);if(!src||src.id!==targetId){return debug("received sdp but dropping due to unmatched src")}q.push({op:function(task,cb){if(isClosed()){return cb(new Error("pc closed: cannot set remote description"))}debug("setting remote description");pc.setRemoteDescription(createSessionDescription(data),function(){if(data.type==="offer"){queue(createAnswer)()}cb()},abort(abortType,data.sdp,cb))}})}function addIceCandidate(data){try{pc.addIceCandidate(createIceCandidate(data));mon.emit("icecandidate:added",data)}catch(e){debug("invalidate candidate specified: ",data);mon.emit("icecandidate:added",data,e)}}function isClosed(){return CLOSED_STATES.indexOf(pc.iceConnectionState)>=0}function queue(negotiateTask){return function(){q.push([{op:negotiateTask}])}}function queueLocalDesc(desc){return function setLocalDesc(task,cb){if(isClosed()){return cb(new Error("connection closed, aborting"))}debug("setting local description");pc.setLocalDescription(desc,function(){signaller.to(targetId).send("/sdp",desc);mon.emit("negotiate:setlocaldescription",desc);cb()},function(err){debug("error setting local description",err);debug(desc.sdp);mon.emit("negotiate:setlocaldescription",desc,err);cb(err)})}}function resetDisconnectTimer(){mon.removeListener("change",handleDisconnectAbort);debug("reset disconnect timer, state: "+pc.iceConnectionState);clearTimeout(disconnectTimer)}if(reactive){pc.onnegotiationneeded=function(){mon.emit("negotiate:renegotiate");debug("renegotiation required, will create offer in 50ms");clearTimeout(offerTimeout);offerTimeout=setTimeout(queue(createOffer),50)}}pc.onicecandidate=handleLocalCandidate;signaller.on("sdp",handleSdp);signaller.on("candidate",handleRemoteCandidate);if(isMaster){signaller.on("negotiate",handleNegotiateRequest)}mon.once("closed",handleConnectionClose);mon.once("disconnected",handleDisconnect);mon.createOffer=queue(createOffer);return mon}module.exports=couple},{"./cleanup":23,"./detect":25,"./monitor":28,async:29,"cog/logger":6,"rtc-core/plugin":10}],25:[function(require,module,exports){"use strict";module.exports=require("rtc-core/detect")},{"rtc-core/detect":8}],26:[function(require,module,exports){"use strict";var debug=require("cog/logger")("generators");var detect=require("./detect");var defaults=require("cog/defaults");var mappings={create:{dtls:function(c){if(!detect.moz){c.optional=(c.optional||[]).concat({DtlsSrtpKeyAgreement:true})}}}};var iceServerGenerator=function(){return[]};exports.config=function(config){var iceServerGenerator=(config||{}).iceServerGenerator;return defaults({},config,{iceServers:typeof iceServerGenerator=="function"?iceServerGenerator():[]})};exports.connectionConstraints=function(flags,constraints){var generated={};var m=mappings.create;var out;Object.keys(flags||{}).forEach(function(key){if(m[key]){m[key](generated)}});out=defaults({},constraints,generated);debug("generated connection constraints: ",out);return out}},{"./detect":25,"cog/defaults":2,"cog/logger":6}],27:[function(require,module,exports){"use strict";var gen=require("./generators");var detect=exports.detect=require("./detect");var findPlugin=require("rtc-core/plugin");exports.logger=require("cog/logger");var RTCPeerConnection=exports.RTCPeerConnection=detect("RTCPeerConnection");exports.couple=require("./couple");exports.createConnection=function(opts,constraints){var plugin=findPlugin((opts||{}).plugins);var config=gen.config(opts);var constraints=gen.connectionConstraints(opts,constraints);if(plugin&&typeof plugin.createConnection=="function"){return plugin.createConnection(config,constraints)}else{return new((opts||{}).RTCPeerConnection||RTCPeerConnection)(config,constraints)}}},{"./couple":24,"./detect":25,"./generators":26,"cog/logger":6,"rtc-core/plugin":10}],28:[function(require,module,exports){"use strict";var EventEmitter=require("eventemitter3");var stateMappings={completed:"connected"};var peerStateEvents=["signalingstatechange","iceconnectionstatechange"];module.exports=function(pc,targetId,signaller,opts){var debugLabel=(opts||{}).debugLabel||"rtc";var debug=require("cog/logger")(debugLabel+"/monitor");var monitor=new EventEmitter;var state;function checkState(){var newState=getMappedState(pc.iceConnectionState);debug("state changed: "+pc.iceConnectionState+", mapped: "+newState);monitor.emit("change",pc);if(state!==newState){monitor.emit(newState);state=newState}}function handlePeerLeave(peerId){debug("captured peer leave for peer: "+peerId);if(peerId!==targetId){return}monitor.emit("closed")}pc.onclose=monitor.emit.bind(monitor,"closed");peerStateEvents.forEach(function(evtName){pc["on"+evtName]=checkState});monitor.stop=function(){pc.onclose=null;peerStateEvents.forEach(function(evtName){pc["on"+evtName]=null});if(signaller&&typeof signaller.removeListener=="function"){signaller.removeListener("peer:leave",handlePeerLeave)}};monitor.checkState=checkState;if(!pc){return monitor}state=getMappedState(pc.iceConnectionState);if(signaller&&typeof signaller.on=="function"){signaller.on("peer:leave",handlePeerLeave)}return monitor};function getMappedState(state){return stateMappings[state]||state}},{"cog/logger":6,eventemitter3:30}],29:[function(require,module,exports){(function(process){(function(){var async={};var root,previous_async;root=this;if(root!=null){previous_async=root.async}async.noConflict=function(){root.async=previous_async;return async};function only_once(fn){var called=false;return function(){if(called)throw new Error("Callback was already called.");called=true;fn.apply(root,arguments)}}var _toString=Object.prototype.toString;var _isArray=Array.isArray||function(obj){return _toString.call(obj)==="[object Array]"};var _each=function(arr,iterator){if(arr.forEach){return arr.forEach(iterator)}for(var i=0;i<arr.length;i+=1){iterator(arr[i],i,arr)}};var _map=function(arr,iterator){if(arr.map){return arr.map(iterator)}var results=[];_each(arr,function(x,i,a){results.push(iterator(x,i,a))});return results};var _reduce=function(arr,iterator,memo){if(arr.reduce){return arr.reduce(iterator,memo)}_each(arr,function(x,i,a){memo=iterator(memo,x,i,a)});return memo};var _keys=function(obj){if(Object.keys){return Object.keys(obj)}var keys=[];for(var k in obj){if(obj.hasOwnProperty(k)){keys.push(k)}}return keys};if(typeof process==="undefined"||!process.nextTick){if(typeof setImmediate==="function"){async.nextTick=function(fn){setImmediate(fn)};async.setImmediate=async.nextTick}else{async.nextTick=function(fn){setTimeout(fn,0)};async.setImmediate=async.nextTick}}else{async.nextTick=process.nextTick;if(typeof setImmediate!=="undefined"){async.setImmediate=function(fn){setImmediate(fn)}}else{async.setImmediate=async.nextTick}}async.each=function(arr,iterator,callback){callback=callback||function(){};if(!arr.length){return callback()}var completed=0;_each(arr,function(x){iterator(x,only_once(done))});function done(err){if(err){callback(err);callback=function(){}}else{completed+=1;if(completed>=arr.length){callback()}}}};async.forEach=async.each;async.eachSeries=function(arr,iterator,callback){callback=callback||function(){};if(!arr.length){return callback()}var completed=0;var iterate=function(){iterator(arr[completed],function(err){if(err){callback(err);callback=function(){}}else{completed+=1;if(completed>=arr.length){callback()}else{iterate()}}})};iterate()};async.forEachSeries=async.eachSeries;async.eachLimit=function(arr,limit,iterator,callback){var fn=_eachLimit(limit);fn.apply(null,[arr,iterator,callback])};async.forEachLimit=async.eachLimit;var _eachLimit=function(limit){return function(arr,iterator,callback){callback=callback||function(){};if(!arr.length||limit<=0){return callback()}var completed=0;var started=0;var running=0;(function replenish(){if(completed>=arr.length){return callback()}while(running<limit&&started<arr.length){started+=1;running+=1;iterator(arr[started-1],function(err){if(err){callback(err);callback=function(){}}else{completed+=1;running-=1;if(completed>=arr.length){callback()}else{replenish()}}})}})()}};var doParallel=function(fn){return function(){var args=Array.prototype.slice.call(arguments);return fn.apply(null,[async.each].concat(args))}};var doParallelLimit=function(limit,fn){return function(){var args=Array.prototype.slice.call(arguments);return fn.apply(null,[_eachLimit(limit)].concat(args))}};var doSeries=function(fn){return function(){var args=Array.prototype.slice.call(arguments);return fn.apply(null,[async.eachSeries].concat(args))}};var _asyncMap=function(eachfn,arr,iterator,callback){arr=_map(arr,function(x,i){return{index:i,value:x}});if(!callback){eachfn(arr,function(x,callback){iterator(x.value,function(err){callback(err)})})}else{var results=[];eachfn(arr,function(x,callback){iterator(x.value,function(err,v){results[x.index]=v;callback(err)})},function(err){callback(err,results)})}};async.map=doParallel(_asyncMap);async.mapSeries=doSeries(_asyncMap);async.mapLimit=function(arr,limit,iterator,callback){return _mapLimit(limit)(arr,iterator,callback)};var _mapLimit=function(limit){return doParallelLimit(limit,_asyncMap)};async.reduce=function(arr,memo,iterator,callback){async.eachSeries(arr,function(x,callback){iterator(memo,x,function(err,v){memo=v;callback(err)})},function(err){callback(err,memo)})};async.inject=async.reduce;async.foldl=async.reduce;async.reduceRight=function(arr,memo,iterator,callback){var reversed=_map(arr,function(x){return x}).reverse();async.reduce(reversed,memo,iterator,callback)};async.foldr=async.reduceRight;var _filter=function(eachfn,arr,iterator,callback){var results=[];arr=_map(arr,function(x,i){return{index:i,value:x}});eachfn(arr,function(x,callback){iterator(x.value,function(v){if(v){results.push(x)}callback()})},function(err){callback(_map(results.sort(function(a,b){return a.index-b.index}),function(x){return x.value}))})};async.filter=doParallel(_filter);async.filterSeries=doSeries(_filter);async.select=async.filter;async.selectSeries=async.filterSeries;var _reject=function(eachfn,arr,iterator,callback){var results=[];arr=_map(arr,function(x,i){return{index:i,value:x}});eachfn(arr,function(x,callback){iterator(x.value,function(v){if(!v){results.push(x)}callback()})},function(err){callback(_map(results.sort(function(a,b){return a.index-b.index}),function(x){return x.value}))})};async.reject=doParallel(_reject);async.rejectSeries=doSeries(_reject);var _detect=function(eachfn,arr,iterator,main_callback){eachfn(arr,function(x,callback){iterator(x,function(result){if(result){main_callback(x);main_callback=function(){}}else{callback()}})},function(err){main_callback()})};async.detect=doParallel(_detect);async.detectSeries=doSeries(_detect);async.some=function(arr,iterator,main_callback){async.each(arr,function(x,callback){iterator(x,function(v){if(v){main_callback(true);main_callback=function(){}}callback()})},function(err){main_callback(false)})};async.any=async.some;async.every=function(arr,iterator,main_callback){async.each(arr,function(x,callback){iterator(x,function(v){if(!v){main_callback(false);main_callback=function(){}}callback()})},function(err){main_callback(true)})};async.all=async.every;async.sortBy=function(arr,iterator,callback){async.map(arr,function(x,callback){iterator(x,function(err,criteria){if(err){callback(err)}else{callback(null,{value:x,criteria:criteria})}})},function(err,results){if(err){return callback(err)}else{var fn=function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0};callback(null,_map(results.sort(fn),function(x){return x.value}))}})};async.auto=function(tasks,callback){callback=callback||function(){};var keys=_keys(tasks);var remainingTasks=keys.length;if(!remainingTasks){return callback()}var results={};var listeners=[];var addListener=function(fn){listeners.unshift(fn)};var removeListener=function(fn){for(var i=0;i<listeners.length;i+=1){if(listeners[i]===fn){listeners.splice(i,1);return}}};var taskComplete=function(){remainingTasks--;_each(listeners.slice(0),function(fn){fn()})};addListener(function(){if(!remainingTasks){var theCallback=callback;callback=function(){};theCallback(null,results)}});_each(keys,function(k){var task=_isArray(tasks[k])?tasks[k]:[tasks[k]];var taskCallback=function(err){var args=Array.prototype.slice.call(arguments,1);if(args.length<=1){args=args[0]}if(err){var safeResults={};_each(_keys(results),function(rkey){safeResults[rkey]=results[rkey]});safeResults[k]=args;callback(err,safeResults);callback=function(){}}else{results[k]=args;async.setImmediate(taskComplete)}};var requires=task.slice(0,Math.abs(task.length-1))||[];var ready=function(){return _reduce(requires,function(a,x){return a&&results.hasOwnProperty(x)},true)&&!results.hasOwnProperty(k)};if(ready()){task[task.length-1](taskCallback,results)}else{var listener=function(){if(ready()){removeListener(listener);task[task.length-1](taskCallback,results)}};addListener(listener)}})};async.retry=function(times,task,callback){var DEFAULT_TIMES=5;var attempts=[];if(typeof times==="function"){callback=task;task=times;times=DEFAULT_TIMES}times=parseInt(times,10)||DEFAULT_TIMES;var wrappedTask=function(wrappedCallback,wrappedResults){var retryAttempt=function(task,finalAttempt){return function(seriesCallback){task(function(err,result){seriesCallback(!err||finalAttempt,{err:err,result:result})},wrappedResults)}};while(times){attempts.push(retryAttempt(task,!(times-=1)))}async.series(attempts,function(done,data){data=data[data.length-1];(wrappedCallback||callback)(data.err,data.result)})};return callback?wrappedTask():wrappedTask};async.waterfall=function(tasks,callback){callback=callback||function(){};if(!_isArray(tasks)){var err=new Error("First argument to waterfall must be an array of functions");return callback(err)}if(!tasks.length){return callback()}var wrapIterator=function(iterator){return function(err){if(err){callback.apply(null,arguments);callback=function(){}}else{var args=Array.prototype.slice.call(arguments,1);var next=iterator.next();if(next){args.push(wrapIterator(next))}else{args.push(callback)}async.setImmediate(function(){iterator.apply(null,args)})}}};wrapIterator(async.iterator(tasks))()};var _parallel=function(eachfn,tasks,callback){callback=callback||function(){};if(_isArray(tasks)){eachfn.map(tasks,function(fn,callback){if(fn){fn(function(err){var args=Array.prototype.slice.call(arguments,1);if(args.length<=1){args=args[0]}callback.call(null,err,args)})}},callback)}else{var results={};eachfn.each(_keys(tasks),function(k,callback){tasks[k](function(err){var args=Array.prototype.slice.call(arguments,1);if(args.length<=1){args=args[0]}results[k]=args;callback(err)})},function(err){callback(err,results)})}};async.parallel=function(tasks,callback){_parallel({map:async.map,each:async.each},tasks,callback)};async.parallelLimit=function(tasks,limit,callback){_parallel({map:_mapLimit(limit),each:_eachLimit(limit)},tasks,callback)};async.series=function(tasks,callback){callback=callback||function(){};if(_isArray(tasks)){async.mapSeries(tasks,function(fn,callback){if(fn){fn(function(err){var args=Array.prototype.slice.call(arguments,1);if(args.length<=1){args=args[0]}callback.call(null,err,args)})}},callback)}else{var results={};async.eachSeries(_keys(tasks),function(k,callback){tasks[k](function(err){var args=Array.prototype.slice.call(arguments,1);if(args.length<=1){args=args[0]}results[k]=args;callback(err)})},function(err){callback(err,results)})}};async.iterator=function(tasks){var makeCallback=function(index){var fn=function(){if(tasks.length){tasks[index].apply(null,arguments)}return fn.next()};fn.next=function(){return index<tasks.length-1?makeCallback(index+1):null};return fn};return makeCallback(0)};async.apply=function(fn){var args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(null,args.concat(Array.prototype.slice.call(arguments)))}};var _concat=function(eachfn,arr,fn,callback){var r=[];eachfn(arr,function(x,cb){fn(x,function(err,y){r=r.concat(y||[]);cb(err)})},function(err){callback(err,r)})};async.concat=doParallel(_concat);async.concatSeries=doSeries(_concat);async.whilst=function(test,iterator,callback){if(test()){iterator(function(err){if(err){return callback(err)}async.whilst(test,iterator,callback)})}else{callback()}};async.doWhilst=function(iterator,test,callback){iterator(function(err){if(err){return callback(err)}var args=Array.prototype.slice.call(arguments,1);if(test.apply(null,args)){async.doWhilst(iterator,test,callback)}else{callback()}})};async.until=function(test,iterator,callback){if(!test()){iterator(function(err){if(err){return callback(err)}async.until(test,iterator,callback)})}else{callback()}};async.doUntil=function(iterator,test,callback){iterator(function(err){if(err){return callback(err)}var args=Array.prototype.slice.call(arguments,1);if(!test.apply(null,args)){async.doUntil(iterator,test,callback)}else{callback()}})};async.queue=function(worker,concurrency){if(concurrency===undefined){concurrency=1}function _insert(q,data,pos,callback){if(!q.started){q.started=true}if(!_isArray(data)){data=[data]}if(data.length==0){return async.setImmediate(function(){if(q.drain){q.drain()}})}_each(data,function(task){var item={data:task,callback:typeof callback==="function"?callback:null};if(pos){q.tasks.unshift(item)}else{q.tasks.push(item)}if(q.saturated&&q.tasks.length===q.concurrency){q.saturated()}async.setImmediate(q.process)})}var workers=0;var q={tasks:[],concurrency:concurrency,saturated:null,empty:null,drain:null,started:false,paused:false,push:function(data,callback){_insert(q,data,false,callback)},kill:function(){q.drain=null;q.tasks=[]},unshift:function(data,callback){_insert(q,data,true,callback)},process:function(){if(!q.paused&&workers<q.concurrency&&q.tasks.length){var task=q.tasks.shift();if(q.empty&&q.tasks.length===0){q.empty()}workers+=1;var next=function(){workers-=1;if(task.callback){task.callback.apply(task,arguments)}if(q.drain&&q.tasks.length+workers===0){q.drain()}q.process()};var cb=only_once(next);worker(task.data,cb)}},length:function(){return q.tasks.length},running:function(){return workers},idle:function(){return q.tasks.length+workers===0},pause:function(){if(q.paused===true){return}q.paused=true;q.process()},resume:function(){if(q.paused===false){return}q.paused=false;q.process()}};return q};async.priorityQueue=function(worker,concurrency){function _compareTasks(a,b){return a.priority-b.priority}function _binarySearch(sequence,item,compare){var beg=-1,end=sequence.length-1;while(beg<end){var mid=beg+(end-beg+1>>>1);if(compare(item,sequence[mid])>=0){beg=mid}else{end=mid-1}}return beg}function _insert(q,data,priority,callback){if(!q.started){q.started=true}if(!_isArray(data)){data=[data]}if(data.length==0){return async.setImmediate(function(){if(q.drain){q.drain()}})}_each(data,function(task){var item={data:task,priority:priority,callback:typeof callback==="function"?callback:null};q.tasks.splice(_binarySearch(q.tasks,item,_compareTasks)+1,0,item);if(q.saturated&&q.tasks.length===q.concurrency){q.saturated()}async.setImmediate(q.process)})}var q=async.queue(worker,concurrency);q.push=function(data,priority,callback){_insert(q,data,priority,callback)};delete q.unshift;return q};async.cargo=function(worker,payload){var working=false,tasks=[];var cargo={tasks:tasks,payload:payload,saturated:null,empty:null,drain:null,drained:true,push:function(data,callback){if(!_isArray(data)){data=[data]}_each(data,function(task){tasks.push({data:task,callback:typeof callback==="function"?callback:null});cargo.drained=false;if(cargo.saturated&&tasks.length===payload){cargo.saturated()}});async.setImmediate(cargo.process)},process:function process(){if(working)return;if(tasks.length===0){if(cargo.drain&&!cargo.drained)cargo.drain();cargo.drained=true;return}var ts=typeof payload==="number"?tasks.splice(0,payload):tasks.splice(0,tasks.length);var ds=_map(ts,function(task){return task.data});if(cargo.empty)cargo.empty();working=true;worker(ds,function(){working=false;var args=arguments;_each(ts,function(data){if(data.callback){data.callback.apply(null,args)}});process()})},length:function(){return tasks.length},running:function(){return working}};return cargo};var _console_fn=function(name){return function(fn){var args=Array.prototype.slice.call(arguments,1);fn.apply(null,args.concat([function(err){var args=Array.prototype.slice.call(arguments,1);if(typeof console!=="undefined"){if(err){if(console.error){console.error(err)}}else if(console[name]){_each(args,function(x){console[name](x)})}}}]))}};async.log=_console_fn("log");async.dir=_console_fn("dir");async.memoize=function(fn,hasher){var memo={};var queues={};hasher=hasher||function(x){return x};var memoized=function(){var args=Array.prototype.slice.call(arguments);var callback=args.pop();var key=hasher.apply(null,args);if(key in memo){async.nextTick(function(){callback.apply(null,memo[key])})}else if(key in queues){queues[key].push(callback)}else{queues[key]=[callback];fn.apply(null,args.concat([function(){memo[key]=arguments;var q=queues[key];delete queues[key];for(var i=0,l=q.length;i<l;i++){q[i].apply(null,arguments)}}]))}};memoized.memo=memo;memoized.unmemoized=fn;return memoized};async.unmemoize=function(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}};async.times=function(count,iterator,callback){var counter=[];for(var i=0;i<count;i++){counter.push(i)}return async.map(counter,iterator,callback)};async.timesSeries=function(count,iterator,callback){var counter=[];for(var i=0;i<count;i++){counter.push(i)}return async.mapSeries(counter,iterator,callback)};async.seq=function(){var fns=arguments;return function(){var that=this;var args=Array.prototype.slice.call(arguments);var callback=args.pop();async.reduce(fns,args,function(newargs,fn,cb){fn.apply(that,newargs.concat([function(){var err=arguments[0];var nextargs=Array.prototype.slice.call(arguments,1);cb(err,nextargs)}]))},function(err,results){callback.apply(that,[err].concat(results))})}};async.compose=function(){return async.seq.apply(null,Array.prototype.reverse.call(arguments))};var _applyEach=function(eachfn,fns){var go=function(){var that=this;var args=Array.prototype.slice.call(arguments);var callback=args.pop();return eachfn(fns,function(fn,cb){fn.apply(that,args.concat([cb]))},callback)};if(arguments.length>2){var args=Array.prototype.slice.call(arguments,2);return go.apply(this,args)}else{return go}};async.applyEach=doParallel(_applyEach);async.applyEachSeries=doSeries(_applyEach);async.forever=function(fn,callback){function next(err){if(err){if(callback){return callback(err)}throw err}fn(next)}next()};if(typeof module!=="undefined"&&module.exports){module.exports=async}else if(typeof define!=="undefined"&&define.amd){define([],function(){return async})}else{root.async=async}})()}).call(this,require("_process"))},{_process:1}],30:[function(require,module,exports){module.exports=require(17)},{}],"rtc-quickconnect":[function(require,module,exports){(function(process){"use strict";var rtc=require("rtc-tools");var cleanup=require("rtc-tools/cleanup");var debug=rtc.logger("rtc-quickconnect");var signaller=require("rtc-signaller");var defaults=require("cog/defaults");var extend=require("cog/extend");var getable=require("cog/getable");var reTrailingSlash=/\/$/;module.exports=function(signalhost,opts){var hash=typeof location!="undefined"&&location.hash.slice(1);var signaller=require("rtc-signaller")(signalhost,opts);var ns=(opts||{}).ns||"";var room=(opts||{}).room;var debugging=(opts||{}).debug;var profile={};var announced=false;var localStreams=[];var calls=signaller.calls=getable({});var channels={};var plugins=signaller.plugins=(opts||{}).plugins||[];var expectedLocalStreams=(opts||{}).expectedLocalStreams||0;var announceTimer=0;function callCreate(id,pc,data){calls.set(id,{active:false,pc:pc,channels:getable({}),data:data,streams:[]})}function callEnd(id){var call=calls.get(id);if(!call){return}debug("ending call to: "+id);call.channels.keys().forEach(function(label){var channel=call.channels.get(label);var args=[id,channel,label];signaller.emit.apply(signaller,["channel:closed"].concat(args));signaller.emit.apply(signaller,["channel:closed:"+label].concat(args));channel.onopen=null});call.streams.forEach(function(stream){signaller.emit("stream:removed",id,stream)});calls.delete(id);signaller.emit("call:ended",id,call.pc);cleanup(call.pc)}function callStart(id,pc,data){var call=calls.get(id);var streams=[].concat(pc.getRemoteStreams());call.active=true;call.streams=[].concat(pc.getRemoteStreams());pc.onaddstream=createStreamAddHandler(id);pc.onremovestream=createStreamRemoveHandler(id);
debug(signaller.id+" - "+id+" call start: "+streams.length+" streams");signaller.emit("call:started",id,pc,data);process.nextTick(function(){streams.forEach(receiveRemoteStream(id))})}function checkReadyToAnnounce(){clearTimeout(announceTimer);if(expectedLocalStreams&&localStreams.length<expectedLocalStreams){return}announceTimer=setTimeout(function(){var data=extend({},profile,{room:room});signaller.announce(data);announced=true},0)}function createStreamAddHandler(id){return function(evt){debug("peer "+id+" added stream");updateRemoteStreams(id);receiveRemoteStream(id)(evt.stream)}}function createStreamRemoveHandler(id){return function(evt){debug("peer "+id+" removed stream");updateRemoteStreams(id);signaller.emit("stream:removed",id,evt.stream)}}function getActiveCall(peerId){var call=calls.get(peerId);if(!call){throw new Error("No active call for peer: "+peerId)}return call}function gotPeerChannel(channel,pc,data){var channelMonitor;function channelReady(){var call=calls.get(data.id);var args=[data.id,channel,data,pc];debug('reporting channel "'+channel.label+'" ready, have call: '+!!call);clearInterval(channelMonitor);channel.onopen=null;if(call){call.channels.set(channel.label,channel)}debug("triggering channel:opened events for channel: "+channel.label);signaller.emit.apply(signaller,["channel:opened"].concat(args));signaller.emit.apply(signaller,["channel:opened:"+channel.label].concat(args))}debug("channel "+channel.label+" discovered for peer: "+data.id);if(channel.readyState==="open"){return channelReady()}debug("channel not ready, current state = "+channel.readyState);channel.onopen=channelReady;channelMonitor=setInterval(function(){debug("checking channel state, current state = "+channel.readyState);if(channel.readyState==="open"){channelReady()}},500)}function handleLocalAnnounce(data){if(data&&typeof data.room!="undefined"){room=data.room}}function handlePeerAnnounce(data){var pc;var monitor;if(data.room!==room){return}pc=rtc.createConnection(opts,(opts||{}).constraints);signaller.emit("peer:connect",data.id,pc,data);callCreate(data.id,pc,data);localStreams.forEach(function(stream,idx){pc.addStream(stream)});if(signaller.isMaster(data.id)){debug("is master, creating data channels: ",Object.keys(channels));Object.keys(channels).forEach(function(label){gotPeerChannel(pc.createDataChannel(label,channels[label]),pc,data)})}else{pc.ondatachannel=function(evt){var channel=evt&&evt.channel;if(!channel){return}if(channels[channel.label]!==undefined){gotPeerChannel(channel,pc,data)}}}debug("coupling "+signaller.id+" to "+data.id);monitor=rtc.couple(pc,data.id,signaller,opts);signaller.emit("peer:couple",data.id,pc,data,monitor);monitor.once("connected",callStart.bind(null,data.id,pc,data));monitor.once("closed",callEnd.bind(null,data.id));if(signaller.isMaster(data.id)){monitor.createOffer()}}function handlePeerUpdate(data){var id=data&&data.id;var activeCall=id&&calls.get(id);if(id&&!activeCall){debug("received peer update from peer "+id+", no active calls");return handlePeerAnnounce(data)}}function receiveRemoteStream(id){var call=calls.get(id);return function(stream){signaller.emit("stream:added",id,stream,call&&call.data)}}function updateRemoteStreams(id){var call=calls.get(id);if(call&&call.pc){call.streams=[].concat(call.pc.getRemoteStreams())}}if(!room){if(!hash){hash=location.hash=""+Math.pow(2,53)*Math.random()}room=ns+"#"+hash}if(debugging){rtc.logger.enable.apply(rtc.logger,Array.isArray(debug)?debugging:["*"])}signaller.on("peer:announce",handlePeerAnnounce);signaller.on("peer:update",handlePeerUpdate);signaller.on("peer:leave",callEnd);signaller.broadcast=signaller.addStream=function(stream){localStreams.push(stream);calls.values().forEach(function(data){data.pc.addStream(stream)});checkReadyToAnnounce();return signaller};signaller.endCalls=function(){calls.keys().forEach(callEnd)};signaller.close=function(){signaller.endCalls();signaller.leave()};signaller.createDataChannel=function(label,opts){calls.keys().forEach(function(peerId){var call=calls.get(peerId);var dc;if(call&&call.pc&&signaller.isMaster(peerId)){dc=call.pc.createDataChannel(label,opts);gotPeerChannel(dc,call.pc,call.data)}});channels[label]=opts||null;return signaller};signaller.reactive=function(){opts=opts||{};opts.reactive=true;return signaller};signaller.removeStream=function(stream){var localIndex=localStreams.indexOf(stream);calls.values().forEach(function(call){call.pc.removeStream(stream)});if(localIndex>=0){localStreams.splice(localIndex,1)}return signaller};signaller.requestChannel=function(targetId,label,callback){var call=getActiveCall(targetId);var channel=call&&call.channels.get(label);if(channel){callback(null,channel);return signaller}signaller.once("channel:opened:"+label,function(id,dc){callback(null,dc)});return signaller};signaller.requestStream=function(targetId,idx,callback){var call=getActiveCall(targetId);var stream;function waitForStream(peerId){if(peerId!==targetId){return}stream=call.pc.getRemoteStreams()[idx];if(stream){signaller.removeListener("stream:added",waitForStream);callback(null,stream)}}stream=call.pc.getRemoteStreams()[idx];if(stream){callback(null,stream);return signaller}signaller.on("stream:added",waitForStream);return signaller};signaller.profile=function(data){extend(profile,data);if(announced){signaller.announce(profile)}return signaller};signaller.waitForCall=function(targetId,callback){var call=calls.get(targetId);if(call&&call.active){callback(null,call.pc);return signaller}signaller.on("call:started",function handleNewCall(id){if(id===targetId){signaller.removeListener("call:started",handleNewCall);callback(null,calls.get(id).pc)}})};signaller.on("local:announce",handleLocalAnnounce);checkReadyToAnnounce();return signaller}}).call(this,require("_process"))},{_process:1,"cog/defaults":2,"cog/extend":3,"cog/getable":4,"rtc-signaller":11,"rtc-tools":27,"rtc-tools/cleanup":23}]},{},[]);require=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<r.length;o++)s(r[o]);return s}({sillyname:[function(require,module,exports){var defaultPlayerName="Player Name";var adjectives=["Black","White","Gray","Brown","Red","Pink","Crimson","Carnelian","Orange","Yellow","Ivory","Cream","Green","Viridian","Aquamarine","Cyan","Blue","Cerulean","Azure","Indigo","Navy","Violet","Purple","Lavender","Magenta","Rainbow","Iridescent","Spectrum","Prism","Bold","Vivid","Pale","Clear","Glass","Translucent","Misty","Dark","Light","Gold","Silver","Copper","Bronze","Steel","Iron","Brass","Mercury","Zinc","Chrome","Platinum","Titanium","Nickel","Lead","Pewter","Rust","Metal","Stone","Quartz","Granite","Marble","Alabaster","Agate","Jasper","Pebble","Pyrite","Crystal","Geode","Obsidian","Mica","Flint","Sand","Gravel","Boulder","Basalt","Ruby","Beryl","Scarlet","Citrine","Sulpher","Topaz","Amber","Emerald","Malachite","Jade","Abalone","Lapis","Sapphire","Diamond","Peridot","Gem","Jewel","Bevel","Coral","Jet","Ebony","Wood","Tree","Cherry","Maple","Cedar","Branch","Bramble","Rowan","Ash","Fir","Pine","Cactus","Alder","Grove","Forest","Jungle","Palm","Bush","Mulberry","Juniper","Vine","Ivy","Rose","Lily","Tulip","Daffodil","Honeysuckle","Fuschia","Hazel","Walnut","Almond","Lime","Lemon","Apple","Blossom","Bloom","Crocus","Rose","Buttercup","Dandelion","Iris","Carnation","Fern","Root","Branch","Leaf","Seed","Flower","Petal","Pollen","Orchid","Mangrove","Cypress","Sequoia","Sage","Heather","Snapdragon","Daisy","Mountain","Hill","Alpine","Chestnut","Valley","Glacier","Forest","Grove","Glen","Tree","Thorn","Stump","Desert","Canyon","Dune","Oasis","Mirage","Well","Spring","Meadow","Field","Prairie","Grass","Tundra","Island","Shore","Sand","Shell","Surf","Wave","Foam","Tide","Lake","River","Brook","Stream","Pool","Pond","Sun","Sprinkle","Shade","Shadow","Rain","Cloud","Storm","Hail","Snow","Sleet","Thunder","Lightning","Wind","Hurricane","Typhoon","Dawn","Sunrise","Morning","Noon","Twilight","Evening","Sunset","Midnight","Night","Sky","Star","Stellar","Comet","Nebula","Quasar","Solar","Lunar","Planet","Meteor","Sprout","Pear","Plum","Kiwi","Berry","Apricot","Peach","Mango","Pineapple","Coconut","Olive","Ginger","Root","Plain","Fancy","Stripe","Spot","Speckle","Spangle","Ring","Band","Blaze","Paint","Pinto","Shade","Tabby","Brindle","Patch","Calico","Checker","Dot","Pattern","Glitter","Glimmer","Shimmer","Dull","Dust","Dirt","Glaze","Scratch","Quick","Swift","Fast","Slow","Clever","Fire","Flicker","Flash","Spark","Ember","Coal","Flame","Chocolate","Vanilla","Sugar","Spice","Cake","Pie","Cookie","Candy","Caramel","Spiral","Round","Jelly","Square","Narrow","Long","Short","Small","Tiny","Big","Giant","Great","Atom","Peppermint","Mint","Butter","Fringe","Rag","Quilt","Truth","Lie","Holy","Curse","Noble","Sly","Brave","Shy","Lava","Foul","Leather","Fantasy","Keen","Luminous","Feather","Sticky","Gossamer","Cotton","Rattle","Silk","Satin","Cord","Denim","Flannel","Plaid","Wool","Linen","Silent","Flax","Weak","Valiant","Fierce","Gentle","Rhinestone","Splash","North","South","East","West","Summer","Winter","Autumn","Spring","Season","Equinox","Solstice","Paper","Motley","Torch","Ballistic","Rampant","Shag","Freckle","Wild","Free","Chain","Sheer","Crazy","Mad","Candle","Ribbon","Lace","Notch","Wax","Shine","Shallow","Deep","Bubble","Harvest","Fluff","Venom","Boom","Slash","Rune","Cold","Quill","Love","Hate","Garnet","Zircon","Power","Bone","Void","Horn","Glory","Cyber","Nova","Hot","Helix","Cosmic","Quark","Quiver","Holly","Clover","Polar","Regal","Ripple","Ebony","Wheat","Phantom","Dew","Chisel","Crack","Chatter","Laser","Foil","Tin","Clever","Treasure","Maze","Twisty","Curly","Fortune","Fate","Destiny","Cute","Slime","Ink","Disco","Plume","Time","Psychadelic","Relic","Fossil","Water","Savage","Ancient","Rapid","Road","Trail","Stitch","Button","Bow","Nimble","Zest","Sour","Bitter","Phase","Fan","Frill","Plump","Pickle","Mud","Puddle","Pond","River","Spring","Stream","Battle","Arrow","Plume","Roan","Pitch","Tar","Cat","Dog","Horse","Lizard","Bird","Fish","Saber","Scythe","Sharp","Soft","Razor","Neon","Dandy","Weed","Swamp","Marsh","Bog","Peat","Moor","Muck","Mire","Grave","Fair","Just","Brick","Puzzle","Skitter","Prong","Fork","Dent","Dour","Warp","Luck","Coffee","Split","Chip","Hollow","Heavy","Legend","Hickory","Mesquite","Nettle","Rogue","Charm","Prickle","Bead","Sponge","Whip","Bald","Frost","Fog","Oil","Veil","Cliff","Volcano","Rift","Maze","Proud","Dew","Mirror","Shard","Salt","Pepper","Honey","Thread","Bristle","Ripple","Glow","Zenith"];var nouns=["head","crest","crown","tooth","fang","horn","frill","skull","bone","tongue","throat","voice","nose","snout","chin","eye","sight","seer","speaker","singer","song","chanter","howler","chatter","shrieker","shriek","jaw","bite","biter","neck","shoulder","fin","wing","arm","lifter","grasp","grabber","hand","paw","foot","finger","toe","thumb","talon","palm","touch","racer","runner","hoof","fly","flier","swoop","roar","hiss","hisser","snarl","dive","diver","rib","chest","back","ridge","leg","legs","tail","beak","walker","lasher","swisher","carver","kicker","roarer","crusher","spike","shaker","charger","hunter","weaver","crafter","binder","scribe","muse","snap","snapper","slayer","stalker","track","tracker","scar","scarer","fright","killer","death","doom","healer","saver","friend","foe","guardian","thunder","lightning","cloud","storm","forger","scale","hair","braid","nape","belly","thief","stealer","reaper","giver","taker","dancer","player","gambler","twister","turner","painter","dart","drifter","sting","stinger","venom","spur","ripper","swallow","devourer","knight","lady","lord","queen","king","master","mistress","prince","princess","duke","dutchess","samurai","ninja","knave","slave","servant","sage","wizard","witch","warlock","warrior","jester","paladin","bard","trader","sword","shield","knife","dagger","arrow","bow","fighter","bane","follower","leader","scourge","watcher","cat","panther","tiger","cougar","puma","jaguar","ocelot","lynx","lion","leopard","ferret","weasel","wolverine","bear","raccoon","dog","wolf","kitten","puppy","cub","fox","hound","terrier","coyote","hyena","jackal","pig","horse","donkey","stallion","mare","zebra","antelope","gazelle","deer","buffalo","bison","boar","elk","whale","dolphin","shark","fish","minnow","salmon","ray","fisher","otter","gull","duck","goose","crow","raven","bird","eagle","raptor","hawk","falcon","moose","heron","owl","stork","crane","sparrow","robin","parrot","cockatoo","carp","lizard","gecko","iguana","snake","python","viper","boa","condor","vulture","spider","fly","scorpion","heron","oriole","toucan","bee","wasp","hornet","rabbit","bunny","hare","brow","mustang","ox","piper","soarer","flasher","moth","mask","hide","hero","antler","chill","chiller","gem","ogre","myth","elf","fairy","pixie","dragon","griffin","unicorn","pegasus","sprite","fancier","chopper","slicer","skinner","butterfly","legend","wanderer","rover","raver","loon","lancer","glass","glazer","flame","crystal","lantern","lighter","cloak","bell","ringer","keeper","centaur","bolt","catcher","whimsey","quester","rat","mouse","serpent","wyrm","gargoyle","thorn","whip","rider","spirit","sentry","bat","beetle","burn","cowl","stone","gem","collar","mark","grin","scowl","spear","razor","edge","seeker","jay","ape","monkey","gorilla","koala","kangaroo","yak","sloth","ant","roach","weed","seed","eater","razor","shirt","face","goat","mind","shift","rider","face","mole","vole","pirate","llama","stag","bug","cap","boot","drop","hugger","sargent","snagglefoot","carpet","curtain"];function randomNoun(){return nouns[Math.floor(Math.random()*nouns.length)]}function randomAdjective(){return adjectives[Math.floor(Math.random()*adjectives.length)]}function generateStupidName(){var noun1=randomNoun();var noun2=randomNoun();noun2=noun2.substr(0,1).toUpperCase()+noun2.substr(1);var adjective=randomAdjective();return adjective+noun1+" "+noun2}module.exports=generateStupidName;module.exports.randomNoun=randomNoun;module.exports.randomAdjective=randomAdjective},{}]},{},[]);var rtcDataStream=require("rtc-data-stream");var quickconnect=require("rtc-quickconnect");var generateName=require("sillyname");var output=document.createElement("textarea");output.style.width="100%";output.style.height="80%";output.style.resize="none";document.body.appendChild(output);document.body.appendChild(document.createElement("br"));var input=document.createElement("input");input.style.width="100%";input.style.height="20%";input.placeholder="type here to chat...";document.body.appendChild(input);input.addEventListener("keydown",function(){if(event.keyCode==13){var message=input.value;input.value="";broadcast(message);showMessage("me",message);event.preventDefault();event.stopPropagation()}});function showMessage(origin,message){if(output.value)output.value+="\n";if(origin)output.value+=origin+": ";output.value+=message;output.scrollTop=99999}var peers=[];quickconnect("http://rtc.io/switchboard",{room:"rtc-data-stream-demo"}).createDataChannel("chat").on("channel:opened:chat",function(id,dc){var username=generateName();username=username.split(" ").join("_");showMessage(null,username+" joined...");var rtc=rtcDataStream(dc);rtc.on("data",function(data){showMessage(username,data)});peers.push(rtc)});function broadcast(message){console.log(message);peers.forEach(function(rtc){rtc.write(message)})}
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"rtc-data-stream": "0.0.2",
"rtc-quickconnect": "2.7.0",
"sillyname": "0.0.3"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.