diff --git a/.travis.yml b/.travis.yml index 3bffc6ec..677c775a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,13 +2,16 @@ sudo: false language: node_js node_js: "4.0" script: +- gulp build - mocha test/cov.js --reporter mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js - npm install -g bower - bower install getstream - #node test/browser/runner.js +- npm run sauce addons: sauce_connect: true env: global: - - secure: KKcEWcF2eDpiU7HaHEQyHDXB81J1T41r3TQpFxKHIZoyns3P8ualSXQZIAq2XW0Szwkixd7sRpmKG36YGiMiYHivd0SQ1FzzUDcCUqvO4Vvr4Gdws2eJbTfjNDtRQXzhRx4GhkSADYqVI8rjusQmWAO+A4scy0KI5LmDSS1JTw0= - - secure: Rkd2w0xYZX47FM3u4SCMvHluWtB7SlfMEc3C2/AvgZBVDmzknI5LtCAohJhmVkSZZvlhxPRgFir3CVfZeP5V3IBsIwrLeOSVDQ0FOnpvZsQt1wxCHhebVdL681ufYDB8cjwbAegaaTZjoLCzIhfX6r69f90qhI/MZ1ERebW2U9E= + - secure: QmxG6aSNZfZlrXcA92/NzX2GNNzcyiFMwEVi9iC2AnHhcm2/YKBtJHQy2AlMpKOON80UZuzYHpKely7jOOASJ7Blr7S4e6uiJR5lPCsW5RFxylY81z1MGhYtMu/64Yau64dFu9Uzue07jwRLVwbLp/jQgkPT3/i/G4qAsx6gK6c= + - secure: FlnXcxMo1nfcsW2V8N/n6ZcVsdyxGS+opiaZNhnQNRotPBgGUYeysDVAdKENV1OPMLO3RCasxtxJc9l2vwQVHN6OpuLLqfuWuqK6ZlnlTSCZNHBNSSX0JyaKpu4/Kx9NF2Q2LWMN3dP8QhMG69OIP9Pzv9R0/jpI4+HOlOSWT5Y= + # - secure: KKcEWcF2eDpiU7HaHEQyHDXB81J1T41r3TQpFxKHIZoyns3P8ualSXQZIAq2XW0Szwkixd7sRpmKG36YGiMiYHivd0SQ1FzzUDcCUqvO4Vvr4Gdws2eJbTfjNDtRQXzhRx4GhkSADYqVI8rjusQmWAO+A4scy0KI5LmDSS1JTw0= + # - secure: Rkd2w0xYZX47FM3u4SCMvHluWtB7SlfMEc3C2/AvgZBVDmzknI5LtCAohJhmVkSZZvlhxPRgFir3CVfZeP5V3IBsIwrLeOSVDQ0FOnpvZsQt1wxCHhebVdL681ufYDB8cjwbAegaaTZjoLCzIhfX6r69f90qhI/MZ1ERebW2U9E= diff --git a/dist/js/getstream.js b/dist/js/getstream.js index 398c83c4..9e5f87a6 100644 --- a/dist/js/getstream.js +++ b/dist/js/getstream.js @@ -401,7 +401,9 @@ return /******/ (function(modules) { // webpackBootstrap */ var description = this.node ? 'node' : 'browser'; // TODO: get the version here in a way which works in both and browserify - var version = 'unknown'; + + var version = __webpack_require__(14).version; + return 'stream-javascript-client-' + description + '-' + version; }, @@ -514,7 +516,7 @@ return /******/ (function(modules) { // webpackBootstrap kwargs.headers = {}; // auto-detect authentication type and set HTTP headers accordingly - if (signing.isJWTSignature(signature)) { + if (signature && signing.isJWTSignature(signature)) { kwargs.headers['stream-auth-type'] = 'jwt'; signature = signature.split(' ').reverse()[0]; } else { @@ -690,7 +692,7 @@ return /******/ (function(modules) { // webpackBootstrap * @param {array} events List of events to track * @return {string} The redirect url */ - var url = __webpack_require__(14); + var url = __webpack_require__(15); var uri = url.parse(targetUrl); if (!(uri.host || uri.hostname && uri.port) && !uri.isUnix) { @@ -1864,7 +1866,7 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; var Faye = { - VERSION: '1.1.1', + VERSION: '1.1.2', BAYEUX_VERSION: '1.0', ID_LENGTH: 160, @@ -3555,8 +3557,8 @@ return /******/ (function(modules) { // webpackBootstrap if (!this.batching) return Faye.Promise.fulfilled(this.request([message])); this._outbox.push(message); - this._flushLargeBatch(); this._promise = this._promise || new Faye.Promise(); + this._flushLargeBatch(); if (message.channel === Faye.Channel.HANDSHAKE) { this.addTimeout('publish', 0.01, this._flush, this); @@ -4230,7 +4232,7 @@ return /******/ (function(modules) { // webpackBootstrap var promise = new Faye.Promise(); this.callback(function(socket) { - if (!socket) return; + if (!socket || socket.readyState !== 1) return; socket.send(Faye.toJSON(messages)); Faye.Promise.fulfill(promise, socket); }, this); @@ -4507,6 +4509,7 @@ return /******/ (function(modules) { // webpackBootstrap request: function(messages) { var xhrClass = Faye.ENV.XDomainRequest ? XDomainRequest : XMLHttpRequest, xhr = new xhrClass(), + id = ++Faye.Transport.CORS._id, headers = this._dispatcher.headers, self = this, key; @@ -4523,6 +4526,7 @@ return /******/ (function(modules) { // webpackBootstrap var cleanUp = function() { if (!xhr) return false; + Faye.Transport.CORS._pending.remove(id); xhr.onload = xhr.onerror = xhr.ontimeout = xhr.onprogress = null; xhr = null; }; @@ -4547,10 +4551,17 @@ return /******/ (function(modules) { // webpackBootstrap }; xhr.onprogress = function() {}; + + if (xhrClass === Faye.ENV.XDomainRequest) + Faye.Transport.CORS._pending.add({id: id, xhr: xhr}); + xhr.send(this.encode(messages)); return xhr; } }), { + _id: 0, + _pending: new Faye.Set(), + isUsable: function(dispatcher, endpoint, callback, context) { if (Faye.URI.isSameOrigin(endpoint)) return callback.call(context, false); @@ -4711,6 +4722,88 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, /* 14 */ +/***/ function(module, exports) { + + module.exports = { + "author": { + "name": "Thierry Schellenbach", + "company": "Stream.io Inc" + }, + "name": "getstream", + "description": "The official low-level GetStream.io client for Node.js and the browser.", + "main": "./src/getstream.js", + "homepage": "https://getstream.io/", + "version": "3.0.0", + "browser": { + "request": "browser-request", + "crypto": false, + "jsonwebtoken": false, + "./src/lib/batch_operations.js": false, + "qs": false, + "url": false + }, + "config": { + "blanket": { + "pattern": "src", + "data-cover-never": [ + "node_modules" + ] + } + }, + "devDependencies": { + "async": "~0.9.0", + "babel-core": "^5.8.25", + "babel-loader": "^5.3.2", + "blanket": "~1.1.6", + "bluebird": "^2.1.3", + "connect": "^3.0.1", + "coveralls": "~2.10.1", + "expect.js": "~0.3.1", + "gulp": "^3.8.7", + "gulp-browserify": "^0.5.0", + "gulp-bump": "^0.1.8", + "gulp-git": "git://github.com/stevelacy/gulp-git.git", + "gulp-jscs": "^3.0.1", + "gulp-jscs-stylish": "^1.2.1", + "gulp-jshint": "^1.6.3", + "gulp-mocha": "^0.4.1", + "gulp-shell": "^0.2.7", + "gulp-uglify": "~0.3.1", + "gulp-util": "^2.2.17", + "jshint-stylish": "^2.0.1", + "json-loader": "^0.5.4", + "mocha": "^1.20.1", + "mocha-lcov-reporter": "0.0.1", + "mocha-sauce": "git://github.com/pbakaus/mocha-sauce.git", + "quickcheck": "0.0.4", + "serve-static": "^1.2.3", + "vinyl-source-stream": "^1.1.0", + "webpack": "^1.12.2" + }, + "license": "BSD", + "dependencies": { + "Base64": "^0.3.0", + "browser-request": "matthisk/browser-request", + "faye": "^1.0.1", + "http-signature": "^1.0.2", + "jsonwebtoken": "^5.0.1", + "qs": "^5.2.0", + "request": "2.63.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/GetStream/stream-js.git" + }, + "scripts": { + "test": "gulp test" + }, + "engines": { + "node": ">=0.8 <0.11" + } + }; + +/***/ }, +/* 15 */ /***/ function(module, exports) { /* (ignored) */ diff --git a/dist/js_min/getstream.js b/dist/js_min/getstream.js index 2805488f..c3dd0bc7 100644 --- a/dist/js_min/getstream.js +++ b/dist/js_min/getstream.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.stream=t():e.stream=t()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="dist/",t(0)}([function(e,t,n){(function(t){"use strict";function i(e,n,i,s){if("undefined"!=typeof t&&t.env.STREAM_URL&&!e){var o=/https\:\/\/(\w+)\:(\w+)\@([\w-]*).*\?app_id=(\d+)/.exec(t.env.STREAM_URL);e=o[1],n=o[2];var a=o[3];i=o[4],void 0===s&&(s={}),"getstream"!==a&&(s.location=a)}return new r(e,n,i,s)}var r=n(2),s=n(5),o=n(3);e.exports.connect=i,e.exports.errors=s,e.exports.request=o,e.exports.Client=r}).call(t,n(1))},function(e){function t(){c=!1,s.length?a=s.concat(a):u=-1,a.length&&n()}function n(){if(!c){var e=setTimeout(t);c=!0;for(var n=a.length;n;){for(s=a,a=[];++u1)for(var r=1;r>18&63,s=c>>12&63,o=c>>6&63,a=63&c,d[l++]=u.charAt(r)+u.charAt(s)+u.charAt(o)+u.charAt(a);while(h299)&&i.error){e=new Error("CouchDB error: "+(i.error.reason||i.error.error));for(var r in i)e[r]=i[r];return n(e,t,i)}return n(e,t,i)}"string"==typeof e&&(e={uri:e}),e.json=!0,e.body&&(e.json=e.body),delete e.body,n=n||i;var s=t(e,r);return s},e.exports=t},function(e,t,n){"use strict";var i=n(5),r=n(6),s=function(){this.initialize.apply(this,arguments)};s.prototype={initialize:function(e,t,n,i){this.client=e,this.slug=t,this.userId=n,this.id=this.slug+":"+this.userId,this.token=i,this.feedUrl=this.id.replace(":","/"),this.feedTogether=this.id.replace(":",""),this.signature=this.feedTogether+" "+this.token,this.notificationChannel="site-"+this.client.appId+"-feed-"+this.feedTogether},addActivity:function(e,t){return e=this.client.signActivity(e),this.client.post({url:"feed/"+this.feedUrl+"/",body:e,signature:this.signature},t)},removeActivity:function(e,t){var n=e.foreignId?e.foreignId:e,i={};return e.foreignId&&(i.foreign_id="1"),this.client["delete"]({url:"feed/"+this.feedUrl+"/"+n+"/",qs:i,signature:this.signature},t)},addActivities:function(e,t){e=this.client.signActivities(e);var n={activities:e},i=this.client.post({url:"feed/"+this.feedUrl+"/",body:n,signature:this.signature},t);return i},follow:function(e,t,n,i){r.validateFeedSlug(e),r.validateUserId(t);var s,o=arguments[arguments.length-1];i=o.call?o:void 0;var a=e+":"+t;n&&!n.call&&n.limit&&(s=n.limit);var c={target:a};return s&&(c.activity_copy_limit=s),this.client.post({url:"feed/"+this.feedUrl+"/following/",body:c,signature:this.signature},i)},unfollow:function(e,t,n){r.validateFeedSlug(e),r.validateUserId(t);var i=e+":"+t,s=this.client["delete"]({url:"feed/"+this.feedUrl+"/following/"+i+"/",signature:this.signature},n);return s},following:function(e,t){return void 0!==e&&e.filter&&(e.filter=e.filter.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/following/",qs:e,signature:this.signature},t)},followers:function(e,t){return void 0!==e&&e.filter&&(e.filter=e.filter.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/followers/",qs:e,signature:this.signature},t)},get:function(e,t){return e&&e.mark_read&&e.mark_read.join&&(e.mark_read=e.mark_read.join(",")),e&&e.mark_seen&&e.mark_seen.join&&(e.mark_seen=e.mark_seen.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/",qs:e,signature:this.signature},t)},getFayeClient:function(){return this.client.getFayeClient()},subscribe:function(e){if(!this.client.appId)throw new i.SiteError("Missing app id, which is needed to subscribe, use var client = stream.connect(key, secret, appId);");return this.client.subscriptions["/"+this.notificationChannel]={token:this.token,userId:this.notificationChannel},this.getFayeClient().subscribe("/"+this.notificationChannel,e)}},e.exports=s},function(e){"use strict";function t(e,t){this.message=e,Error.call(this,this.message),i?Error.captureStackTrace(this,t):this.stack=r?(new Error).stack:""}var n=e.exports,i="function"==typeof Error.captureStackTrace,r=!!(new Error).stack;n._Abstract=t,t.prototype=new Error,n.FeedError=function(e){t.call(this,e)},n.FeedError.prototype=new t,n.SiteError=function(e){t.call(this,e)},n.SiteError.prototype=new t,n.MissingSchemaError=function(e){t.call(this,e)},n.MissingSchemaError.prototype=new t},function(e,t,n){"use strict";function i(e){var t=e.split(":");if(2!==t.length)throw new a.FeedError("Invalid feedId, expected something like user:1 got "+e);var n=t[0],i=t[1];return r(n),s(i),e}function r(e){var t=c.test(e);if(!t)throw new a.FeedError("Invalid feedSlug, please use letters, numbers or _ got: "+e);return e}function s(e){var t=c.test(e);if(!t)throw new a.FeedError("Invalid feedSlug, please use letters, numbers or _ got: "+e);return e}function o(e){return e.replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var a=n(5),c=/^[\w-]+$/;t.validateFeedId=i,t.validateFeedSlug=r,t.validateUserId=s,t.rfc3986=o},function(e,t,n){"use strict";function i(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_");return t.replace(/^=+/,"").replace(/=+$/,"")}function r(e){try{return f.atob(a(e))}catch(t){if("InvalidCharacterError"===t.name)return void 0;throw t}}function s(e){if("object"==typeof e)return e;try{return JSON.parse(e)}catch(t){return void 0}}function o(e){var t=4,n=e.length%t;if(!n)return e;for(var i=t-n;i--;)e+="=";return e}function a(e){var t=o(e).replace(/\-/g,"+").replace(/_/g,"/");return t}function c(e){var t=e.split(".",1)[0];return s(r(t))}var u=n(8),h=n(9),l=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/,f=n(10);t.headerFromJWS=c,t.sign=function(e,t){var n=new u.createHash("sha1").update(e).digest(),r=u.createHmac("sha1",n),s=r.update(t).digest("base64"),o=i(s);return o},t.JWTScopeToken=function(e,t,n,i){var r=i||{},s=r.expireTokens?!r.expireTokens:!0,o={resource:t,action:n};r.feedId&&(o.feed_id=r.feedId),r.userId&&(o.user_id=r.userId);var a=h.sign(o,e,{algorithm:"HS256",noTimestamp:s});return a},t.isJWTSignature=function(e){var t=e.split(" ")[1];return l.test(t)&&!!c(t)}},function(){},function(){"use strict"},function(e,t){!function(){function e(e){this.message=e}var n=t,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",n.btoa||(n.btoa=function(t){for(var n,r,s=String(t),o=0,a=i,c="";s.charAt(0|o)||(a="=",o%1);c+=a.charAt(63&n>>8-o%1*8)){if(r=s.charCodeAt(o+=.75),r>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|r}return c}),n.atob||(n.atob=function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,s,o=0,a=0,c="";s=n.charAt(a++);~s&&(r=o%4?64*r+s:s,o++%4)?c+=String.fromCharCode(255&r>>(-2*o&6)):0)s=i.indexOf(s);return c})}()},function(e,t,n){"use strict";var i=n(12).Promise;i.prototype["catch"]=function(e){return this.then(null,e)},e.exports=i},function(module,exports,__webpack_require__){(function(global,setImmediate,process){!function(){"use strict";var Faye={VERSION:"1.1.1",BAYEUX_VERSION:"1.0",ID_LENGTH:160,JSONP_CALLBACK:"jsonpcallback",CONNECTION_TYPES:["long-polling","cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],MANDATORY_CONNECTION_TYPES:["long-polling","callback-polling","in-process"],ENV:"undefined"!=typeof window?window:global,extend:function(e,t,n){if(!t)return e;for(var i in t)t.hasOwnProperty(i)&&(e.hasOwnProperty(i)&&n===!1||e[i]!==t[i]&&(e[i]=t[i]));return e},random:function(e){e=e||this.ID_LENGTH;for(var t=Math.ceil(e*Math.log(2)/Math.log(36)),n=csprng(e,36);n.lengthn;n++)if(-1!==this.indexOf(t,e[n]))return e[n];return null},indexOf:function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,i=e.length;i>n;n++)if(e[n]===t)return n;return-1},map:function(e,t,n){if(e.map)return e.map(t,n);var i=[];if(e instanceof Array)for(var r=0,s=e.length;s>r;r++)i.push(t.call(n||null,e[r],r));else for(var o in e)e.hasOwnProperty(o)&&i.push(t.call(n||null,o,e[o]));return i},filter:function(e,t,n){if(e.filter)return e.filter(t,n);for(var i=[],r=0,s=e.length;s>r;r++)t.call(n||null,e[r],r)&&i.push(e[r]);return i},asyncEach:function(e,t,n,i){var r=e.length,s=-1,o=0,a=!1,c=function(){return o-=1,s+=1,s===r?n&&n.call(i):(t(e[s],h),void 0)},u=function(){if(!a){for(a=!0;o>0;)c();a=!1}},h=function(){o+=1,u()};h()},toJSON:function(e){return this.stringify?this.stringify(e,function(e,t){return this[e]instanceof Array?this[e]:t}):JSON.stringify(e)}};module.exports=Faye,Faye.Class=function(e,t){"function"!=typeof e&&(t=e,e=Object);var n=function(){return this.initialize?this.initialize.apply(this,arguments)||this:this},i=function(){};return i.prototype=e.prototype,n.prototype=new i,Faye.extend(n.prototype,t),n},function(){function e(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;ns;s++)r[s].apply(this,i);return!0}return!1},t.prototype.addListener=function(e,t){if("function"!=typeof t)throw new Error("addListener only takes instances of Function");return this._events||(this._events={}),this.emit("newListener",e,t),this._events[e]?n(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){var n=this;return n.on(e,function i(){n.removeListener(e,i),t.apply(this,arguments)}),this},t.prototype.removeListener=function(t,i){if("function"!=typeof i)throw new Error("removeListener only takes instances of Function");if(!this._events||!this._events[t])return this;var r=this._events[t];if(n(r)){var s=e(r,i);if(0>s)return this;r.splice(s,1),0==r.length&&delete this._events[t]}else this._events[t]===i&&delete this._events[t];return this},t.prototype.removeAllListeners=function(e){return 0===arguments.length?(this._events={},this):(e&&this._events&&this._events[e]&&(this._events[e]=null),this)},t.prototype.listeners=function(e){return this._events||(this._events={}),this._events[e]||(this._events[e]=[]),n(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]}}(),Faye.Namespace=Faye.Class({initialize:function(){this._used={}},exists:function(e){return this._used.hasOwnProperty(e)},generate:function(){for(var e=Faye.random();this._used.hasOwnProperty(e);)e=Faye.random();return this._used[e]=e},release:function(e){delete this._used[e]}}),function(){var e,t=setTimeout;e="function"==typeof setImmediate?function(e){setImmediate(e)}:"object"==typeof process&&process.nextTick?function(e){process.nextTick(e)}:function(e){t(e,0)};var n=0,i=1,r=2,s=function(e){return e},o=function(e){throw e},a=function(e){if(this._state=n,this._onFulfilled=[],this._onRejected=[],"function"==typeof e){var t=this;e(function(e){f(t,e)},function(e){p(t,e)})}};a.prototype.then=function(e,t){var n=new a;return c(this,e,n),u(this,t,n),n};var c=function(e,t,r){"function"!=typeof t&&(t=s);var o=function(e){h(t,e,r)};e._state===n?e._onFulfilled.push(o):e._state===i&&o(e._value)},u=function(e,t,i){"function"!=typeof t&&(t=o);var s=function(e){h(t,e,i)};e._state===n?e._onRejected.push(s):e._state===r&&s(e._reason)},h=function(t,n,i){e(function(){l(t,n,i)})},l=function(e,t,n){var i;try{i=e(t)}catch(r){return p(n,r)}i===n?p(n,new TypeError("Recursive promise chain detected")):f(n,i)},f=a.fulfill=a.resolve=function(e,t){var n,i,r=!1;try{if(n=typeof t,i=null!==t&&("function"===n||"object"===n)&&t.then,"function"!=typeof i)return d(e,t);i.call(t,function(t){r^(r=!0)&&f(e,t)},function(t){r^(r=!0)&&p(e,t)})}catch(s){if(!(r^(r=!0)))return;p(e,s)}},d=function(e,t){if(e._state===n){e._state=i,e._value=t,e._onRejected=[];for(var r,s=e._onFulfilled;r=s.shift();)r(t)}},p=a.reject=function(e,t){if(e._state===n){e._state=r,e._reason=t,e._onFulfilled=[];for(var i,s=e._onRejected;i=s.shift();)i(t)}};a.all=function(e){return new a(function(t,n){var i,r=[],s=e.length;if(0===s)return t(r);for(i=0;s>i;i++)(function(e,i){a.fulfilled(e).then(function(e){r[i]=e,0===--s&&t(r)},n)})(e[i],i)})},a.defer=e,a.deferred=a.pending=function(){var e={};return e.promise=new a(function(t,n){e.fulfill=e.resolve=t,e.reject=n}),e},a.fulfilled=a.resolved=function(e){return new a(function(t){t(e)})},a.rejected=function(e){return new a(function(t,n){n(e)})},"undefined"==typeof Faye?module.exports=a:Faye.Promise=a}(),Faye.Set=Faye.Class({initialize:function(){this._index={}},add:function(e){var t=void 0!==e.id?e.id:e;return this._index.hasOwnProperty(t)?!1:(this._index[t]=e,!0)},forEach:function(e,t){for(var n in this._index)this._index.hasOwnProperty(n)&&e.call(t,this._index[n])},isEmpty:function(){for(var e in this._index)if(this._index.hasOwnProperty(e))return!1;return!0},member:function(e){for(var t in this._index)if(this._index[t]===e)return!0;return!1},remove:function(e){var t=void 0!==e.id?e.id:e,n=this._index[t];return delete this._index[t],n},toArray:function(){var e=[];return this.forEach(function(t){e.push(t)}),e}}),Faye.URI={isURI:function(e){return e&&e.protocol&&e.host&&e.path},isSameOrigin:function(e){var t=Faye.ENV.location;return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port},parse:function(e){if("string"!=typeof e)return e;var t,n,i,r,s,o,a={},c=function(t,n){e=e.replace(n,function(e){return a[t]=e,""}),a[t]=a[t]||""};for(c("protocol",/^[a-z]+\:/i),c("host",/^\/\/[^\/\?#]+/),/^\//.test(e)||a.host||(e=Faye.ENV.location.pathname.replace(/[^\/]*$/,"")+e),c("pathname",/^[^\?#]*/),c("search",/^\?[^#]*/),c("hash",/^#.*/),a.protocol=a.protocol||Faye.ENV.location.protocol,a.host?(a.host=a.host.substr(2),t=a.host.split(":"),a.hostname=t[0],a.port=t[1]||""):(a.host=Faye.ENV.location.host,a.hostname=Faye.ENV.location.hostname,a.port=Faye.ENV.location.port),a.pathname=a.pathname||"/",a.path=a.pathname+a.search,n=a.search.replace(/^\?/,""),i=n?n.split("&"):[],o={},r=0,s=i.length;s>r;r++)t=i[r].split("="),o[decodeURIComponent(t[0]||"")]=decodeURIComponent(t[1]||"");return a.query=o,a.href=this.stringify(a),a},stringify:function(e){var t=e.protocol+"//"+e.hostname;return e.port&&(t+=":"+e.port),t+=e.pathname+this.queryString(e.query)+(e.hash||"")},queryString:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return 0===t.length?"":"?"+t.join("&")}},Faye.Error=Faye.Class({initialize:function(e,t,n){this.code=e,this.params=Array.prototype.slice.call(t),this.message=n},toString:function(){return this.code+":"+this.params.join(",")+":"+this.message}}),Faye.Error.parse=function(e){if(e=e||"",!Faye.Grammar.ERROR.test(e))return new this(null,[],e);var t=e.split(":"),n=parseInt(t[0]),i=t[1].split(","),e=t[2];return new this(n,i,e)},Faye.Error.versionMismatch=function(){return new this(300,arguments,"Version mismatch").toString()},Faye.Error.conntypeMismatch=function(){return new this(301,arguments,"Connection types not supported").toString()},Faye.Error.extMismatch=function(){return new this(302,arguments,"Extension mismatch").toString()},Faye.Error.badRequest=function(){return new this(400,arguments,"Bad request").toString()},Faye.Error.clientUnknown=function(){return new this(401,arguments,"Unknown client").toString()},Faye.Error.parameterMissing=function(){return new this(402,arguments,"Missing required parameter").toString()},Faye.Error.channelForbidden=function(){return new this(403,arguments,"Forbidden channel").toString()},Faye.Error.channelUnknown=function(){return new this(404,arguments,"Unknown channel").toString()},Faye.Error.channelInvalid=function(){return new this(405,arguments,"Invalid channel").toString()},Faye.Error.extUnknown=function(){return new this(406,arguments,"Unknown extension").toString()},Faye.Error.publishFailed=function(){return new this(407,arguments,"Failed to publish").toString()},Faye.Error.serverError=function(){return new this(500,arguments,"Internal server error").toString()},Faye.Deferrable={then:function(e,t){var n=this;return this._promise||(this._promise=new Faye.Promise(function(e,t){n._fulfill=e,n._reject=t})),0===arguments.length?this._promise:this._promise.then(e,t)},callback:function(e,t){return this.then(function(n){e.call(t,n)})},errback:function(e,t){return this.then(null,function(n){e.call(t,n)})},timeout:function(e,t){this.then();var n=this;this._timer=Faye.ENV.setTimeout(function(){n._reject(t)},1e3*e)},setDeferredStatus:function(e,t){this._timer&&Faye.ENV.clearTimeout(this._timer),this.then(),"succeeded"===e?this._fulfill(t):"failed"===e?this._reject(t):delete this._promise}},Faye.Publisher={countListeners:function(e){return this.listeners(e).length},bind:function(e,t,n){var i=Array.prototype.slice,r=function(){t.apply(n,i.call(arguments))};return this._listeners=this._listeners||[],this._listeners.push([e,t,n,r]),this.on(e,r)},unbind:function(e,t,n){this._listeners=this._listeners||[];for(var i,r=this._listeners.length;r--;)i=this._listeners[r],i[0]===e&&(!t||i[1]===t&&i[2]===n)&&(this._listeners.splice(r,1),this.removeListener(e,i[3]))}},Faye.extend(Faye.Publisher,Faye.EventEmitter.prototype),Faye.Publisher.trigger=Faye.Publisher.emit,Faye.Timeouts={addTimeout:function(e,t,n,i){if(this._timeouts=this._timeouts||{},!this._timeouts.hasOwnProperty(e)){var r=this;this._timeouts[e]=Faye.ENV.setTimeout(function(){delete r._timeouts[e],n.call(i)},1e3*t)}},removeTimeout:function(e){this._timeouts=this._timeouts||{};var t=this._timeouts[e];t&&(Faye.ENV.clearTimeout(t),delete this._timeouts[e])},removeAllTimeouts:function(){this._timeouts=this._timeouts||{};for(var e in this._timeouts)this.removeTimeout(e)}},Faye.Logging={LOG_LEVELS:{fatal:4,error:3,warn:2,info:1,debug:0},writeLog:function(e,t){if(Faye.logger){var n=Array.prototype.slice.apply(e),i="[Faye",r=this.className,s=n.shift().replace(/\?/g,function(){try{return Faye.toJSON(n.shift())}catch(e){return"[Object]"}});for(var o in Faye)r||"function"==typeof Faye[o]&&this instanceof Faye[o]&&(r=o);r&&(i+="."+r),i+="] ","function"==typeof Faye.logger[t]?Faye.logger[t](i+s):"function"==typeof Faye.logger&&Faye.logger(i+s)}}},function(){for(var e in Faye.Logging.LOG_LEVELS)(function(e){Faye.Logging[e]=function(){this.writeLog(arguments,e)}})(e)}(),Faye.Grammar={CHANNEL_NAME:/^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,CHANNEL_PATTERN:/^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,ERROR:/^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/,VERSION:/^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/},Faye.Extensible={addExtension:function(e){this._extensions=this._extensions||[],this._extensions.push(e),e.added&&e.added(this)},removeExtension:function(e){if(this._extensions)for(var t=this._extensions.length;t--;)this._extensions[t]===e&&(this._extensions.splice(t,1),e.removed&&e.removed(this))},pipeThroughExtensions:function(e,t,n,i,r){if(this.debug("Passing through ? extensions: ?",e,t),!this._extensions)return i.call(r,t);var s=this._extensions.slice(),o=function(t){if(!t)return i.call(r,t); -var a=s.shift();if(!a)return i.call(r,t);var c=a[e];return c?(c.length>=3?a[e](t,n,o):a[e](t,o),void 0):o(t)};o(t)}},Faye.extend(Faye.Extensible,Faye.Logging),Faye.Channel=Faye.Class({initialize:function(e){this.id=this.name=e},push:function(e){this.trigger("message",e)},isUnused:function(){return 0===this.countListeners("message")}}),Faye.extend(Faye.Channel.prototype,Faye.Publisher),Faye.extend(Faye.Channel,{HANDSHAKE:"/meta/handshake",CONNECT:"/meta/connect",SUBSCRIBE:"/meta/subscribe",UNSUBSCRIBE:"/meta/unsubscribe",DISCONNECT:"/meta/disconnect",META:"meta",SERVICE:"service",expand:function(e){var t=this.parse(e),n=["/**",e],i=t.slice();i[i.length-1]="*",n.push(this.unparse(i));for(var r=1,s=t.length;s>r;r++)i=t.slice(0,r),i.push("**"),n.push(this.unparse(i));return n},isValid:function(e){return Faye.Grammar.CHANNEL_NAME.test(e)||Faye.Grammar.CHANNEL_PATTERN.test(e)},parse:function(e){return this.isValid(e)?e.split("/").slice(1):null},unparse:function(e){return"/"+e.join("/")},isMeta:function(e){var t=this.parse(e);return t?t[0]===this.META:null},isService:function(e){var t=this.parse(e);return t?t[0]===this.SERVICE:null},isSubscribable:function(e){return this.isValid(e)?!this.isMeta(e)&&!this.isService(e):null},Set:Faye.Class({initialize:function(){this._channels={}},getKeys:function(){var e=[];for(var t in this._channels)e.push(t);return e},remove:function(e){delete this._channels[e]},hasSubscription:function(e){return this._channels.hasOwnProperty(e)},subscribe:function(e,t,n){for(var i,r=0,s=e.length;s>r;r++){i=e[r];var o=this._channels[i]=this._channels[i]||new Faye.Channel(i);t&&o.bind("message",t,n)}},unsubscribe:function(e,t,n){var i=this._channels[e];return i?(i.unbind("message",t,n),i.isUnused()?(this.remove(e),!0):!1):!1},distributeMessage:function(e){for(var t=Faye.Channel.expand(e.channel),n=0,i=t.length;i>n;n++){var r=this._channels[t[n]];r&&r.trigger("message",e.data)}}})}),Faye.Publication=Faye.Class(Faye.Deferrable),Faye.Subscription=Faye.Class({initialize:function(e,t,n,i){this._client=e,this._channels=t,this._callback=n,this._context=i,this._cancelled=!1},cancel:function(){this._cancelled||(this._client.unsubscribe(this._channels,this._callback,this._context),this._cancelled=!0)},unsubscribe:function(){this.cancel()}}),Faye.extend(Faye.Subscription.prototype,Faye.Deferrable),Faye.Client=Faye.Class({UNCONNECTED:1,CONNECTING:2,CONNECTED:3,DISCONNECTED:4,HANDSHAKE:"handshake",RETRY:"retry",NONE:"none",CONNECTION_TIMEOUT:60,DEFAULT_ENDPOINT:"/bayeux",INTERVAL:0,initialize:function(e,t){this.info("New client created for ?",e),t=t||{},Faye.validateOptions(t,["interval","timeout","endpoints","proxy","retry","scheduler","websocketExtensions","tls","ca"]),this._endpoint=e||this.DEFAULT_ENDPOINT,this._channels=new Faye.Channel.Set,this._dispatcher=new Faye.Dispatcher(this,this._endpoint,t),this._messageId=0,this._state=this.UNCONNECTED,this._responseCallbacks={},this._advice={reconnect:this.RETRY,interval:1e3*(t.interval||this.INTERVAL),timeout:1e3*(t.timeout||this.CONNECTION_TIMEOUT)},this._dispatcher.timeout=this._advice.timeout/1e3,this._dispatcher.bind("message",this._receiveMessage,this),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.indexOf(this._dispatcher._disabled,"autodisconnect")<0&&this.disconnect()},this)},addWebsocketExtension:function(e){return this._dispatcher.addWebsocketExtension(e)},disable:function(e){return this._dispatcher.disable(e)},setHeader:function(e,t){return this._dispatcher.setHeader(e,t)},handshake:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state===this.UNCONNECTED){this._state=this.CONNECTING;var n=this;this.info("Initiating handshake with ?",Faye.URI.stringify(this._endpoint)),this._dispatcher.selectTransport(Faye.MANDATORY_CONNECTION_TYPES),this._sendMessage({channel:Faye.Channel.HANDSHAKE,version:Faye.BAYEUX_VERSION,supportedConnectionTypes:this._dispatcher.getConnectionTypes()},{},function(i){i.successful?(this._state=this.CONNECTED,this._dispatcher.clientId=i.clientId,this._dispatcher.selectTransport(i.supportedConnectionTypes),this.info("Handshake successful: ?",this._dispatcher.clientId),this.subscribe(this._channels.getKeys(),!0),e&&Faye.Promise.defer(function(){e.call(t)})):(this.info("Handshake unsuccessful"),Faye.ENV.setTimeout(function(){n.handshake(e,t)},1e3*this._dispatcher.retry),this._state=this.UNCONNECTED)},this)}},connect:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state!==this.DISCONNECTED){if(this._state===this.UNCONNECTED)return this.handshake(function(){this.connect(e,t)},this);this.callback(e,t),this._state===this.CONNECTED&&(this.info("Calling deferred actions for ?",this._dispatcher.clientId),this.setDeferredStatus("succeeded"),this.setDeferredStatus("unknown"),this._connectRequest||(this._connectRequest=!0,this.info("Initiating connection for ?",this._dispatcher.clientId),this._sendMessage({channel:Faye.Channel.CONNECT,clientId:this._dispatcher.clientId,connectionType:this._dispatcher.connectionType},{},this._cycleConnection,this)))}},disconnect:function(){if(this._state===this.CONNECTED){this._state=this.DISCONNECTED,this.info("Disconnecting ?",this._dispatcher.clientId);var e=new Faye.Publication;return this._sendMessage({channel:Faye.Channel.DISCONNECT,clientId:this._dispatcher.clientId},{},function(t){t.successful?(this._dispatcher.close(),e.setDeferredStatus("succeeded")):e.setDeferredStatus("failed",Faye.Error.parse(t.error))},this),this.info("Clearing channel listeners for ?",this._dispatcher.clientId),this._channels=new Faye.Channel.Set,e}},subscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.subscribe(e,t,n)},this);var i=new Faye.Subscription(this,e,t,n),r=t===!0,s=this._channels.hasSubscription(e);return s&&!r?(this._channels.subscribe([e],t,n),i.setDeferredStatus("succeeded"),i):(this.connect(function(){this.info("Client ? attempting to subscribe to ?",this._dispatcher.clientId,e),r||this._channels.subscribe([e],t,n),this._sendMessage({channel:Faye.Channel.SUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(r){if(!r.successful)return i.setDeferredStatus("failed",Faye.Error.parse(r.error)),this._channels.unsubscribe(e,t,n);var s=[].concat(r.subscription);this.info("Subscription acknowledged for ? to ?",this._dispatcher.clientId,s),i.setDeferredStatus("succeeded")},this)},this),i)},unsubscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.unsubscribe(e,t,n)},this);var i=this._channels.unsubscribe(e,t,n);i&&this.connect(function(){this.info("Client ? attempting to unsubscribe from ?",this._dispatcher.clientId,e),this._sendMessage({channel:Faye.Channel.UNSUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(e){if(e.successful){var t=[].concat(e.subscription);this.info("Unsubscription acknowledged for ? from ?",this._dispatcher.clientId,t)}},this)},this)},publish:function(e,t,n){Faye.validateOptions(n||{},["attempts","deadline"]);var i=new Faye.Publication;return this.connect(function(){this.info("Client ? queueing published message to ?: ?",this._dispatcher.clientId,e,t),this._sendMessage({channel:e,data:t,clientId:this._dispatcher.clientId},n,function(e){e.successful?i.setDeferredStatus("succeeded"):i.setDeferredStatus("failed",Faye.Error.parse(e.error))},this)},this),i},_sendMessage:function(e,t,n,i){e.id=this._generateMessageId();var r=this._advice.timeout?1.2*this._advice.timeout/1e3:1.2*this._dispatcher.retry;this.pipeThroughExtensions("outgoing",e,null,function(e){e&&(n&&(this._responseCallbacks[e.id]=[n,i]),this._dispatcher.sendMessage(e,r,t||{}))},this)},_generateMessageId:function(){return this._messageId+=1,this._messageId>=Math.pow(2,32)&&(this._messageId=0),this._messageId.toString(36)},_receiveMessage:function(e){var t,n=e.id;void 0!==e.successful&&(t=this._responseCallbacks[n],delete this._responseCallbacks[n]),this.pipeThroughExtensions("incoming",e,null,function(e){e&&(e.advice&&this._handleAdvice(e.advice),this._deliverMessage(e),t&&t[0].call(t[1],e))},this)},_handleAdvice:function(e){Faye.extend(this._advice,e),this._dispatcher.timeout=this._advice.timeout/1e3,this._advice.reconnect===this.HANDSHAKE&&this._state!==this.DISCONNECTED&&(this._state=this.UNCONNECTED,this._dispatcher.clientId=null,this._cycleConnection())},_deliverMessage:function(e){e.channel&&void 0!==e.data&&(this.info("Client ? calling listeners for ? with ?",this._dispatcher.clientId,e.channel,e.data),this._channels.distributeMessage(e))},_cycleConnection:function(){this._connectRequest&&(this._connectRequest=null,this.info("Closed connection for ?",this._dispatcher.clientId));var e=this;Faye.ENV.setTimeout(function(){e.connect()},this._advice.interval)}}),Faye.extend(Faye.Client.prototype,Faye.Deferrable),Faye.extend(Faye.Client.prototype,Faye.Publisher),Faye.extend(Faye.Client.prototype,Faye.Logging),Faye.extend(Faye.Client.prototype,Faye.Extensible),Faye.Dispatcher=Faye.Class({MAX_REQUEST_SIZE:2048,DEFAULT_RETRY:5,UP:1,DOWN:2,initialize:function(e,t,n){this._client=e,this.endpoint=Faye.URI.parse(t),this._alternates=n.endpoints||{},this.cookies=Faye.Cookies&&new Faye.Cookies.CookieJar,this._disabled=[],this._envelopes={},this.headers={},this.retry=n.retry||this.DEFAULT_RETRY,this._scheduler=n.scheduler||Faye.Scheduler,this._state=0,this.transports={},this.wsExtensions=[],this.proxy=n.proxy||{},"string"==typeof this._proxy&&(this._proxy={origin:this._proxy});var i=n.websocketExtensions;if(i){i=[].concat(i);for(var r=0,s=i.length;s>r;r++)this.addWebsocketExtension(i[r])}this.tls=n.tls||{},this.tls.ca=this.tls.ca||n.ca;for(var o in this._alternates)this._alternates[o]=Faye.URI.parse(this._alternates[o]);this.maxRequestSize=this.MAX_REQUEST_SIZE},endpointFor:function(e){return this._alternates[e]||this.endpoint},addWebsocketExtension:function(e){this.wsExtensions.push(e)},disable:function(e){this._disabled.push(e)},setHeader:function(e,t){this.headers[e]=t},close:function(){var e=this._transport;delete this._transport,e&&e.close()},getConnectionTypes:function(){return Faye.Transport.getConnectionTypes()},selectTransport:function(e){Faye.Transport.get(this,e,this._disabled,function(e){this.debug("Selected ? transport for ?",e.connectionType,Faye.URI.stringify(e.endpoint)),e!==this._transport&&(this._transport&&this._transport.close(),this._transport=e,this.connectionType=e.connectionType)},this)},sendMessage:function(e,t,n){n=n||{};var i,r=e.id,s=n.attempts,o=n.deadline&&(new Date).getTime()+1e3*n.deadline,a=this._envelopes[r];a||(i=new this._scheduler(e,{timeout:t,interval:this.retry,attempts:s,deadline:o}),a=this._envelopes[r]={message:e,scheduler:i}),this._sendEnvelope(a)},_sendEnvelope:function(e){if(this._transport&&!e.request&&!e.timer){var t=e.message,n=e.scheduler,i=this;if(!n.isDeliverable())return n.abort(),delete this._envelopes[t.id],void 0;e.timer=Faye.ENV.setTimeout(function(){i.handleError(t)},1e3*n.getTimeout()),n.send(),e.request=this._transport.sendMessage(t)}},handleResponse:function(e){var t=this._envelopes[e.id];void 0!==e.successful&&t&&(t.scheduler.succeed(),delete this._envelopes[e.id],Faye.ENV.clearTimeout(t.timer)),this.trigger("message",e),this._state!==this.UP&&(this._state=this.UP,this._client.trigger("transport:up"))},handleError:function(e,t){var n=this._envelopes[e.id],i=n&&n.request,r=this;if(i){i.then(function(e){e&&e.abort&&e.abort()});var s=n.scheduler;s.fail(),Faye.ENV.clearTimeout(n.timer),n.request=n.timer=null,t?this._sendEnvelope(n):n.timer=Faye.ENV.setTimeout(function(){n.timer=null,r._sendEnvelope(n)},1e3*s.getInterval()),this._state!==this.DOWN&&(this._state=this.DOWN,this._client.trigger("transport:down"))}}}),Faye.extend(Faye.Dispatcher.prototype,Faye.Publisher),Faye.extend(Faye.Dispatcher.prototype,Faye.Logging),Faye.Scheduler=function(e,t){this.message=e,this.options=t,this.attempts=0},Faye.extend(Faye.Scheduler.prototype,{getTimeout:function(){return this.options.timeout},getInterval:function(){return this.options.interval},isDeliverable:function(){var e=this.options.attempts,t=this.attempts,n=this.options.deadline,i=(new Date).getTime();return void 0!==e&&t>=e?!1:void 0!==n&&i>n?!1:!0},send:function(){this.attempts+=1},succeed:function(){},fail:function(){},abort:function(){}}),Faye.Transport=Faye.extend(Faye.Class({DEFAULT_PORTS:{"http:":80,"https:":443,"ws:":80,"wss:":443},SECURE_PROTOCOLS:["https:","wss:"],MAX_DELAY:0,batching:!0,initialize:function(e,t){this._dispatcher=e,this.endpoint=t,this._outbox=[],this._proxy=Faye.extend({},this._dispatcher.proxy),!this._proxy.origin&&Faye.NodeAdapter&&(this._proxy.origin=Faye.indexOf(this.SECURE_PROTOCOLS,this.endpoint.protocol)>=0?process.env.HTTPS_PROXY||process.env.https_proxy:process.env.HTTP_PROXY||process.env.http_proxy)},close:function(){},encode:function(){return""},sendMessage:function(e){return this.debug("Client ? sending message to ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),e),this.batching?(this._outbox.push(e),this._flushLargeBatch(),this._promise=this._promise||new Faye.Promise,e.channel===Faye.Channel.HANDSHAKE?(this.addTimeout("publish",.01,this._flush,this),this._promise):(e.channel===Faye.Channel.CONNECT&&(this._connectMessage=e),this.addTimeout("publish",this.MAX_DELAY,this._flush,this),this._promise)):Faye.Promise.fulfilled(this.request([e]))},_flush:function(){this.removeTimeout("publish"),this._outbox.length>1&&this._connectMessage&&(this._connectMessage.advice={timeout:0}),Faye.Promise.fulfill(this._promise,this.request(this._outbox)),delete this._promise,this._connectMessage=null,this._outbox=[]},_flushLargeBatch:function(){var e=this.encode(this._outbox);if(!(e.lengtht;t++)this._dispatcher.handleResponse(e[t])}},_handleError:function(e){e=[].concat(e),this.debug("Client ? failed to send to ? via ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),this.connectionType,e);for(var t=0,n=e.length;n>t;t++)this._dispatcher.handleError(e[t])},_getCookies:function(){var e=this._dispatcher.cookies,t=Faye.URI.stringify(this.endpoint);return e?Faye.map(e.getCookiesSync(t),function(e){return e.cookieString()}).join("; "):""},_storeCookies:function(e){var t,n=this._dispatcher.cookies,i=Faye.URI.stringify(this.endpoint);if(e&&n){e=[].concat(e);for(var r=0,s=e.length;s>r;r++)t=Faye.Cookies.Cookie.parse(e[r]),n.setCookieSync(t,i)}}}),{get:function(e,t,n,i,r){var s=e.endpoint;Faye.asyncEach(this._transports,function(s,o){var a=s[0],c=s[1],u=e.endpointFor(a);return Faye.indexOf(n,a)>=0?o():Faye.indexOf(t,a)<0?(c.isUsable(e,u,function(){}),o()):(c.isUsable(e,u,function(t){if(!t)return o();var n=c.hasOwnProperty("create")?c.create(e,u):new c(e,u);i.call(r,n)}),void 0)},function(){throw new Error("Could not find a usable connection type for "+Faye.URI.stringify(s))})},register:function(e,t){this._transports.push([e,t]),t.prototype.connectionType=e},getConnectionTypes:function(){return Faye.map(this._transports,function(e){return e[0]})},_transports:[]}),Faye.extend(Faye.Transport.prototype,Faye.Logging),Faye.extend(Faye.Transport.prototype,Faye.Timeouts),Faye.Event={_registry:[],on:function(e,t,n,i){var r=function(){n.call(i)};e.addEventListener?e.addEventListener(t,r,!1):e.attachEvent("on"+t,r),this._registry.push({_element:e,_type:t,_callback:n,_context:i,_handler:r})},detach:function(e,t,n,i){for(var r,s=this._registry.length;s--;)r=this._registry[s],e&&e!==r._element||t&&t!==r._type||n&&n!==r._callback||i&&i!==r._context||(r._element.removeEventListener?r._element.removeEventListener(r._type,r._handler,!1):r._element.detachEvent("on"+r._type,r._handler),this._registry.splice(s,1),r=null)}},void 0!==Faye.ENV.onunload&&Faye.Event.on(Faye.ENV,"unload",Faye.Event.detach,Faye.Event),"object"!=typeof JSON&&(JSON={}),function(){function f(e){return 10>e?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,i,r,s,o,a=gap,c=t[e];switch(c&&"object"==typeof c&&"function"==typeof c.toJSON&&(c=c.toJSON(e)),"function"==typeof rep&&(c=rep.call(t,e,c)),typeof c){case"string":return quote(c);case"number":return isFinite(c)?String(c):"null";case"boolean":case"null":return String(c);case"object":if(!c)return"null";if(gap+=indent,o=[],"[object Array]"===Object.prototype.toString.apply(c)){for(s=c.length,n=0;s>n;n+=1)o[n]=str(n,c)||"null";return r=0===o.length?"[]":gap?"[\n"+gap+o.join(",\n"+gap)+"\n"+a+"]":"["+o.join(",")+"]",gap=a,r}if(rep&&"object"==typeof rep)for(s=rep.length,n=0;s>n;n+=1)"string"==typeof rep[n]&&(i=rep[n],r=str(i,c),r&&o.push(quote(i)+(gap?": ":":")+r));else for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(r=str(i,c),r&&o.push(quote(i)+(gap?": ":":")+r));return r=0===o.length?"{}":gap?"{\n"+gap+o.join(",\n"+gap)+"\n"+a+"}":"{"+o.join(",")+"}",gap=a,r}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;Faye.stringify=function(e,t,n){var i;if(gap="",indent="","number"==typeof n)for(i=0;n>i;i+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw new Error("JSON.stringify");return str("",{"":e})},"function"!=typeof JSON.stringify&&(JSON.stringify=Faye.stringify),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(e,t){var n,i,r=e[t];if(r&&"object"==typeof r)for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(i=walk(r,n),void 0!==i?r[n]=i:delete r[n]);return reviver.call(e,t,r)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),Faye.Transport.WebSocket=Faye.extend(Faye.Class(Faye.Transport,{UNCONNECTED:1,CONNECTING:2,CONNECTED:3,batching:!1,isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)}),this.connect()},request:function(e){this._pending=this._pending||new Faye.Set;for(var t=0,n=e.length;n>t;t++)this._pending.add(e[t]);var i=new Faye.Promise;return this.callback(function(t){t&&(t.send(Faye.toJSON(e)),Faye.Promise.fulfill(i,t))},this),this.connect(),{abort:function(){i.then(function(e){e.close()})}}},connect:function(){if(!Faye.Transport.WebSocket._unloaded&&(this._state=this._state||this.UNCONNECTED,this._state===this.UNCONNECTED)){this._state=this.CONNECTING;var e=this._createSocket();if(!e)return this.setDeferredStatus("failed");var t=this;e.onopen=function(){e.headers&&t._storeCookies(e.headers["set-cookie"]),t._socket=e,t._state=t.CONNECTED,t._everConnected=!0,t._ping(),t.setDeferredStatus("succeeded",e)};var n=!1;e.onclose=e.onerror=function(){if(!n){n=!0;var i=t._state===t.CONNECTED;e.onopen=e.onclose=e.onerror=e.onmessage=null,delete t._socket,t._state=t.UNCONNECTED,t.removeTimeout("ping"),t.setDeferredStatus("unknown");var r=t._pending?t._pending.toArray():[];delete t._pending,i?t._handleError(r,!0):t._everConnected?t._handleError(r):t.setDeferredStatus("failed")}},e.onmessage=function(e){var n=JSON.parse(e.data);if(n){n=[].concat(n);for(var i=0,r=n.length;r>i;i++)void 0!==n[i].successful&&t._pending.remove(n[i]);t._receive(n)}}}},close:function(){this._socket&&this._socket.close()},_createSocket:function(){var e=Faye.Transport.WebSocket.getSocketUrl(this.endpoint),t=this._dispatcher.headers,n=this._dispatcher.wsExtensions,i=this._getCookies(),r=this._dispatcher.tls,s={extensions:n,headers:t,proxy:this._proxy,tls:r};return""!==i&&(s.headers.Cookie=i),Faye.WebSocket?new Faye.WebSocket.Client(e,[],s):Faye.ENV.MozWebSocket?new MozWebSocket(e):Faye.ENV.WebSocket?new WebSocket(e):void 0},_ping:function(){this._socket&&(this._socket.send("[]"),this.addTimeout("ping",this._dispatcher.timeout/2,this._ping,this))}}),{PROTOCOLS:{"http:":"ws:","https:":"wss:"},create:function(e,t){var n=e.transports.websocket=e.transports.websocket||{};return n[t.href]=n[t.href]||new this(e,t),n[t.href]},getSocketUrl:function(e){return e=Faye.copyObject(e),e.protocol=this.PROTOCOLS[e.protocol],Faye.URI.stringify(e)},isUsable:function(e,t,n,i){this.create(e,t).isUsable(n,i)}}),Faye.extend(Faye.Transport.WebSocket.prototype,Faye.Deferrable),Faye.Transport.register("websocket",Faye.Transport.WebSocket),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.Transport.WebSocket._unloaded=!0}),Faye.Transport.EventSource=Faye.extend(Faye.Class(Faye.Transport,{initialize:function(e,t){if(Faye.Transport.prototype.initialize.call(this,e,t),!Faye.ENV.EventSource)return this.setDeferredStatus("failed");this._xhr=new Faye.Transport.XHR(e,t),t=Faye.copyObject(t),t.pathname+="/"+e.clientId;var n=new EventSource(Faye.URI.stringify(t)),i=this;n.onopen=function(){i._everConnected=!0,i.setDeferredStatus("succeeded")},n.onerror=function(){i._everConnected?i._handleError([]):(i.setDeferredStatus("failed"),n.close())},n.onmessage=function(e){i._receive(JSON.parse(e.data))},this._socket=n},close:function(){this._socket&&(this._socket.onopen=this._socket.onerror=this._socket.onmessage=null,this._socket.close(),delete this._socket)},isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)})},encode:function(e){return this._xhr.encode(e)},request:function(e){return this._xhr.request(e)}}),{isUsable:function(e,t,n,i){var r=e.clientId;return r?(Faye.Transport.XHR.isUsable(e,t,function(r){return r?(this.create(e,t).isUsable(n,i),void 0):n.call(i,!1)},this),void 0):n.call(i,!1)},create:function(e,t){var n=e.transports.eventsource=e.transports.eventsource||{},i=e.clientId,r=Faye.copyObject(t);return r.pathname+="/"+(i||""),r=Faye.URI.stringify(r),n[r]=n[r]||new this(e,t),n[r]}}),Faye.extend(Faye.Transport.EventSource.prototype,Faye.Deferrable),Faye.Transport.register("eventsource",Faye.Transport.EventSource),Faye.Transport.XHR=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return Faye.toJSON(e)},request:function(e){var t=this.endpoint.href,n=Faye.ENV.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest,i=this;n.open("POST",t,!0),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Pragma","no-cache"),n.setRequestHeader("X-Requested-With","XMLHttpRequest");var r=this._dispatcher.headers;for(var s in r)r.hasOwnProperty(s)&&n.setRequestHeader(s,r[s]);var o=function(){n.abort()};return void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){if(n&&4===n.readyState){var t=null,r=n.status,s=n.responseText,a=r>=200&&300>r||304===r||1223===r;if(void 0!==Faye.ENV.onbeforeunload&&Faye.Event.detach(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){},n=null,!a)return i._handleError(e);try{t=JSON.parse(s)}catch(c){}t?i._receive(t):i._handleError(e)}},n.send(this.encode(e)),n}}),{isUsable:function(e,t,n,i){n.call(i,Faye.URI.isSameOrigin(t))}}),Faye.Transport.register("long-polling",Faye.Transport.XHR),Faye.Transport.CORS=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return"message="+encodeURIComponent(Faye.toJSON(e))},request:function(e){var t,n=Faye.ENV.XDomainRequest?XDomainRequest:XMLHttpRequest,i=new n,r=this._dispatcher.headers,s=this;if(i.open("POST",Faye.URI.stringify(this.endpoint),!0),i.setRequestHeader){i.setRequestHeader("Pragma","no-cache");for(t in r)r.hasOwnProperty(t)&&i.setRequestHeader(t,r[t])}var o=function(){return i?(i.onload=i.onerror=i.ontimeout=i.onprogress=null,i=null,void 0):!1};return i.onload=function(){var t=null;try{t=JSON.parse(i.responseText)}catch(n){}o(),t?s._receive(t):s._handleError(e)},i.onerror=i.ontimeout=function(){o(),s._handleError(e)},i.onprogress=function(){},i.send(this.encode(e)),i}}),{isUsable:function(e,t,n,i){if(Faye.URI.isSameOrigin(t))return n.call(i,!1);if(Faye.ENV.XDomainRequest)return n.call(i,t.protocol===Faye.ENV.location.protocol);if(Faye.ENV.XMLHttpRequest){var r=new Faye.ENV.XMLHttpRequest;return n.call(i,void 0!==r.withCredentials)}return n.call(i,!1)}}),Faye.Transport.register("cross-origin-long-polling",Faye.Transport.CORS),Faye.Transport.JSONP=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){var t=Faye.copyObject(this.endpoint);return t.query.message=Faye.toJSON(e),t.query.jsonp="__jsonp"+Faye.Transport.JSONP._cbCount+"__",Faye.URI.stringify(t)},request:function(e){var t=document.getElementsByTagName("head")[0],n=document.createElement("script"),i=Faye.Transport.JSONP.getCallbackName(),r=Faye.copyObject(this.endpoint),s=this;r.query.message=Faye.toJSON(e),r.query.jsonp=i;var o=function(){if(!Faye.ENV[i])return!1;Faye.ENV[i]=void 0;try{delete Faye.ENV[i]}catch(e){}n.parentNode.removeChild(n)};return Faye.ENV[i]=function(e){o(),s._receive(e)},n.type="text/javascript",n.src=Faye.URI.stringify(r),t.appendChild(n),n.onerror=function(){o(),s._handleError(e)},{abort:o}}}),{_cbCount:0,getCallbackName:function(){return this._cbCount+=1,"__jsonp"+this._cbCount+"__"},isUsable:function(e,t,n,i){n.call(i,!0)}}),Faye.Transport.register("callback-polling",Faye.Transport.JSONP)}()}).call(exports,function(){return this}(),__webpack_require__(13).setImmediate,__webpack_require__(1))},function(e,t,n){(function(e,i){function r(e,t){this._id=e,this._clearFn=t}var s=n(1).nextTick,o=Function.prototype.apply,a=Array.prototype.slice,c={},u=0;t.setTimeout=function(){return new r(o.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new r(o.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},t.setImmediate="function"==typeof e?e:function(e){var n=u++,i=arguments.length<2?!1:a.call(arguments,1);return c[n]=!0,s(function(){c[n]&&(i?e.apply(null,i):e.call(null),t.clearImmediate(n))}),n},t.clearImmediate="function"==typeof i?i:function(e){delete c[e]}}).call(t,n(13).setImmediate,n(13).clearImmediate)},function(){}])}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.stream=t():e.stream=t()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="dist/",t(0)}([function(e,t,n){(function(t){"use strict";function i(e,n,i,s){if("undefined"!=typeof t&&t.env.STREAM_URL&&!e){var o=/https\:\/\/(\w+)\:(\w+)\@([\w-]*).*\?app_id=(\d+)/.exec(t.env.STREAM_URL);e=o[1],n=o[2];var a=o[3];i=o[4],void 0===s&&(s={}),"getstream"!==a&&(s.location=a)}return new r(e,n,i,s)}var r=n(2),s=n(5),o=n(3);e.exports.connect=i,e.exports.errors=s,e.exports.request=o,e.exports.Client=r}).call(t,n(1))},function(e){function t(){c=!1,s.length?a=s.concat(a):u=-1,a.length&&n()}function n(){if(!c){var e=setTimeout(t);c=!0;for(var n=a.length;n;){for(s=a,a=[];++u1)for(var r=1;r>18&63,s=c>>12&63,o=c>>6&63,a=63&c,d[l++]=u.charAt(r)+u.charAt(s)+u.charAt(o)+u.charAt(a);while(h299)&&i.error){e=new Error("CouchDB error: "+(i.error.reason||i.error.error));for(var r in i)e[r]=i[r];return n(e,t,i)}return n(e,t,i)}"string"==typeof e&&(e={uri:e}),e.json=!0,e.body&&(e.json=e.body),delete e.body,n=n||i;var s=t(e,r);return s},e.exports=t},function(e,t,n){"use strict";var i=n(5),r=n(6),s=function(){this.initialize.apply(this,arguments)};s.prototype={initialize:function(e,t,n,i){this.client=e,this.slug=t,this.userId=n,this.id=this.slug+":"+this.userId,this.token=i,this.feedUrl=this.id.replace(":","/"),this.feedTogether=this.id.replace(":",""),this.signature=this.feedTogether+" "+this.token,this.notificationChannel="site-"+this.client.appId+"-feed-"+this.feedTogether},addActivity:function(e,t){return e=this.client.signActivity(e),this.client.post({url:"feed/"+this.feedUrl+"/",body:e,signature:this.signature},t)},removeActivity:function(e,t){var n=e.foreignId?e.foreignId:e,i={};return e.foreignId&&(i.foreign_id="1"),this.client["delete"]({url:"feed/"+this.feedUrl+"/"+n+"/",qs:i,signature:this.signature},t)},addActivities:function(e,t){e=this.client.signActivities(e);var n={activities:e},i=this.client.post({url:"feed/"+this.feedUrl+"/",body:n,signature:this.signature},t);return i},follow:function(e,t,n,i){r.validateFeedSlug(e),r.validateUserId(t);var s,o=arguments[arguments.length-1];i=o.call?o:void 0;var a=e+":"+t;n&&!n.call&&n.limit&&(s=n.limit);var c={target:a};return s&&(c.activity_copy_limit=s),this.client.post({url:"feed/"+this.feedUrl+"/following/",body:c,signature:this.signature},i)},unfollow:function(e,t,n){r.validateFeedSlug(e),r.validateUserId(t);var i=e+":"+t,s=this.client["delete"]({url:"feed/"+this.feedUrl+"/following/"+i+"/",signature:this.signature},n);return s},following:function(e,t){return void 0!==e&&e.filter&&(e.filter=e.filter.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/following/",qs:e,signature:this.signature},t)},followers:function(e,t){return void 0!==e&&e.filter&&(e.filter=e.filter.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/followers/",qs:e,signature:this.signature},t)},get:function(e,t){return e&&e.mark_read&&e.mark_read.join&&(e.mark_read=e.mark_read.join(",")),e&&e.mark_seen&&e.mark_seen.join&&(e.mark_seen=e.mark_seen.join(",")),this.client.get({url:"feed/"+this.feedUrl+"/",qs:e,signature:this.signature},t)},getFayeClient:function(){return this.client.getFayeClient()},subscribe:function(e){if(!this.client.appId)throw new i.SiteError("Missing app id, which is needed to subscribe, use var client = stream.connect(key, secret, appId);");return this.client.subscriptions["/"+this.notificationChannel]={token:this.token,userId:this.notificationChannel},this.getFayeClient().subscribe("/"+this.notificationChannel,e)}},e.exports=s},function(e){"use strict";function t(e,t){this.message=e,Error.call(this,this.message),i?Error.captureStackTrace(this,t):this.stack=r?(new Error).stack:""}var n=e.exports,i="function"==typeof Error.captureStackTrace,r=!!(new Error).stack;n._Abstract=t,t.prototype=new Error,n.FeedError=function(e){t.call(this,e)},n.FeedError.prototype=new t,n.SiteError=function(e){t.call(this,e)},n.SiteError.prototype=new t,n.MissingSchemaError=function(e){t.call(this,e)},n.MissingSchemaError.prototype=new t},function(e,t,n){"use strict";function i(e){var t=e.split(":");if(2!==t.length)throw new a.FeedError("Invalid feedId, expected something like user:1 got "+e);var n=t[0],i=t[1];return r(n),s(i),e}function r(e){var t=c.test(e);if(!t)throw new a.FeedError("Invalid feedSlug, please use letters, numbers or _ got: "+e);return e}function s(e){var t=c.test(e);if(!t)throw new a.FeedError("Invalid feedSlug, please use letters, numbers or _ got: "+e);return e}function o(e){return e.replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var a=n(5),c=/^[\w-]+$/;t.validateFeedId=i,t.validateFeedSlug=r,t.validateUserId=s,t.rfc3986=o},function(e,t,n){"use strict";function i(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_");return t.replace(/^=+/,"").replace(/=+$/,"")}function r(e){try{return f.atob(a(e))}catch(t){if("InvalidCharacterError"===t.name)return void 0;throw t}}function s(e){if("object"==typeof e)return e;try{return JSON.parse(e)}catch(t){return void 0}}function o(e){var t=4,n=e.length%t;if(!n)return e;for(var i=t-n;i--;)e+="=";return e}function a(e){var t=o(e).replace(/\-/g,"+").replace(/_/g,"/");return t}function c(e){var t=e.split(".",1)[0];return s(r(t))}var u=n(8),h=n(9),l=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/,f=n(10);t.headerFromJWS=c,t.sign=function(e,t){var n=new u.createHash("sha1").update(e).digest(),r=u.createHmac("sha1",n),s=r.update(t).digest("base64"),o=i(s);return o},t.JWTScopeToken=function(e,t,n,i){var r=i||{},s=r.expireTokens?!r.expireTokens:!0,o={resource:t,action:n};r.feedId&&(o.feed_id=r.feedId),r.userId&&(o.user_id=r.userId);var a=h.sign(o,e,{algorithm:"HS256",noTimestamp:s});return a},t.isJWTSignature=function(e){var t=e.split(" ")[1];return l.test(t)&&!!c(t)}},function(){},function(){"use strict"},function(e,t){!function(){function e(e){this.message=e}var n=t,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",n.btoa||(n.btoa=function(t){for(var n,r,s=String(t),o=0,a=i,c="";s.charAt(0|o)||(a="=",o%1);c+=a.charAt(63&n>>8-o%1*8)){if(r=s.charCodeAt(o+=.75),r>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|r}return c}),n.atob||(n.atob=function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,s,o=0,a=0,c="";s=n.charAt(a++);~s&&(r=o%4?64*r+s:s,o++%4)?c+=String.fromCharCode(255&r>>(-2*o&6)):0)s=i.indexOf(s);return c})}()},function(e,t,n){"use strict";var i=n(12).Promise;i.prototype["catch"]=function(e){return this.then(null,e)},e.exports=i},function(module,exports,__webpack_require__){(function(global,setImmediate,process){!function(){"use strict";var Faye={VERSION:"1.1.2",BAYEUX_VERSION:"1.0",ID_LENGTH:160,JSONP_CALLBACK:"jsonpcallback",CONNECTION_TYPES:["long-polling","cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],MANDATORY_CONNECTION_TYPES:["long-polling","callback-polling","in-process"],ENV:"undefined"!=typeof window?window:global,extend:function(e,t,n){if(!t)return e;for(var i in t)t.hasOwnProperty(i)&&(e.hasOwnProperty(i)&&n===!1||e[i]!==t[i]&&(e[i]=t[i]));return e},random:function(e){e=e||this.ID_LENGTH;for(var t=Math.ceil(e*Math.log(2)/Math.log(36)),n=csprng(e,36);n.lengthn;n++)if(-1!==this.indexOf(t,e[n]))return e[n];return null},indexOf:function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,i=e.length;i>n;n++)if(e[n]===t)return n;return-1},map:function(e,t,n){if(e.map)return e.map(t,n);var i=[];if(e instanceof Array)for(var r=0,s=e.length;s>r;r++)i.push(t.call(n||null,e[r],r));else for(var o in e)e.hasOwnProperty(o)&&i.push(t.call(n||null,o,e[o]));return i},filter:function(e,t,n){if(e.filter)return e.filter(t,n);for(var i=[],r=0,s=e.length;s>r;r++)t.call(n||null,e[r],r)&&i.push(e[r]);return i},asyncEach:function(e,t,n,i){var r=e.length,s=-1,o=0,a=!1,c=function(){return o-=1,s+=1,s===r?n&&n.call(i):(t(e[s],h),void 0)},u=function(){if(!a){for(a=!0;o>0;)c();a=!1}},h=function(){o+=1,u()};h()},toJSON:function(e){return this.stringify?this.stringify(e,function(e,t){return this[e]instanceof Array?this[e]:t}):JSON.stringify(e)}};module.exports=Faye,Faye.Class=function(e,t){"function"!=typeof e&&(t=e,e=Object);var n=function(){return this.initialize?this.initialize.apply(this,arguments)||this:this},i=function(){};return i.prototype=e.prototype,n.prototype=new i,Faye.extend(n.prototype,t),n},function(){function e(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;ns;s++)r[s].apply(this,i);return!0}return!1},t.prototype.addListener=function(e,t){if("function"!=typeof t)throw new Error("addListener only takes instances of Function");return this._events||(this._events={}),this.emit("newListener",e,t),this._events[e]?n(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){var n=this;return n.on(e,function i(){n.removeListener(e,i),t.apply(this,arguments)}),this},t.prototype.removeListener=function(t,i){if("function"!=typeof i)throw new Error("removeListener only takes instances of Function");if(!this._events||!this._events[t])return this;var r=this._events[t];if(n(r)){var s=e(r,i);if(0>s)return this;r.splice(s,1),0==r.length&&delete this._events[t]}else this._events[t]===i&&delete this._events[t];return this},t.prototype.removeAllListeners=function(e){return 0===arguments.length?(this._events={},this):(e&&this._events&&this._events[e]&&(this._events[e]=null),this)},t.prototype.listeners=function(e){return this._events||(this._events={}),this._events[e]||(this._events[e]=[]),n(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]}}(),Faye.Namespace=Faye.Class({initialize:function(){this._used={}},exists:function(e){return this._used.hasOwnProperty(e)},generate:function(){for(var e=Faye.random();this._used.hasOwnProperty(e);)e=Faye.random();return this._used[e]=e},release:function(e){delete this._used[e]}}),function(){var e,t=setTimeout;e="function"==typeof setImmediate?function(e){setImmediate(e)}:"object"==typeof process&&process.nextTick?function(e){process.nextTick(e)}:function(e){t(e,0)};var n=0,i=1,r=2,s=function(e){return e},o=function(e){throw e},a=function(e){if(this._state=n,this._onFulfilled=[],this._onRejected=[],"function"==typeof e){var t=this;e(function(e){f(t,e)},function(e){p(t,e)})}};a.prototype.then=function(e,t){var n=new a;return c(this,e,n),u(this,t,n),n};var c=function(e,t,r){"function"!=typeof t&&(t=s);var o=function(e){h(t,e,r)};e._state===n?e._onFulfilled.push(o):e._state===i&&o(e._value)},u=function(e,t,i){"function"!=typeof t&&(t=o);var s=function(e){h(t,e,i)};e._state===n?e._onRejected.push(s):e._state===r&&s(e._reason)},h=function(t,n,i){e(function(){l(t,n,i)})},l=function(e,t,n){var i;try{i=e(t)}catch(r){return p(n,r)}i===n?p(n,new TypeError("Recursive promise chain detected")):f(n,i)},f=a.fulfill=a.resolve=function(e,t){var n,i,r=!1;try{if(n=typeof t,i=null!==t&&("function"===n||"object"===n)&&t.then,"function"!=typeof i)return d(e,t);i.call(t,function(t){r^(r=!0)&&f(e,t)},function(t){r^(r=!0)&&p(e,t)})}catch(s){if(!(r^(r=!0)))return;p(e,s)}},d=function(e,t){if(e._state===n){e._state=i,e._value=t,e._onRejected=[];for(var r,s=e._onFulfilled;r=s.shift();)r(t)}},p=a.reject=function(e,t){if(e._state===n){e._state=r,e._reason=t,e._onFulfilled=[];for(var i,s=e._onRejected;i=s.shift();)i(t)}};a.all=function(e){return new a(function(t,n){var i,r=[],s=e.length;if(0===s)return t(r);for(i=0;s>i;i++)(function(e,i){a.fulfilled(e).then(function(e){r[i]=e,0===--s&&t(r)},n)})(e[i],i)})},a.defer=e,a.deferred=a.pending=function(){var e={};return e.promise=new a(function(t,n){e.fulfill=e.resolve=t,e.reject=n}),e},a.fulfilled=a.resolved=function(e){return new a(function(t){t(e)})},a.rejected=function(e){return new a(function(t,n){n(e)})},"undefined"==typeof Faye?module.exports=a:Faye.Promise=a}(),Faye.Set=Faye.Class({initialize:function(){this._index={}},add:function(e){var t=void 0!==e.id?e.id:e;return this._index.hasOwnProperty(t)?!1:(this._index[t]=e,!0)},forEach:function(e,t){for(var n in this._index)this._index.hasOwnProperty(n)&&e.call(t,this._index[n])},isEmpty:function(){for(var e in this._index)if(this._index.hasOwnProperty(e))return!1;return!0},member:function(e){for(var t in this._index)if(this._index[t]===e)return!0;return!1},remove:function(e){var t=void 0!==e.id?e.id:e,n=this._index[t];return delete this._index[t],n},toArray:function(){var e=[];return this.forEach(function(t){e.push(t)}),e}}),Faye.URI={isURI:function(e){return e&&e.protocol&&e.host&&e.path},isSameOrigin:function(e){var t=Faye.ENV.location;return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port},parse:function(e){if("string"!=typeof e)return e;var t,n,i,r,s,o,a={},c=function(t,n){e=e.replace(n,function(e){return a[t]=e,""}),a[t]=a[t]||""};for(c("protocol",/^[a-z]+\:/i),c("host",/^\/\/[^\/\?#]+/),/^\//.test(e)||a.host||(e=Faye.ENV.location.pathname.replace(/[^\/]*$/,"")+e),c("pathname",/^[^\?#]*/),c("search",/^\?[^#]*/),c("hash",/^#.*/),a.protocol=a.protocol||Faye.ENV.location.protocol,a.host?(a.host=a.host.substr(2),t=a.host.split(":"),a.hostname=t[0],a.port=t[1]||""):(a.host=Faye.ENV.location.host,a.hostname=Faye.ENV.location.hostname,a.port=Faye.ENV.location.port),a.pathname=a.pathname||"/",a.path=a.pathname+a.search,n=a.search.replace(/^\?/,""),i=n?n.split("&"):[],o={},r=0,s=i.length;s>r;r++)t=i[r].split("="),o[decodeURIComponent(t[0]||"")]=decodeURIComponent(t[1]||"");return a.query=o,a.href=this.stringify(a),a},stringify:function(e){var t=e.protocol+"//"+e.hostname;return e.port&&(t+=":"+e.port),t+=e.pathname+this.queryString(e.query)+(e.hash||"")},queryString:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return 0===t.length?"":"?"+t.join("&")}},Faye.Error=Faye.Class({initialize:function(e,t,n){this.code=e,this.params=Array.prototype.slice.call(t),this.message=n},toString:function(){return this.code+":"+this.params.join(",")+":"+this.message}}),Faye.Error.parse=function(e){if(e=e||"",!Faye.Grammar.ERROR.test(e))return new this(null,[],e);var t=e.split(":"),n=parseInt(t[0]),i=t[1].split(","),e=t[2];return new this(n,i,e)},Faye.Error.versionMismatch=function(){return new this(300,arguments,"Version mismatch").toString()},Faye.Error.conntypeMismatch=function(){return new this(301,arguments,"Connection types not supported").toString()},Faye.Error.extMismatch=function(){return new this(302,arguments,"Extension mismatch").toString()},Faye.Error.badRequest=function(){return new this(400,arguments,"Bad request").toString()},Faye.Error.clientUnknown=function(){return new this(401,arguments,"Unknown client").toString()},Faye.Error.parameterMissing=function(){return new this(402,arguments,"Missing required parameter").toString()},Faye.Error.channelForbidden=function(){return new this(403,arguments,"Forbidden channel").toString()},Faye.Error.channelUnknown=function(){return new this(404,arguments,"Unknown channel").toString()},Faye.Error.channelInvalid=function(){return new this(405,arguments,"Invalid channel").toString()},Faye.Error.extUnknown=function(){return new this(406,arguments,"Unknown extension").toString()},Faye.Error.publishFailed=function(){return new this(407,arguments,"Failed to publish").toString()},Faye.Error.serverError=function(){return new this(500,arguments,"Internal server error").toString()},Faye.Deferrable={then:function(e,t){var n=this;return this._promise||(this._promise=new Faye.Promise(function(e,t){n._fulfill=e,n._reject=t})),0===arguments.length?this._promise:this._promise.then(e,t)},callback:function(e,t){return this.then(function(n){e.call(t,n)})},errback:function(e,t){return this.then(null,function(n){e.call(t,n)})},timeout:function(e,t){this.then();var n=this;this._timer=Faye.ENV.setTimeout(function(){n._reject(t)},1e3*e)},setDeferredStatus:function(e,t){this._timer&&Faye.ENV.clearTimeout(this._timer),this.then(),"succeeded"===e?this._fulfill(t):"failed"===e?this._reject(t):delete this._promise}},Faye.Publisher={countListeners:function(e){return this.listeners(e).length},bind:function(e,t,n){var i=Array.prototype.slice,r=function(){t.apply(n,i.call(arguments))};return this._listeners=this._listeners||[],this._listeners.push([e,t,n,r]),this.on(e,r)},unbind:function(e,t,n){this._listeners=this._listeners||[];for(var i,r=this._listeners.length;r--;)i=this._listeners[r],i[0]===e&&(!t||i[1]===t&&i[2]===n)&&(this._listeners.splice(r,1),this.removeListener(e,i[3]))}},Faye.extend(Faye.Publisher,Faye.EventEmitter.prototype),Faye.Publisher.trigger=Faye.Publisher.emit,Faye.Timeouts={addTimeout:function(e,t,n,i){if(this._timeouts=this._timeouts||{},!this._timeouts.hasOwnProperty(e)){var r=this;this._timeouts[e]=Faye.ENV.setTimeout(function(){delete r._timeouts[e],n.call(i)},1e3*t)}},removeTimeout:function(e){this._timeouts=this._timeouts||{};var t=this._timeouts[e];t&&(Faye.ENV.clearTimeout(t),delete this._timeouts[e])},removeAllTimeouts:function(){this._timeouts=this._timeouts||{};for(var e in this._timeouts)this.removeTimeout(e)}},Faye.Logging={LOG_LEVELS:{fatal:4,error:3,warn:2,info:1,debug:0},writeLog:function(e,t){if(Faye.logger){var n=Array.prototype.slice.apply(e),i="[Faye",r=this.className,s=n.shift().replace(/\?/g,function(){try{return Faye.toJSON(n.shift())}catch(e){return"[Object]"}});for(var o in Faye)r||"function"==typeof Faye[o]&&this instanceof Faye[o]&&(r=o);r&&(i+="."+r),i+="] ","function"==typeof Faye.logger[t]?Faye.logger[t](i+s):"function"==typeof Faye.logger&&Faye.logger(i+s)}}},function(){for(var e in Faye.Logging.LOG_LEVELS)(function(e){Faye.Logging[e]=function(){this.writeLog(arguments,e)}})(e)}(),Faye.Grammar={CHANNEL_NAME:/^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,CHANNEL_PATTERN:/^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,ERROR:/^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/,VERSION:/^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/},Faye.Extensible={addExtension:function(e){this._extensions=this._extensions||[],this._extensions.push(e),e.added&&e.added(this)},removeExtension:function(e){if(this._extensions)for(var t=this._extensions.length;t--;)this._extensions[t]===e&&(this._extensions.splice(t,1),e.removed&&e.removed(this))},pipeThroughExtensions:function(e,t,n,i,r){if(this.debug("Passing through ? extensions: ?",e,t),!this._extensions)return i.call(r,t); +var s=this._extensions.slice(),o=function(t){if(!t)return i.call(r,t);var a=s.shift();if(!a)return i.call(r,t);var c=a[e];return c?(c.length>=3?a[e](t,n,o):a[e](t,o),void 0):o(t)};o(t)}},Faye.extend(Faye.Extensible,Faye.Logging),Faye.Channel=Faye.Class({initialize:function(e){this.id=this.name=e},push:function(e){this.trigger("message",e)},isUnused:function(){return 0===this.countListeners("message")}}),Faye.extend(Faye.Channel.prototype,Faye.Publisher),Faye.extend(Faye.Channel,{HANDSHAKE:"/meta/handshake",CONNECT:"/meta/connect",SUBSCRIBE:"/meta/subscribe",UNSUBSCRIBE:"/meta/unsubscribe",DISCONNECT:"/meta/disconnect",META:"meta",SERVICE:"service",expand:function(e){var t=this.parse(e),n=["/**",e],i=t.slice();i[i.length-1]="*",n.push(this.unparse(i));for(var r=1,s=t.length;s>r;r++)i=t.slice(0,r),i.push("**"),n.push(this.unparse(i));return n},isValid:function(e){return Faye.Grammar.CHANNEL_NAME.test(e)||Faye.Grammar.CHANNEL_PATTERN.test(e)},parse:function(e){return this.isValid(e)?e.split("/").slice(1):null},unparse:function(e){return"/"+e.join("/")},isMeta:function(e){var t=this.parse(e);return t?t[0]===this.META:null},isService:function(e){var t=this.parse(e);return t?t[0]===this.SERVICE:null},isSubscribable:function(e){return this.isValid(e)?!this.isMeta(e)&&!this.isService(e):null},Set:Faye.Class({initialize:function(){this._channels={}},getKeys:function(){var e=[];for(var t in this._channels)e.push(t);return e},remove:function(e){delete this._channels[e]},hasSubscription:function(e){return this._channels.hasOwnProperty(e)},subscribe:function(e,t,n){for(var i,r=0,s=e.length;s>r;r++){i=e[r];var o=this._channels[i]=this._channels[i]||new Faye.Channel(i);t&&o.bind("message",t,n)}},unsubscribe:function(e,t,n){var i=this._channels[e];return i?(i.unbind("message",t,n),i.isUnused()?(this.remove(e),!0):!1):!1},distributeMessage:function(e){for(var t=Faye.Channel.expand(e.channel),n=0,i=t.length;i>n;n++){var r=this._channels[t[n]];r&&r.trigger("message",e.data)}}})}),Faye.Publication=Faye.Class(Faye.Deferrable),Faye.Subscription=Faye.Class({initialize:function(e,t,n,i){this._client=e,this._channels=t,this._callback=n,this._context=i,this._cancelled=!1},cancel:function(){this._cancelled||(this._client.unsubscribe(this._channels,this._callback,this._context),this._cancelled=!0)},unsubscribe:function(){this.cancel()}}),Faye.extend(Faye.Subscription.prototype,Faye.Deferrable),Faye.Client=Faye.Class({UNCONNECTED:1,CONNECTING:2,CONNECTED:3,DISCONNECTED:4,HANDSHAKE:"handshake",RETRY:"retry",NONE:"none",CONNECTION_TIMEOUT:60,DEFAULT_ENDPOINT:"/bayeux",INTERVAL:0,initialize:function(e,t){this.info("New client created for ?",e),t=t||{},Faye.validateOptions(t,["interval","timeout","endpoints","proxy","retry","scheduler","websocketExtensions","tls","ca"]),this._endpoint=e||this.DEFAULT_ENDPOINT,this._channels=new Faye.Channel.Set,this._dispatcher=new Faye.Dispatcher(this,this._endpoint,t),this._messageId=0,this._state=this.UNCONNECTED,this._responseCallbacks={},this._advice={reconnect:this.RETRY,interval:1e3*(t.interval||this.INTERVAL),timeout:1e3*(t.timeout||this.CONNECTION_TIMEOUT)},this._dispatcher.timeout=this._advice.timeout/1e3,this._dispatcher.bind("message",this._receiveMessage,this),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.indexOf(this._dispatcher._disabled,"autodisconnect")<0&&this.disconnect()},this)},addWebsocketExtension:function(e){return this._dispatcher.addWebsocketExtension(e)},disable:function(e){return this._dispatcher.disable(e)},setHeader:function(e,t){return this._dispatcher.setHeader(e,t)},handshake:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state===this.UNCONNECTED){this._state=this.CONNECTING;var n=this;this.info("Initiating handshake with ?",Faye.URI.stringify(this._endpoint)),this._dispatcher.selectTransport(Faye.MANDATORY_CONNECTION_TYPES),this._sendMessage({channel:Faye.Channel.HANDSHAKE,version:Faye.BAYEUX_VERSION,supportedConnectionTypes:this._dispatcher.getConnectionTypes()},{},function(i){i.successful?(this._state=this.CONNECTED,this._dispatcher.clientId=i.clientId,this._dispatcher.selectTransport(i.supportedConnectionTypes),this.info("Handshake successful: ?",this._dispatcher.clientId),this.subscribe(this._channels.getKeys(),!0),e&&Faye.Promise.defer(function(){e.call(t)})):(this.info("Handshake unsuccessful"),Faye.ENV.setTimeout(function(){n.handshake(e,t)},1e3*this._dispatcher.retry),this._state=this.UNCONNECTED)},this)}},connect:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state!==this.DISCONNECTED){if(this._state===this.UNCONNECTED)return this.handshake(function(){this.connect(e,t)},this);this.callback(e,t),this._state===this.CONNECTED&&(this.info("Calling deferred actions for ?",this._dispatcher.clientId),this.setDeferredStatus("succeeded"),this.setDeferredStatus("unknown"),this._connectRequest||(this._connectRequest=!0,this.info("Initiating connection for ?",this._dispatcher.clientId),this._sendMessage({channel:Faye.Channel.CONNECT,clientId:this._dispatcher.clientId,connectionType:this._dispatcher.connectionType},{},this._cycleConnection,this)))}},disconnect:function(){if(this._state===this.CONNECTED){this._state=this.DISCONNECTED,this.info("Disconnecting ?",this._dispatcher.clientId);var e=new Faye.Publication;return this._sendMessage({channel:Faye.Channel.DISCONNECT,clientId:this._dispatcher.clientId},{},function(t){t.successful?(this._dispatcher.close(),e.setDeferredStatus("succeeded")):e.setDeferredStatus("failed",Faye.Error.parse(t.error))},this),this.info("Clearing channel listeners for ?",this._dispatcher.clientId),this._channels=new Faye.Channel.Set,e}},subscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.subscribe(e,t,n)},this);var i=new Faye.Subscription(this,e,t,n),r=t===!0,s=this._channels.hasSubscription(e);return s&&!r?(this._channels.subscribe([e],t,n),i.setDeferredStatus("succeeded"),i):(this.connect(function(){this.info("Client ? attempting to subscribe to ?",this._dispatcher.clientId,e),r||this._channels.subscribe([e],t,n),this._sendMessage({channel:Faye.Channel.SUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(r){if(!r.successful)return i.setDeferredStatus("failed",Faye.Error.parse(r.error)),this._channels.unsubscribe(e,t,n);var s=[].concat(r.subscription);this.info("Subscription acknowledged for ? to ?",this._dispatcher.clientId,s),i.setDeferredStatus("succeeded")},this)},this),i)},unsubscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.unsubscribe(e,t,n)},this);var i=this._channels.unsubscribe(e,t,n);i&&this.connect(function(){this.info("Client ? attempting to unsubscribe from ?",this._dispatcher.clientId,e),this._sendMessage({channel:Faye.Channel.UNSUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(e){if(e.successful){var t=[].concat(e.subscription);this.info("Unsubscription acknowledged for ? from ?",this._dispatcher.clientId,t)}},this)},this)},publish:function(e,t,n){Faye.validateOptions(n||{},["attempts","deadline"]);var i=new Faye.Publication;return this.connect(function(){this.info("Client ? queueing published message to ?: ?",this._dispatcher.clientId,e,t),this._sendMessage({channel:e,data:t,clientId:this._dispatcher.clientId},n,function(e){e.successful?i.setDeferredStatus("succeeded"):i.setDeferredStatus("failed",Faye.Error.parse(e.error))},this)},this),i},_sendMessage:function(e,t,n,i){e.id=this._generateMessageId();var r=this._advice.timeout?1.2*this._advice.timeout/1e3:1.2*this._dispatcher.retry;this.pipeThroughExtensions("outgoing",e,null,function(e){e&&(n&&(this._responseCallbacks[e.id]=[n,i]),this._dispatcher.sendMessage(e,r,t||{}))},this)},_generateMessageId:function(){return this._messageId+=1,this._messageId>=Math.pow(2,32)&&(this._messageId=0),this._messageId.toString(36)},_receiveMessage:function(e){var t,n=e.id;void 0!==e.successful&&(t=this._responseCallbacks[n],delete this._responseCallbacks[n]),this.pipeThroughExtensions("incoming",e,null,function(e){e&&(e.advice&&this._handleAdvice(e.advice),this._deliverMessage(e),t&&t[0].call(t[1],e))},this)},_handleAdvice:function(e){Faye.extend(this._advice,e),this._dispatcher.timeout=this._advice.timeout/1e3,this._advice.reconnect===this.HANDSHAKE&&this._state!==this.DISCONNECTED&&(this._state=this.UNCONNECTED,this._dispatcher.clientId=null,this._cycleConnection())},_deliverMessage:function(e){e.channel&&void 0!==e.data&&(this.info("Client ? calling listeners for ? with ?",this._dispatcher.clientId,e.channel,e.data),this._channels.distributeMessage(e))},_cycleConnection:function(){this._connectRequest&&(this._connectRequest=null,this.info("Closed connection for ?",this._dispatcher.clientId));var e=this;Faye.ENV.setTimeout(function(){e.connect()},this._advice.interval)}}),Faye.extend(Faye.Client.prototype,Faye.Deferrable),Faye.extend(Faye.Client.prototype,Faye.Publisher),Faye.extend(Faye.Client.prototype,Faye.Logging),Faye.extend(Faye.Client.prototype,Faye.Extensible),Faye.Dispatcher=Faye.Class({MAX_REQUEST_SIZE:2048,DEFAULT_RETRY:5,UP:1,DOWN:2,initialize:function(e,t,n){this._client=e,this.endpoint=Faye.URI.parse(t),this._alternates=n.endpoints||{},this.cookies=Faye.Cookies&&new Faye.Cookies.CookieJar,this._disabled=[],this._envelopes={},this.headers={},this.retry=n.retry||this.DEFAULT_RETRY,this._scheduler=n.scheduler||Faye.Scheduler,this._state=0,this.transports={},this.wsExtensions=[],this.proxy=n.proxy||{},"string"==typeof this._proxy&&(this._proxy={origin:this._proxy});var i=n.websocketExtensions;if(i){i=[].concat(i);for(var r=0,s=i.length;s>r;r++)this.addWebsocketExtension(i[r])}this.tls=n.tls||{},this.tls.ca=this.tls.ca||n.ca;for(var o in this._alternates)this._alternates[o]=Faye.URI.parse(this._alternates[o]);this.maxRequestSize=this.MAX_REQUEST_SIZE},endpointFor:function(e){return this._alternates[e]||this.endpoint},addWebsocketExtension:function(e){this.wsExtensions.push(e)},disable:function(e){this._disabled.push(e)},setHeader:function(e,t){this.headers[e]=t},close:function(){var e=this._transport;delete this._transport,e&&e.close()},getConnectionTypes:function(){return Faye.Transport.getConnectionTypes()},selectTransport:function(e){Faye.Transport.get(this,e,this._disabled,function(e){this.debug("Selected ? transport for ?",e.connectionType,Faye.URI.stringify(e.endpoint)),e!==this._transport&&(this._transport&&this._transport.close(),this._transport=e,this.connectionType=e.connectionType)},this)},sendMessage:function(e,t,n){n=n||{};var i,r=e.id,s=n.attempts,o=n.deadline&&(new Date).getTime()+1e3*n.deadline,a=this._envelopes[r];a||(i=new this._scheduler(e,{timeout:t,interval:this.retry,attempts:s,deadline:o}),a=this._envelopes[r]={message:e,scheduler:i}),this._sendEnvelope(a)},_sendEnvelope:function(e){if(this._transport&&!e.request&&!e.timer){var t=e.message,n=e.scheduler,i=this;if(!n.isDeliverable())return n.abort(),delete this._envelopes[t.id],void 0;e.timer=Faye.ENV.setTimeout(function(){i.handleError(t)},1e3*n.getTimeout()),n.send(),e.request=this._transport.sendMessage(t)}},handleResponse:function(e){var t=this._envelopes[e.id];void 0!==e.successful&&t&&(t.scheduler.succeed(),delete this._envelopes[e.id],Faye.ENV.clearTimeout(t.timer)),this.trigger("message",e),this._state!==this.UP&&(this._state=this.UP,this._client.trigger("transport:up"))},handleError:function(e,t){var n=this._envelopes[e.id],i=n&&n.request,r=this;if(i){i.then(function(e){e&&e.abort&&e.abort()});var s=n.scheduler;s.fail(),Faye.ENV.clearTimeout(n.timer),n.request=n.timer=null,t?this._sendEnvelope(n):n.timer=Faye.ENV.setTimeout(function(){n.timer=null,r._sendEnvelope(n)},1e3*s.getInterval()),this._state!==this.DOWN&&(this._state=this.DOWN,this._client.trigger("transport:down"))}}}),Faye.extend(Faye.Dispatcher.prototype,Faye.Publisher),Faye.extend(Faye.Dispatcher.prototype,Faye.Logging),Faye.Scheduler=function(e,t){this.message=e,this.options=t,this.attempts=0},Faye.extend(Faye.Scheduler.prototype,{getTimeout:function(){return this.options.timeout},getInterval:function(){return this.options.interval},isDeliverable:function(){var e=this.options.attempts,t=this.attempts,n=this.options.deadline,i=(new Date).getTime();return void 0!==e&&t>=e?!1:void 0!==n&&i>n?!1:!0},send:function(){this.attempts+=1},succeed:function(){},fail:function(){},abort:function(){}}),Faye.Transport=Faye.extend(Faye.Class({DEFAULT_PORTS:{"http:":80,"https:":443,"ws:":80,"wss:":443},SECURE_PROTOCOLS:["https:","wss:"],MAX_DELAY:0,batching:!0,initialize:function(e,t){this._dispatcher=e,this.endpoint=t,this._outbox=[],this._proxy=Faye.extend({},this._dispatcher.proxy),!this._proxy.origin&&Faye.NodeAdapter&&(this._proxy.origin=Faye.indexOf(this.SECURE_PROTOCOLS,this.endpoint.protocol)>=0?process.env.HTTPS_PROXY||process.env.https_proxy:process.env.HTTP_PROXY||process.env.http_proxy)},close:function(){},encode:function(){return""},sendMessage:function(e){return this.debug("Client ? sending message to ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),e),this.batching?(this._outbox.push(e),this._promise=this._promise||new Faye.Promise,this._flushLargeBatch(),e.channel===Faye.Channel.HANDSHAKE?(this.addTimeout("publish",.01,this._flush,this),this._promise):(e.channel===Faye.Channel.CONNECT&&(this._connectMessage=e),this.addTimeout("publish",this.MAX_DELAY,this._flush,this),this._promise)):Faye.Promise.fulfilled(this.request([e]))},_flush:function(){this.removeTimeout("publish"),this._outbox.length>1&&this._connectMessage&&(this._connectMessage.advice={timeout:0}),Faye.Promise.fulfill(this._promise,this.request(this._outbox)),delete this._promise,this._connectMessage=null,this._outbox=[]},_flushLargeBatch:function(){var e=this.encode(this._outbox);if(!(e.lengtht;t++)this._dispatcher.handleResponse(e[t])}},_handleError:function(e){e=[].concat(e),this.debug("Client ? failed to send to ? via ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),this.connectionType,e);for(var t=0,n=e.length;n>t;t++)this._dispatcher.handleError(e[t])},_getCookies:function(){var e=this._dispatcher.cookies,t=Faye.URI.stringify(this.endpoint);return e?Faye.map(e.getCookiesSync(t),function(e){return e.cookieString()}).join("; "):""},_storeCookies:function(e){var t,n=this._dispatcher.cookies,i=Faye.URI.stringify(this.endpoint);if(e&&n){e=[].concat(e);for(var r=0,s=e.length;s>r;r++)t=Faye.Cookies.Cookie.parse(e[r]),n.setCookieSync(t,i)}}}),{get:function(e,t,n,i,r){var s=e.endpoint;Faye.asyncEach(this._transports,function(s,o){var a=s[0],c=s[1],u=e.endpointFor(a);return Faye.indexOf(n,a)>=0?o():Faye.indexOf(t,a)<0?(c.isUsable(e,u,function(){}),o()):(c.isUsable(e,u,function(t){if(!t)return o();var n=c.hasOwnProperty("create")?c.create(e,u):new c(e,u);i.call(r,n)}),void 0)},function(){throw new Error("Could not find a usable connection type for "+Faye.URI.stringify(s))})},register:function(e,t){this._transports.push([e,t]),t.prototype.connectionType=e},getConnectionTypes:function(){return Faye.map(this._transports,function(e){return e[0]})},_transports:[]}),Faye.extend(Faye.Transport.prototype,Faye.Logging),Faye.extend(Faye.Transport.prototype,Faye.Timeouts),Faye.Event={_registry:[],on:function(e,t,n,i){var r=function(){n.call(i)};e.addEventListener?e.addEventListener(t,r,!1):e.attachEvent("on"+t,r),this._registry.push({_element:e,_type:t,_callback:n,_context:i,_handler:r})},detach:function(e,t,n,i){for(var r,s=this._registry.length;s--;)r=this._registry[s],e&&e!==r._element||t&&t!==r._type||n&&n!==r._callback||i&&i!==r._context||(r._element.removeEventListener?r._element.removeEventListener(r._type,r._handler,!1):r._element.detachEvent("on"+r._type,r._handler),this._registry.splice(s,1),r=null)}},void 0!==Faye.ENV.onunload&&Faye.Event.on(Faye.ENV,"unload",Faye.Event.detach,Faye.Event),"object"!=typeof JSON&&(JSON={}),function(){function f(e){return 10>e?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,i,r,s,o,a=gap,c=t[e];switch(c&&"object"==typeof c&&"function"==typeof c.toJSON&&(c=c.toJSON(e)),"function"==typeof rep&&(c=rep.call(t,e,c)),typeof c){case"string":return quote(c);case"number":return isFinite(c)?String(c):"null";case"boolean":case"null":return String(c);case"object":if(!c)return"null";if(gap+=indent,o=[],"[object Array]"===Object.prototype.toString.apply(c)){for(s=c.length,n=0;s>n;n+=1)o[n]=str(n,c)||"null";return r=0===o.length?"[]":gap?"[\n"+gap+o.join(",\n"+gap)+"\n"+a+"]":"["+o.join(",")+"]",gap=a,r}if(rep&&"object"==typeof rep)for(s=rep.length,n=0;s>n;n+=1)"string"==typeof rep[n]&&(i=rep[n],r=str(i,c),r&&o.push(quote(i)+(gap?": ":":")+r));else for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(r=str(i,c),r&&o.push(quote(i)+(gap?": ":":")+r));return r=0===o.length?"{}":gap?"{\n"+gap+o.join(",\n"+gap)+"\n"+a+"}":"{"+o.join(",")+"}",gap=a,r}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;Faye.stringify=function(e,t,n){var i;if(gap="",indent="","number"==typeof n)for(i=0;n>i;i+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw new Error("JSON.stringify");return str("",{"":e})},"function"!=typeof JSON.stringify&&(JSON.stringify=Faye.stringify),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(e,t){var n,i,r=e[t];if(r&&"object"==typeof r)for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(i=walk(r,n),void 0!==i?r[n]=i:delete r[n]);return reviver.call(e,t,r)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),Faye.Transport.WebSocket=Faye.extend(Faye.Class(Faye.Transport,{UNCONNECTED:1,CONNECTING:2,CONNECTED:3,batching:!1,isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)}),this.connect()},request:function(e){this._pending=this._pending||new Faye.Set;for(var t=0,n=e.length;n>t;t++)this._pending.add(e[t]);var i=new Faye.Promise;return this.callback(function(t){t&&1===t.readyState&&(t.send(Faye.toJSON(e)),Faye.Promise.fulfill(i,t))},this),this.connect(),{abort:function(){i.then(function(e){e.close()})}}},connect:function(){if(!Faye.Transport.WebSocket._unloaded&&(this._state=this._state||this.UNCONNECTED,this._state===this.UNCONNECTED)){this._state=this.CONNECTING;var e=this._createSocket();if(!e)return this.setDeferredStatus("failed");var t=this;e.onopen=function(){e.headers&&t._storeCookies(e.headers["set-cookie"]),t._socket=e,t._state=t.CONNECTED,t._everConnected=!0,t._ping(),t.setDeferredStatus("succeeded",e)};var n=!1;e.onclose=e.onerror=function(){if(!n){n=!0;var i=t._state===t.CONNECTED;e.onopen=e.onclose=e.onerror=e.onmessage=null,delete t._socket,t._state=t.UNCONNECTED,t.removeTimeout("ping"),t.setDeferredStatus("unknown");var r=t._pending?t._pending.toArray():[];delete t._pending,i?t._handleError(r,!0):t._everConnected?t._handleError(r):t.setDeferredStatus("failed")}},e.onmessage=function(e){var n=JSON.parse(e.data);if(n){n=[].concat(n);for(var i=0,r=n.length;r>i;i++)void 0!==n[i].successful&&t._pending.remove(n[i]);t._receive(n)}}}},close:function(){this._socket&&this._socket.close()},_createSocket:function(){var e=Faye.Transport.WebSocket.getSocketUrl(this.endpoint),t=this._dispatcher.headers,n=this._dispatcher.wsExtensions,i=this._getCookies(),r=this._dispatcher.tls,s={extensions:n,headers:t,proxy:this._proxy,tls:r};return""!==i&&(s.headers.Cookie=i),Faye.WebSocket?new Faye.WebSocket.Client(e,[],s):Faye.ENV.MozWebSocket?new MozWebSocket(e):Faye.ENV.WebSocket?new WebSocket(e):void 0},_ping:function(){this._socket&&(this._socket.send("[]"),this.addTimeout("ping",this._dispatcher.timeout/2,this._ping,this))}}),{PROTOCOLS:{"http:":"ws:","https:":"wss:"},create:function(e,t){var n=e.transports.websocket=e.transports.websocket||{};return n[t.href]=n[t.href]||new this(e,t),n[t.href]},getSocketUrl:function(e){return e=Faye.copyObject(e),e.protocol=this.PROTOCOLS[e.protocol],Faye.URI.stringify(e)},isUsable:function(e,t,n,i){this.create(e,t).isUsable(n,i)}}),Faye.extend(Faye.Transport.WebSocket.prototype,Faye.Deferrable),Faye.Transport.register("websocket",Faye.Transport.WebSocket),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.Transport.WebSocket._unloaded=!0}),Faye.Transport.EventSource=Faye.extend(Faye.Class(Faye.Transport,{initialize:function(e,t){if(Faye.Transport.prototype.initialize.call(this,e,t),!Faye.ENV.EventSource)return this.setDeferredStatus("failed");this._xhr=new Faye.Transport.XHR(e,t),t=Faye.copyObject(t),t.pathname+="/"+e.clientId;var n=new EventSource(Faye.URI.stringify(t)),i=this;n.onopen=function(){i._everConnected=!0,i.setDeferredStatus("succeeded")},n.onerror=function(){i._everConnected?i._handleError([]):(i.setDeferredStatus("failed"),n.close())},n.onmessage=function(e){i._receive(JSON.parse(e.data))},this._socket=n},close:function(){this._socket&&(this._socket.onopen=this._socket.onerror=this._socket.onmessage=null,this._socket.close(),delete this._socket)},isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)})},encode:function(e){return this._xhr.encode(e)},request:function(e){return this._xhr.request(e)}}),{isUsable:function(e,t,n,i){var r=e.clientId;return r?(Faye.Transport.XHR.isUsable(e,t,function(r){return r?(this.create(e,t).isUsable(n,i),void 0):n.call(i,!1)},this),void 0):n.call(i,!1)},create:function(e,t){var n=e.transports.eventsource=e.transports.eventsource||{},i=e.clientId,r=Faye.copyObject(t);return r.pathname+="/"+(i||""),r=Faye.URI.stringify(r),n[r]=n[r]||new this(e,t),n[r]}}),Faye.extend(Faye.Transport.EventSource.prototype,Faye.Deferrable),Faye.Transport.register("eventsource",Faye.Transport.EventSource),Faye.Transport.XHR=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return Faye.toJSON(e)},request:function(e){var t=this.endpoint.href,n=Faye.ENV.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest,i=this;n.open("POST",t,!0),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Pragma","no-cache"),n.setRequestHeader("X-Requested-With","XMLHttpRequest");var r=this._dispatcher.headers;for(var s in r)r.hasOwnProperty(s)&&n.setRequestHeader(s,r[s]);var o=function(){n.abort()};return void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){if(n&&4===n.readyState){var t=null,r=n.status,s=n.responseText,a=r>=200&&300>r||304===r||1223===r;if(void 0!==Faye.ENV.onbeforeunload&&Faye.Event.detach(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){},n=null,!a)return i._handleError(e);try{t=JSON.parse(s)}catch(c){}t?i._receive(t):i._handleError(e)}},n.send(this.encode(e)),n}}),{isUsable:function(e,t,n,i){n.call(i,Faye.URI.isSameOrigin(t))}}),Faye.Transport.register("long-polling",Faye.Transport.XHR),Faye.Transport.CORS=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return"message="+encodeURIComponent(Faye.toJSON(e))},request:function(e){var t,n=Faye.ENV.XDomainRequest?XDomainRequest:XMLHttpRequest,i=new n,r=++Faye.Transport.CORS._id,s=this._dispatcher.headers,o=this;if(i.open("POST",Faye.URI.stringify(this.endpoint),!0),i.setRequestHeader){i.setRequestHeader("Pragma","no-cache");for(t in s)s.hasOwnProperty(t)&&i.setRequestHeader(t,s[t])}var a=function(){return i?(Faye.Transport.CORS._pending.remove(r),i.onload=i.onerror=i.ontimeout=i.onprogress=null,i=null,void 0):!1};return i.onload=function(){var t=null;try{t=JSON.parse(i.responseText)}catch(n){}a(),t?o._receive(t):o._handleError(e)},i.onerror=i.ontimeout=function(){a(),o._handleError(e)},i.onprogress=function(){},n===Faye.ENV.XDomainRequest&&Faye.Transport.CORS._pending.add({id:r,xhr:i}),i.send(this.encode(e)),i}}),{_id:0,_pending:new Faye.Set,isUsable:function(e,t,n,i){if(Faye.URI.isSameOrigin(t))return n.call(i,!1);if(Faye.ENV.XDomainRequest)return n.call(i,t.protocol===Faye.ENV.location.protocol);if(Faye.ENV.XMLHttpRequest){var r=new Faye.ENV.XMLHttpRequest;return n.call(i,void 0!==r.withCredentials)}return n.call(i,!1)}}),Faye.Transport.register("cross-origin-long-polling",Faye.Transport.CORS),Faye.Transport.JSONP=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){var t=Faye.copyObject(this.endpoint);return t.query.message=Faye.toJSON(e),t.query.jsonp="__jsonp"+Faye.Transport.JSONP._cbCount+"__",Faye.URI.stringify(t)},request:function(e){var t=document.getElementsByTagName("head")[0],n=document.createElement("script"),i=Faye.Transport.JSONP.getCallbackName(),r=Faye.copyObject(this.endpoint),s=this;r.query.message=Faye.toJSON(e),r.query.jsonp=i;var o=function(){if(!Faye.ENV[i])return!1;Faye.ENV[i]=void 0;try{delete Faye.ENV[i]}catch(e){}n.parentNode.removeChild(n)};return Faye.ENV[i]=function(e){o(),s._receive(e)},n.type="text/javascript",n.src=Faye.URI.stringify(r),t.appendChild(n),n.onerror=function(){o(),s._handleError(e)},{abort:o}}}),{_cbCount:0,getCallbackName:function(){return this._cbCount+=1,"__jsonp"+this._cbCount+"__"},isUsable:function(e,t,n,i){n.call(i,!0)}}),Faye.Transport.register("callback-polling",Faye.Transport.JSONP)}()}).call(exports,function(){return this}(),__webpack_require__(13).setImmediate,__webpack_require__(1))},function(e,t,n){(function(e,i){function r(e,t){this._id=e,this._clearFn=t}var s=n(1).nextTick,o=Function.prototype.apply,a=Array.prototype.slice,c={},u=0;t.setTimeout=function(){return new r(o.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new r(o.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},t.setImmediate="function"==typeof e?e:function(e){var n=u++,i=arguments.length<2?!1:a.call(arguments,1);return c[n]=!0,s(function(){c[n]&&(i?e.apply(null,i):e.call(null),t.clearImmediate(n))}),n},t.clearImmediate="function"==typeof i?i:function(e){delete c[e]}}).call(t,n(13).setImmediate,n(13).clearImmediate)},function(e){e.exports={author:{name:"Thierry Schellenbach",company:"Stream.io Inc"},name:"getstream",description:"The official low-level GetStream.io client for Node.js and the browser.",main:"./src/getstream.js",homepage:"https://getstream.io/",version:"3.0.0",browser:{request:"browser-request",crypto:!1,jsonwebtoken:!1,"./src/lib/batch_operations.js":!1,qs:!1,url:!1},config:{blanket:{pattern:"src","data-cover-never":["node_modules"]}},devDependencies:{async:"~0.9.0","babel-core":"^5.8.25","babel-loader":"^5.3.2",blanket:"~1.1.6",bluebird:"^2.1.3",connect:"^3.0.1",coveralls:"~2.10.1","expect.js":"~0.3.1",gulp:"^3.8.7","gulp-browserify":"^0.5.0","gulp-bump":"^0.1.8","gulp-git":"git://github.com/stevelacy/gulp-git.git","gulp-jscs":"^3.0.1","gulp-jscs-stylish":"^1.2.1","gulp-jshint":"^1.6.3","gulp-mocha":"^0.4.1","gulp-shell":"^0.2.7","gulp-uglify":"~0.3.1","gulp-util":"^2.2.17","jshint-stylish":"^2.0.1","json-loader":"^0.5.4",mocha:"^1.20.1","mocha-lcov-reporter":"0.0.1","mocha-sauce":"git://github.com/pbakaus/mocha-sauce.git",quickcheck:"0.0.4","serve-static":"^1.2.3","vinyl-source-stream":"^1.1.0",webpack:"^1.12.2"},license:"BSD",dependencies:{Base64:"^0.3.0","browser-request":"matthisk/browser-request",faye:"^1.0.1","http-signature":"^1.0.2",jsonwebtoken:"^5.0.1",qs:"^5.2.0",request:"2.63.0"},repository:{type:"git",url:"git://github.com/GetStream/stream-js.git"},scripts:{test:"gulp test"},engines:{node:">=0.8 <0.11"}}},function(){}])}); \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 8e36722a..30e4ce88 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -82,10 +82,10 @@ gulp.task("build", function() { runSynchronized(['build:webpack', 'build:test', 'build:optimize']); }); +var prodWebpackConfig = Object.create(webpackConfig); gulp.task("build:webpack", function(callback) { - var myConfig = Object.create(webpackConfig); - webpack(myConfig, function(err, stats) { + webpack(prodWebpackConfig, function(err, stats) { if(err) throw new gutil.PluginError("webpack:build", err); gutil.log("[webpack:build]", stats.toString({ colors: true @@ -94,19 +94,17 @@ gulp.task("build:webpack", function(callback) { }); }); +var testWebpackConfig = Object.create(webpackConfig); + +testWebpackConfig.context = process.cwd(); +testWebpackConfig.entry = './test/browser/index.js'; +testWebpackConfig.output = { + path: __dirname + '/test/browser', + filename: 'browser.js' +}; + gulp.task('build:test', function(callback) { - webpack({ - entry: './test/browser/index.js', - output : { - path: __dirname + '/test/browser', - filename: 'browser.js' - }, - resolve: { - alias: { - 'request': 'browser-request', - } - } - }, function(err, stats) { + webpack(testWebpackConfig, function(err, stats) { if(err) throw new gutil.PluginError("webpack:build:test", err); gutil.log("[webpack:build:test]", stats.toString({ colors: true diff --git a/package.json b/package.json index 2c37ab2d..5a9c5ba4 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "gulp-uglify": "~0.3.1", "gulp-util": "^2.2.17", "jshint-stylish": "^2.0.1", + "json-loader": "^0.5.4", "mocha": "^1.20.1", "mocha-lcov-reporter": "0.0.1", "mocha-sauce": "git://github.com/pbakaus/mocha-sauce.git", @@ -68,7 +69,8 @@ "url": "git://github.com/GetStream/stream-js.git" }, "scripts": { - "test": "gulp test" + "test": "gulp test", + "sauce": "node test/saucelabs.js" }, "engines": { "node": ">=0.8 <0.11" diff --git a/src/lib/client.js b/src/lib/client.js index 99a777d1..1439cb4b 100644 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -187,8 +187,9 @@ StreamClient.prototype = { * @return {string} current user agent */ var description = (this.node) ? 'node' : 'browser'; - // TODO: get the version here in a way which works in both and browserify - var version = 'unknown'; + + var version = require('../../package.json').version; + return 'stream-javascript-client-' + description + '-' + version; }, @@ -301,7 +302,7 @@ StreamClient.prototype = { kwargs.headers = {}; // auto-detect authentication type and set HTTP headers accordingly - if (signing.isJWTSignature(signature)) { + if (signature && signing.isJWTSignature(signature)) { kwargs.headers['stream-auth-type'] = 'jwt'; signature = signature.split(' ').reverse()[0]; } else { diff --git a/test/browser/browser.js b/test/browser/browser.js index 1abe8abf..93f63119 100644 --- a/test/browser/browser.js +++ b/test/browser/browser.js @@ -44,18 +44,22 @@ /* 0 */ /***/ function(module, exports, __webpack_require__) { - var integrationTests = __webpack_require__(1); - var unitTests = __webpack_require__(25); + 'use strict'; + var integrationTests = __webpack_require__(1); + var unitTests = __webpack_require__(20); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(process) {var expect = __webpack_require__(3); - var Faye = __webpack_require__(9); - var stream = __webpack_require__(11); + /* WEBPACK VAR INJECTION */(function(process) {'use strict'; + + var expect = __webpack_require__(3); + var Faye = __webpack_require__(5); + var stream = __webpack_require__(7); var isNodeEnv = typeof window === 'undefined'; + var errors; var READ_TIMEOUT = 2000; @@ -74,12 +78,12 @@ var self = this; this.timeout(4000); this.localRun = false; - if (typeof (process) != "undefined" && process.env.LOCAL) { + if (typeof process != "undefined" && process.env.LOCAL) { // local testing is slow as we run celery tasks in sync this.timeout(25000); this.localRun = true; } - if (typeof (document) != "undefined" && document.location.href.indexOf('local=1') != -1) { + if (typeof document != "undefined" && document.location.href.indexOf('local=1') != -1) { // local testing via the browser this.timeout(25000); this.localRun = true; @@ -91,9 +95,9 @@ function beforeEachBrowser() { client = stream.connect('ahj2ndz7gsan'); - client = stream.connect('ahj2ndz7gsan', null, 519, {'group': 'browserTestCycle', 'location': 'eu-west'}); + client = stream.connect('ahj2ndz7gsan', null, 519, { 'group': 'browserTestCycle', 'location': 'eu-west' }); - if (self.localRun){ + if (self.localRun) { client.baseUrl = 'http://localhost:8000/api/'; client.fayeUrl = 'http://localhost:9999/faye/'; } @@ -109,18 +113,18 @@ function beforeEachNode() { client = stream.connect('ahj2ndz7gsan', 'gthc2t9gh7pzq52f6cky8w4r4up9dr6rju9w3fjgmkv6cdvvav2ufe5fv7e2r9qy'); - client = stream.connect('ahj2ndz7gsan', 'gthc2t9gh7pzq52f6cky8w4r4up9dr6rju9w3fjgmkv6cdvvav2ufe5fv7e2r9qy', 519, {'group': 'testCycle', 'location': 'us-east'}); + client = stream.connect('ahj2ndz7gsan', 'gthc2t9gh7pzq52f6cky8w4r4up9dr6rju9w3fjgmkv6cdvvav2ufe5fv7e2r9qy', 519, { 'group': 'testCycle', 'location': 'us-east' }); user1 = client.feed('user', '11'); aggregated2 = client.feed('aggregated', '22'); aggregated3 = client.feed('aggregated', '33'); flat3 = client.feed('flat', '33'); secret3 = client.feed('secret', '33'); notification3 = client.feed('notification', '33'); - user1ReadOnly = client.feed('user', '11', null, null, {readOnly: true}); - user2ReadOnly = client.feed('user', '22', null, null, {readOnly: true}); + user1ReadOnly = client.feed('user', '11', null, null, { readOnly: true }); + user2ReadOnly = client.feed('user', '22', null, null, { readOnly: true }); } - var before = (isNodeEnv) ? beforeEachNode : beforeEachBrowser; + var before = isNodeEnv ? beforeEachNode : beforeEachBrowser; beforeEach(before); @@ -160,7 +164,7 @@ it('heroku_overwrite', function (done) { var url = 'https://thierry:pass@getstream.io/?app_id=1'; process.env.STREAM_URL = url; - client = stream.connect('a','b','c'); + client = stream.connect('a', 'b', 'c'); expect(client.apiKey).to.eql('a'); expect(client.apiSecret).to.eql('b'); expect(client.appId).to.eql('c'); @@ -172,7 +176,7 @@ var location = 'us-east'; var fullLocation = 'https://us-east-api.getstream.io/api/'; options.location = location; - client = stream.connect('a','b','c', options); + client = stream.connect('a', 'b', 'c', options); expect(client.baseUrl).to.eql(fullLocation); expect(client.location).to.eql(location); done(); @@ -183,10 +187,10 @@ var called = {}; called.request = 0; called.response = 0; - function callback () { + function callback() { called.request += 1; }; - function responseCallback () { + function responseCallback() { called.response += 1; }; client.on('request', callback); @@ -199,68 +203,79 @@ } function second() { client.off(); - user1.get({'limit': 1}, third); + user1.get({ 'limit': 1 }, third); } - user1.get({'limit': 1}, second); + user1.get({ 'limit': 1 }, second); }); - it('signing', function (done) { expect(user1.token).to.be.an('string'); done(); }); it('get feed', function (done) { - user1.get({'limit': 1}, function(error, response, body) { + user1.get({ 'limit': 1 }, function (error, response, body) { expect(response.statusCode).to.eql(200); - expect(body['results'][0]['id']).to.be.a('string'); - if (isNodeEnv) { - var userAgent = response.req._headers['x-stream-client']; - expect(userAgent.indexOf('stream-javascript-client')).to.eql(0); - } - done(); - }); + expect(body['results'][0]['id']).to.be.a('string'); + if (isNodeEnv) { + var userAgent = response.req._headers['x-stream-client']; + expect(userAgent.indexOf('stream-javascript-client')).to.eql(0); + } + done(); + }); }); it('get wrong feed', function (done) { - var getFeed = function() { client.feed('flat1');}; + var getFeed = function getFeed() { + client.feed('flat1'); + }; expect(getFeed).to.throwException(function (e) { expect(e).to.be.a(errors.FeedError); - }); + }); done(); }); it('get wrong format', function (done) { - var getFeed = function() { client.feed('flat:1', '2');}; + var getFeed = function getFeed() { + client.feed('flat:1', '2'); + }; expect(getFeed).to.throwException(function (e) { expect(e).to.be.a(errors.FeedError); - }); + }); done(); }); it('get invalid format', function (done) { var invalidFormats = []; - invalidFormats.push(function() { client.feed('flat 1', '2');}); - invalidFormats.push(function() { client.feed('flat1', '2:3');}); - invalidFormats.push(function() { user1.follow('flat 1', '3');}); - invalidFormats.push(function() { user1.follow('flat', '3 3');}); + invalidFormats.push(function () { + client.feed('flat 1', '2'); + }); + invalidFormats.push(function () { + client.feed('flat1', '2:3'); + }); + invalidFormats.push(function () { + user1.follow('flat 1', '3'); + }); + invalidFormats.push(function () { + user1.follow('flat', '3 3'); + }); // verify all of the above throw an error for (var i = 0; i < invalidFormats.length; i++) { var callable = invalidFormats[i]; - expect(callable).to.throwException(function (e) { + expect(callable).to.throwException(function (e) { expect(e).to.be.a(errors.FeedError); - }); - } - // a dash should be allowed - client.feed('flat1', '2-3', 'token'); + }); + } + // a dash should be allowed + client.feed('flat1', '2-3', 'token'); done(); }); it('add activity', function (done) { - var activity = {'actor': 'test-various:characters', 'verb': 'add', 'object': 1, 'tweet': 'hello world'}; + var activity = { 'actor': 'test-various:characters', 'verb': 'add', 'object': 1, 'tweet': 'hello world' }; function get(error, response, body) { var activityId = body['id']; - user1.get({'limit': 1}, function(error, response, body) { + user1.get({ 'limit': 1 }, function (error, response, body) { expect(response.statusCode).to.eql(200); expect(body['results'][0]['id']).to.eql(activityId); done(); @@ -270,19 +285,19 @@ }); it('add complex activity', function (done) { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; activity['participants'] = ['Thierry', 'Tommaso']; - activity['route'] = {'name': 'Vondelpark', 'distance': '20'}; + activity['route'] = { 'name': 'Vondelpark', 'distance': '20' }; var currentDate = new Date(); activity['date'] = currentDate; var isoDate = currentDate.toISOString(); function get(error, response, body) { var activityId = body['id']; - user1.get({'limit': 1}, function(error, response, body) { + user1.get({ 'limit': 1 }, function (error, response, body) { expect(response.statusCode).to.eql(200); expect(body['results'][0]['id']).to.eql(activityId); expect(body['results'][0]['participants']).to.eql(['Thierry', 'Tommaso']); - expect(body['results'][0]['route']).to.eql({'name': 'Vondelpark', 'distance': '20'}); + expect(body['results'][0]['route']).to.eql({ 'name': 'Vondelpark', 'distance': '20' }); expect(body['results'][0]['date']).to.eql(isoDate); done(); }); @@ -291,9 +306,9 @@ }); it('add activity using to', function (done) { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; activity['participants'] = ['Thierry', 'Tommaso']; - activity['route'] = {'name': 'Vondelpark', 'distance': '20'}; + activity['route'] = { 'name': 'Vondelpark', 'distance': '20' }; activity['to'] = ['flat:33', 'user:everyone']; //flat3 if (!isNodeEnv) activity['to'] = ['flat:33' + ' ' + flat3.token]; @@ -302,7 +317,7 @@ var activityId = body['id']; expect(error).to.eql(null); expect(body.exception).to.eql(undefined); - flat3.get({'limit': 1}, function(error, response, body) { + flat3.get({ 'limit': 1 }, function (error, response, body) { expect(response.statusCode).to.eql(200); expect(body['results'][0]['id']).to.eql(activityId); done(); @@ -312,17 +327,17 @@ }); it('add activity no callback', function (done) { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; user1.addActivity(activity); done(); }); it('remove activity', function (done) { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; function remove(error, response, body) { var activityId = body['id']; expect(response.statusCode).to.eql(201); - user1.removeActivity(activityId, function(error, response, body) { + user1.removeActivity(activityId, function (error, response, body) { expect(response.statusCode).to.eql(200); done(); }); @@ -331,15 +346,15 @@ }); it('remove activity foreign id', function (done) { - var activity = {'actor': 1, 'verb': 'add', 'object': 1, 'foreign_id': 'add:1'}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1, 'foreign_id': 'add:1' }; var now = new Date(); - activity.time = now.toISOString(); + activity.time = now.toISOString(); function remove(error, response, body) { var activityId = body['id']; expect(response.statusCode).to.eql(201); - user1.removeActivity({foreignId: 'add:1'}, function(error, response, body) { + user1.removeActivity({ foreignId: 'add:1' }, function (error, response, body) { expect(response.statusCode).to.eql(200); - user1.get({limit:10}, function(error, response, body) { + user1.get({ limit: 10 }, function (error, response, body) { expect(response.statusCode).to.eql(200); expect(body['results'][0]['id']).not.to.eql(activityId); expect(body['results'][0]['foreign_id']).not.to.eql('add:1'); @@ -351,14 +366,11 @@ }); it('add activities', function (done) { - var activities = [ - {'actor': 1, 'verb': 'tweet', 'object': 1}, - {'actor': 2, 'verb': 'tweet', 'object': 3}, - ]; + var activities = [{ 'actor': 1, 'verb': 'tweet', 'object': 1 }, { 'actor': 2, 'verb': 'tweet', 'object': 3 }]; function get(error, response, body) { var activityIdFirst = body['activities'][0]['id']; var activityIdLast = body['activities'][1]['id']; - user1.get({'limit': 2}, function(error, response, body) { + user1.get({ 'limit': 2 }, function (error, response, body) { expect(response.statusCode).to.eql(200); expect(body['results'][0]['id']).to.eql(activityIdLast); expect(body['results'][1]['id']).to.eql(activityIdFirst); @@ -372,7 +384,7 @@ var activityId = null; this.timeout(9000); function add() { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; user1.addActivity(activity, follow); } function follow(error, response, body) { @@ -381,14 +393,14 @@ } function runCheck(error, response, body) { function check() { - aggregated2.get({'limit': 1}, function(error, response, body) { - expect(response.statusCode).to.eql(200); - expect(body['results'][0]['activities'][0]['id']).to.eql(activityId); - done(); - }); - } + aggregated2.get({ 'limit': 1 }, function (error, response, body) { + expect(response.statusCode).to.eql(200); + expect(body['results'][0]['activities'][0]['id']).to.eql(activityId); + done(); + }); + } setTimeout(check, READ_TIMEOUT); - } + } add(); }); @@ -398,8 +410,8 @@ }); it('follow with copy limit', function (done) { - aggregated2.follow('user', '999', { limit: 500 }, function(error, response, body) { - if(error) done(error); + aggregated2.follow('user', '999', { limit: 500 }, function (error, response, body) { + if (error) done(error); expect(response.statusCode).to.be(201); done(); }); @@ -409,22 +421,22 @@ this.timeout(6000); var activityId = null; function add() { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; - user1.addActivity(activity, follow); - } - function follow(error, response, body) { - activityId = body['id']; - aggregated2.follow('user', '11', unfollow); - } - function unfollow(error, response, body) { - aggregated2.unfollow('user', '11', check); - } + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; + user1.addActivity(activity, follow); + } + function follow(error, response, body) { + activityId = body['id']; + aggregated2.follow('user', '11', unfollow); + } + function unfollow(error, response, body) { + aggregated2.unfollow('user', '11', check); + } function check(error, response, body) { - setTimeout(function() { - aggregated2.get({'limit': 1}, function(error, response, body) { + setTimeout(function () { + aggregated2.get({ 'limit': 1 }, function (error, response, body) { expect(response.statusCode).to.eql(200); var firstResult = body['results'][0]; - var activityFound = (firstResult) ? firstResult['activities'][0]['id'] : null; + var activityFound = firstResult ? firstResult['activities'][0]['id'] : null; expect(activityFound).to.not.eql(activityId); done(); }); @@ -434,28 +446,28 @@ }); it('list followers', function (done) { - function callback(error, response, body){ + function callback(error, response, body) { expect(error).to.eql(null); expect(body.exception).to.eql(undefined); done(); }; - user1.followers({limit: '10', offset: '10'}, callback); + user1.followers({ limit: '10', offset: '10' }, callback); }); it('list following', function (done) { - function callback(error, response, body){ + function callback(error, response, body) { expect(error).to.eql(null); expect(body.exception).to.eql(undefined); done(); }; - user1.following({limit: '10', offset: '10'}, callback); + user1.following({ limit: '10', offset: '10' }, callback); }); it('do i follow', function (done) { function doifollow() { - user1.following({'filter': ['flat:33', 'flat:44']}, callback); + user1.following({ 'filter': ['flat:33', 'flat:44'] }, callback); } - function callback(error, response, body){ + function callback(error, response, body) { expect(error).to.eql(null); expect(body.exception).to.eql(undefined); var results = body.results; @@ -471,7 +483,7 @@ expect(response.statusCode).to.eql(200); done(); } - user1ReadOnly.get({'limit': 2}, check); + user1ReadOnly.get({ 'limit': 2 }, check); }); it('get filtering', function (done) { @@ -483,20 +495,20 @@ var activityIdThree = null; function add() { - var activity = {'actor': 1, 'verb': 'add', 'object': 1}; + var activity = { 'actor': 1, 'verb': 'add', 'object': 1 }; user1.addActivity(activity, add2); } function add2(error, response, body) { activityIdOne = body['id']; - var activity = {'actor': 2, 'verb': 'watch', 'object': 2}; + var activity = { 'actor': 2, 'verb': 'watch', 'object': 2 }; user1.addActivity(activity, add3); } function add3(error, response, body) { activityIdTwo = body['id']; - var activity = {'actor': 3, 'verb': 'run', 'object': 2}; - user1.addActivity(activity, function(error, response, body) { + var activity = { 'actor': 3, 'verb': 'run', 'object': 2 }; + user1.addActivity(activity, function (error, response, body) { // testing eventual consistency is not easy :) function getBound() { get(error, response, body); @@ -507,7 +519,7 @@ function get(error, response, body) { activityIdThree = body['id']; - user1.get({'limit': 2}, check); + user1.get({ 'limit': 2 }, check); } // no filtering @@ -515,7 +527,7 @@ expect(body['results'].length).to.eql(2); expect(body['results'][0]['id']).to.eql(activityIdThree); expect(body['results'][1]['id']).to.eql(activityIdTwo); - user1.get({limit:2, offset:1}, check2); + user1.get({ limit: 2, offset: 1 }, check2); } // offset based @@ -523,7 +535,7 @@ expect(body['results'].length).to.eql(2); expect(body['results'][0]['id']).to.eql(activityIdTwo); expect(body['results'][1]['id']).to.eql(activityIdOne); - user1.get({limit:2, id_lt:activityIdTwo}, check3); + user1.get({ limit: 2, id_lt: activityIdTwo }, check3); } // try id_lt based @@ -534,16 +546,12 @@ } add(); - }); it('mark read and seen', function (done) { // add 2 activities to ensure we have new data - var params = {limit: 2}; - var activities = [ - {'actor': 1, 'verb': 'add', 'object': 1}, - {'actor': 2, 'verb': 'test', 'object': 2} - ] + var params = { limit: 2 }; + var activities = [{ 'actor': 1, 'verb': 'add', 'object': 1 }, { 'actor': 2, 'verb': 'test', 'object': 2 }]; notification3.addActivities(activities, getNotifications); // lookup the notification ids function getNotifications(error, response, body) { @@ -551,9 +559,9 @@ }; // mark all seen and the first read function markRead(error, response, body) { - var notificationId = body['results'][0]['id']; - var params = {limit:2, mark_seen:true, mark_read: notificationId}; - notification3.get(params, readFeed); + var notificationId = body['results'][0]['id']; + var params = { limit: 2, mark_seen: true, mark_read: notificationId }; + notification3.get(params, readFeed); } // read the feed (should be seen and 1 unread) function readFeed(error, response, body) { @@ -569,7 +577,6 @@ expect(body['unseen']).to.eql(0); done(); }; - }); it('fayeGetClient', function (done) { @@ -579,15 +586,14 @@ it('fayeSubscribe', function (done) { this.timeout(6000); - var client = user1.getFayeClient() - var subscription = user1.subscribe(function callback() { - }); - subscription.then(function() { + var client = user1.getFayeClient(); + var subscription = user1.subscribe(function callback() {}); + subscription.then(function () { done(); - }); + }); }); - it('fayeSubscribeListening', function(done) { + it('fayeSubscribeListening', function (done) { this.timeout(6000); var testUser1 = client.feed('user', '111', 'ksBmfluIarcgjR9e6ptwqkWZWJo'), @@ -603,33 +609,29 @@ 'object': 1 }; - var msgCallback = function(message) { - if( message && message.new && message.new.length > 0) { + var msgCallback = function msgCallback(message) { + if (message && message['new'] && message['new'].length > 0) { messages += 1; } - if( messages == N_MESSAGES ) { + if (messages == N_MESSAGES) { done(); } }; - var httpCallback = function(error, response, body) { - if(error) done(error); - if(response.statusCode !== 201) done(body); + var httpCallback = function httpCallback(error, response, body) { + if (error) done(error); + if (response.statusCode !== 201) done(body); }; - Faye.Promise.all([ - testUser1.subscribe(msgCallback), - testUser2.subscribe(msgCallback), - testUser3.subscribe(msgCallback) - ]).then(function() { + Faye.Promise.all([testUser1.subscribe(msgCallback), testUser2.subscribe(msgCallback), testUser3.subscribe(msgCallback)]).then(function () { testUser1.addActivity(activity, httpCallback); testUser2.addActivity(activity, httpCallback); testUser3.addActivity(activity, httpCallback); }, done); }); - it('fayeSubscribeListeningWrongToken', function(done) { + it('fayeSubscribeListeningWrongToken', function (done) { this.timeout(6000); var testUser1 = client.feed('user', '111', 'psuPHwgwoX-PGsg780jcXdO93VM'), @@ -642,27 +644,26 @@ 'object': 1 }; - var httpCallback = function(error, response, body) { - if(error) done(error); - if(response.statusCode !== 201) done(body); + var httpCallback = function httpCallback(error, response, body) { + if (error) done(error); + if (response.statusCode !== 201) done(body); }; - var doneYet = function(obj) { + var doneYet = function doneYet(obj) { messages++; - if(messages === 2) done(); - } + if (messages === 2) done(); + }; - testUser1.subscribe(function(message) { + testUser1.subscribe(function (message) { done('testUser1 should not receive any messages'); - }).then(function() { + }).then(function () { done('testUser1 should not authenticate succefully'); }, doneYet); - testUser2.subscribe(doneYet).then(function() { + testUser2.subscribe(doneYet).then(function () { testUser2.addActivity(activity, httpCallback); }, done); - }); it('fayeSubscribeScope', function (done) { @@ -670,12 +671,12 @@ var client = user1ReadOnly.getFayeClient(); var isDone = false; - var doneYet = function() { - if(!isDone) { + var doneYet = function doneYet() { + if (!isDone) { done(); isDone = true; } - } + }; var subscription = user1ReadOnly.subscribe(doneYet); subscription.then(doneYet); @@ -686,12 +687,12 @@ var client = user1ReadOnly.getFayeClient(); var isDone = false; - var doneYet = function() { - if(!isDone) { + var doneYet = function doneYet() { + if (!isDone) { done(); isDone = true; } - } + }; var subscription = user1ReadOnly.subscribe(doneYet); subscription.then(doneYet); }); @@ -706,44 +707,44 @@ } expect(sub).to.throwException(function (e) { expect(e).to.be.a(errors.SiteError); - }); - done(); + }); + done(); }); - var wrapCB = function(expectedStatusCode, done, cb) { - return function(error, response, body) { - if(error) return done(error); + var wrapCB = function wrapCB(expectedStatusCode, done, cb) { + return function (error, response, body) { + if (error) return done(error); expect(response.statusCode).to.be(expectedStatusCode); - if( typeof cb === 'function') { + if (typeof cb === 'function') { cb.apply(cb, arguments); } else { done(); } - } + }; }; - if(isNodeEnv) { + if (isNodeEnv) { // Server side specific tests - it('supports application level authentication', function(done) { + it('supports application level authentication', function (done) { client.makeSignedRequest({ url: 'test/auth/digest/' }, wrapCB(200, done)); }); - it('fails application level authentication with wrong keys', function(done) { - var client = stream.connect('aap','noot'); + it('fails application level authentication with wrong keys', function (done) { + var client = stream.connect('aap', 'noot'); client.makeSignedRequest({ url: 'test/auth/digest/' - }, function(error, response, body) { - if(error) done(error); - if(body.exception === 'ApiKeyException') done(); + }, function (error, response, body) { + if (error) done(error); + if (body.exception === 'ApiKeyException') done(); }); }); - it('supports adding activity to multiple feeds', function(done) { + it('supports adding activity to multiple feeds', function (done) { var activity = { 'actor': 'user:11', 'verb': 'like', @@ -754,24 +755,20 @@ client.addToMany(activity, feeds, wrapCB(201, done)); }); - it('supports batch following', function(done) { + it('supports batch following', function (done) { this.timeout(6000); - var follows = [ - {'source': 'flat:1', 'target': 'user:1'}, - {'source': 'flat:1', 'target': 'user:2'}, - {'source': 'flat:1', 'target': 'user:3'} - ]; + var follows = [{ 'source': 'flat:1', 'target': 'user:1' }, { 'source': 'flat:1', 'target': 'user:2' }, { 'source': 'flat:1', 'target': 'user:3' }]; client.followMany(follows, wrapCB(201, done)); }); - it('no secret application auth', function() { + it('no secret application auth', function () { var client = stream.connect('ahj2ndz7gsan'); - expect(function() { - client.addToMany({},[]) - }).to.throwError(function(e) { + expect(function () { + client.addToMany({}, []); + }).to.throwError(function (e) { expect(e).to.be.a(errors.SiteError); }); }); @@ -784,43 +781,41 @@ }; var feeds = ['flat:33', 'user:11']; - client.addToMany(activity, feeds).then(function(body) { + client.addToMany(activity, feeds).then(function (body) { done(); }, done); }); } else { // Client side specific tests - it('shouldn\'t support signed requests on the client', function() { + it('shouldn\'t support signed requests on the client', function () { expect(client.makeSignedRequest).to.be(undefined); }); } it('get promises', function (done) { - user1.get({'limit': 1}).then(function(body) { + user1.get({ 'limit': 1 }).then(function (body) { done(); }, done); }); it('post promises', function (done) { - var activity = {'actor': 'test-various:characters', 'verb': 'add', 'object': 1, 'tweet': 'hello world'}; - user1.addActivity(activity).then(function(body) { - done(); + var activity = { 'actor': 'test-various:characters', 'verb': 'add', 'object': 1, 'tweet': 'hello world' }; + user1.addActivity(activity).then(function (body) { + done(); }, done); }); it('post promises fail', function (done) { - var activity = {'actor': 'test-various:characters', 'verb': 'add', 'object': '', 'tweet': 'hello world'}; - var p = user1.addActivity(activity) - .then(function(body) { - done('expected failure'); - }) - p.catch(function(errorObj) { - done(); - }); + var activity = { 'actor': 'test-various:characters', 'verb': 'add', 'object': '', 'tweet': 'hello world' }; + var p = user1.addActivity(activity).then(function (body) { + done('expected failure'); + }); + p['catch'](function (errorObj) { + done(); + }); }); }); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }, @@ -924,7 +919,7 @@ /* 3 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(module, Buffer) {(function (global, module) { + /* WEBPACK VAR INJECTION */(function(module) {(function (global, module) { var exports = module.exports; @@ -2081,1964 +2076,154 @@ // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can - // produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - - // If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. - - return str('', {'': value}); - }; - - // If the JSON object does not yet have a parse method, give it one. - - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - - return JSON; - })(); - - if ('undefined' != typeof window) { - window.expect = module.exports; - } - - })( - this - , true ? module : {exports: {}} - ); - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)(module), __webpack_require__(5).Buffer)) - -/***/ }, -/* 4 */ -/***/ function(module, exports) { - - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - module.webpackPolyfill = 1; - } - return module; - } - - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - var base64 = __webpack_require__(6) - var ieee754 = __webpack_require__(7) - var isArray = __webpack_require__(8) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - Buffer.poolSize = 8192 // not used by this implementation - - var rootParent = {} - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property - * on objects. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - function typedArraySupport () { - function Bar () {} - try { - var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - arr.constructor = Bar - return arr.foo() === 42 && // typed array instances can be augmented - arr.constructor === Bar && // constructor can be set - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - /** - * Class: Buffer - * ============= - * - * The Buffer constructor returns instances of `Uint8Array` that are augmented - * with function properties for all the node `Buffer` API functions. We use - * `Uint8Array` so that square bracket notation works as expected -- it returns - * a single octet. - * - * By augmenting the instances, we can avoid modifying the `Uint8Array` - * prototype. - */ - function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) - } - - this.length = 0 - this.parent = undefined - - // Common case. - if (typeof arg === 'number') { - return fromNumber(this, arg) - } - - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') - } - - // Unusual. - return fromObject(this, arg) - } - - function fromNumber (that, length) { - that = allocate(that, length < 0 ? 0 : checked(length) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < length; i++) { - that[i] = 0 - } - } - return that - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) - - that.write(string, encoding) - return that - } - - function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) - - if (isArray(object)) return fromArray(that, object) - - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') - } - - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } - } - - if (object.length) return fromArrayLike(that, object) - - return fromJsonObject(that, object) - } - - function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that - } - - function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - // Duplicate of fromArray() to keep fromArray() monomorphic. - function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - array.byteLength - that = Buffer._augment(new Uint8Array(array)) - } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) - } - return that - } - - function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. - // Returns a zero-length buffer for inputs that don't conform to the spec. - function fromJsonObject (that, object) { - var array - var length = 0 - - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 - } - that = allocate(that, length) - - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - } - - function allocate (that, length) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = Buffer._augment(new Uint8Array(length)) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that.length = length - that._isBuffer = true - } - - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent - - return that - } - - function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break - - ++i - } - - if (i !== len) { - x = a[i] - y = b[i] - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (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.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') - - if (list.length === 0) { - return new Buffer(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length - } - } - - var buf = new Buffer(length) - var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length - } - return buf - } - - function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'binary': - // Deprecated - case 'raw': - case 'raws': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined - - function slowToString (encoding, start, end) { - var loweredCase = false - - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 - - if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return 0 - return Buffer.compare(this, b) - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) - } - if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) - } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) - } - return arrayIndexOf(this, [ val ], byteOffset) - } - - function arrayIndexOf (arr, val, byteOffset) { - var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex - } else { - foundIndex = -1 - } - } - return -1 - } - - throw new TypeError('val must be string, number or Buffer') - } - - // `get` is deprecated - Buffer.prototype.get = function get (offset) { - console.log('.get() is deprecated. Access using array indexes instead.') - return this.readUInt8(offset) - } - - // `set` is deprecated - Buffer.prototype.set = function set (v, offset) { - console.log('.set() is deprecated. Access using array indexes instead.') - return this.writeUInt8(v, offset) - } - - 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 - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) throw new Error('Invalid hex string') - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'binary': - return binaryWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - 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) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - 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] & 0x7F) - } - return ret - } - - function binarySlice (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 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 slice (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 - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = Buffer._augment(this.subarray(start, end)) - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - if (newBuf.length) newBuf.parent = this.parent || this - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = value < 0 ? 1 : 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = value < 0 ? 1 : 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') - if (offset < 0) throw new RangeError('index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start] - } - } else { - target._set(this.subarray(start, start + len), targetStart) - } - - return len - } - - // fill(value, start=0, end=buffer.length) - Buffer.prototype.fill = function fill (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length - - if (end < start) throw new RangeError('end < start') - - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return - - if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') - if (end < 0 || end > this.length) throw new RangeError('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 - } - - /** - * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. - * Added in Node 0.12. Only available in browsers that support ArrayBuffer. - */ - Buffer.prototype.toArrayBuffer = function toArrayBuffer () { - if (typeof Uint8Array !== 'undefined') { - if (Buffer.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 TypeError('Buffer.toArrayBuffer not supported in this browser') - } - } - - // HELPER FUNCTIONS - // ================ - - var BP = Buffer.prototype - - /** - * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods - */ - Buffer._augment = function _augment (arr) { - arr.constructor = Buffer - arr._isBuffer = true - - // save reference to original Uint8Array set method before overwriting - arr._set = arr.set - - // deprecated - 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.indexOf = BP.indexOf - arr.copy = BP.copy - arr.slice = BP.slice - arr.readUIntLE = BP.readUIntLE - arr.readUIntBE = BP.readUIntBE - arr.readUInt8 = BP.readUInt8 - arr.readUInt16LE = BP.readUInt16LE - arr.readUInt16BE = BP.readUInt16BE - arr.readUInt32LE = BP.readUInt32LE - arr.readUInt32BE = BP.readUInt32BE - arr.readIntLE = BP.readIntLE - arr.readIntBE = BP.readIntBE - 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.writeUIntLE = BP.writeUIntLE - arr.writeUIntBE = BP.writeUIntBE - arr.writeUInt16LE = BP.writeUInt16LE - arr.writeUInt16BE = BP.writeUInt16BE - arr.writeUInt32LE = BP.writeUInt32LE - arr.writeUInt32BE = BP.writeUInt32BE - arr.writeIntLE = BP.writeIntLE - arr.writeIntBE = BP.writeIntBE - 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-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - 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 toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; i++) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } + // produce text that is more easily readable. - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } + var i; + gap = ''; + indent = ''; - 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 - } + // If the space parameter is a number, make an indent string containing that + // many spaces. - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer, (function() { return this; }()))) + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { + // If the space parameter is a string, it will be used as the indent string. - 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) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || - code === PLUS_URL_SAFE) - return 62 // '+' - if (code === SLASH || - code === SLASH_URL_SAFE) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } + } else if (typeof space === 'string') { + indent = space; + } - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr + // If there is a replacer, it must be a function or an array. + // Otherwise, throw an error. - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + // Make a fake root object containing our value under the key of ''. + // Return the result of stringifying the value. - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) + return str('', {'': value}); + }; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length + // If the JSON object does not yet have a parse method, give it one. - var L = 0 + JSON.parse = function (text, reviver) { + // The parse method takes a text and an optional reviver function, and returns + // a JavaScript value if the text is a valid JSON text. - function push (v) { - arr[L++] = v - } + var j; - 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 & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } + function walk(holder, key) { - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } 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) & 0xFF) - push(tmp & 0xFF) - } + // The walk method is used to recursively walk the resulting structure so + // that modifications can be made. - return arr - } + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length - function encode (num) { - return lookup.charAt(num) - } + // Parsing happens in four stages. In the first stage, we replace certain + // Unicode characters with escape sequences. JavaScript handles many characters + // incorrectly, either silently deleting them, or treating them as line endings. - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } - // go through the array every three bytes, we'll deal with trailing stuff later - 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) - } + // In the second stage, we run the text against regular expressions that look + // for non-JSON patterns. We are especially concerned with '()' and 'new' + // because they can cause invocation, and '=' because it can cause mutation. + // But just to be safe, we want to reject all unexpected forms. - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } + // We split the second stage into 4 regexp operations in order to work around + // crippling inefficiencies in IE's and Safari's regexp engines. First we + // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we + // replace all simple value tokens with ']' characters. Third, we delete all + // open brackets that follow a colon or comma or that begin the text. Finally, + // we look to see that the remaining characters are only whitespace or ']' or + // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - return output - } + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 - }( false ? (this.base64js = {}) : exports)) + // In the third stage we use the eval function to compile the text into a + // JavaScript structure. The '{' operator is subject to a syntactic ambiguity + // in JavaScript: it can begin a block or an object literal. We wrap the text + // in parens to eliminate the ambiguity. + j = eval('(' + text + ')'); -/***/ }, -/* 7 */ -/***/ function(module, exports) { + // In the optional fourth stage, we recursively walk the new structure, passing + // each name/value pair to a reviver function for possible transformation. - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var 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) - } + return typeof reviver === 'function' ? + walk({'': j}, '') : j; + } - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var 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 the text is not JSON parseable, then a SyntaxError is thrown. - 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 - } - } + throw new SyntaxError('JSON.parse'); + }; - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + return JSON; + })(); - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + if ('undefined' != typeof window) { + window.expect = module.exports; + } - buffer[offset + i - d] |= s * 128 - } + })( + this + , true ? module : {exports: {}} + ); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)(module))) /***/ }, -/* 8 */ +/* 4 */ /***/ function(module, exports) { - - /** - * isArray - */ - - var isArray = Array.isArray; - - /** - * toString - */ - - var str = Object.prototype.toString; - - /** - * Whether or not the given `val` - * is an array. - * - * example: - * - * isArray([]); - * // > true - * isArray(arguments); - * // > false - * isArray(''); - * // > false - * - * @param {mixed} val - * @return {bool} - */ - - module.exports = isArray || function (val) { - return !! val && '[object Array]' == str.call(val); - }; + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } /***/ }, -/* 9 */ +/* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, setImmediate, process) {(function() { @@ -6815,10 +5000,10 @@ Faye.Transport.register('callback-polling', Faye.Transport.JSONP); })(); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(10).setImmediate, __webpack_require__(2))) + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(6).setImmediate, __webpack_require__(2))) /***/ }, -/* 10 */ +/* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(2).nextTick; @@ -6897,10 +5082,10 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10).setImmediate, __webpack_require__(10).clearImmediate)) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6).setImmediate, __webpack_require__(6).clearImmediate)) /***/ }, -/* 11 */ +/* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** @@ -6908,9 +5093,11 @@ * @author Thierry Schellenbach * BSD License */ - var StreamClient = __webpack_require__(12); - var errors = __webpack_require__(15); - var request = __webpack_require__(13); + 'use strict'; + + var StreamClient = __webpack_require__(8); + var errors = __webpack_require__(11); + var request = __webpack_require__(9); function connect(apiKey, apiSecret, appId, options) { /** @@ -6931,7 +5118,7 @@ * @example where streamURL looks like * "https://thierry:pass@gestream.io/?app=1" */ - if (typeof (process) !== 'undefined' && process.env.STREAM_URL && !apiKey) { + if (typeof process !== 'undefined' && process.env.STREAM_URL && !apiKey) { var parts = /https\:\/\/(\w+)\:(\w+)\@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL); apiKey = parts[1]; apiSecret = parts[2]; @@ -6953,21 +5140,22 @@ module.exports.errors = errors; module.exports.request = request; module.exports.Client = StreamClient; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }, -/* 12 */ +/* 8 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(process) {var request = __webpack_require__(13); - var StreamFeed = __webpack_require__(14); - var signing = __webpack_require__(17); - var errors = __webpack_require__(15); - var utils = __webpack_require__(16); - var BatchOperations = __webpack_require__(21); - var Promise = __webpack_require__(22); - var qs = __webpack_require__(23); + /* WEBPACK VAR INJECTION */(function(process) {'use strict'; + + var request = __webpack_require__(9); + var StreamFeed = __webpack_require__(10); + var signing = __webpack_require__(13); + var errors = __webpack_require__(11); + var utils = __webpack_require__(12); + var BatchOperations = __webpack_require__(15); + var Promise = __webpack_require__(17); + var qs = __webpack_require__(15); /** * @callback requestCallback @@ -6976,7 +5164,7 @@ * @param {object} body */ - var StreamClient = function() { + var StreamClient = function StreamClient() { /** * Client to connect to Stream api * @class StreamClient @@ -6988,7 +5176,7 @@ baseUrl: 'https://api.getstream.io/api/', baseAnalyticsUrl: 'https://analytics.getstream.io/analytics/', - initialize: function(apiKey, apiSecret, appId, options) { + initialize: function initialize(apiKey, apiSecret, appId, options) { /** * Initialize a client * @method intialize @@ -7022,16 +5210,16 @@ this.baseUrl = 'https://' + this.location + '-api.getstream.io/api/'; } - if (typeof (process) !== 'undefined' && process.env.LOCAL) { + if (typeof process !== 'undefined' && process.env.LOCAL) { this.baseUrl = 'http://localhost:8000/api/'; } - if (typeof (process) !== 'undefined' && process.env.LOCAL_FAYE) { + if (typeof process !== 'undefined' && process.env.LOCAL_FAYE) { this.fayeUrl = 'http://localhost:9999/faye/'; } this.handlers = {}; - this.browser = typeof (window) !== 'undefined'; + this.browser = typeof window !== 'undefined'; this.node = !this.browser; if (this.browser && this.apiSecret) { @@ -7039,7 +5227,7 @@ } }, - on: function(event, callback) { + on: function on(event, callback) { /** * Support for global event callbacks * This is useful for generic error and loading handling @@ -7054,7 +5242,7 @@ this.handlers[event] = callback; }, - off: function(key) { + off: function off(key) { /** * Remove one or more event handlers * @method off @@ -7071,7 +5259,7 @@ } }, - send: function() { + send: function send() { /** * Call the given handler with the arguments * @method send @@ -7086,7 +5274,7 @@ } }, - wrapPromiseTask: function(cb, fulfill, reject) { + wrapPromiseTask: function wrapPromiseTask(cb, fulfill, reject) { /** * Wrap a task to be used as a promise * @method wrapPromiseTask @@ -7104,12 +5292,12 @@ if (error) { reject({ error: error, - response: response, + response: response }); } else if (!/^2/.test('' + response.statusCode)) { reject({ error: body, - response: response, + response: response }); } else { fulfill(body); @@ -7119,7 +5307,7 @@ }; }, - wrapCallback: function(cb) { + wrapCallback: function wrapCallback(cb) { /** * Wrap callback for HTTP request * @method wrapCallBack @@ -7141,20 +5329,22 @@ return callback; }, - userAgent: function() { + userAgent: function userAgent() { /** * Get the current user agent * @method userAgent * @memberof StreamClient.prototype * @return {string} current user agent */ - var description = (this.node) ? 'node' : 'browser'; + var description = this.node ? 'node' : 'browser'; // TODO: get the version here in a way which works in both and browserify - var version = 'unknown'; + + var version = __webpack_require__(18).version; + return 'stream-javascript-client-' + description + '-' + version; }, - getReadOnlyToken: function(feedSlug, userId) { + getReadOnlyToken: function getReadOnlyToken(feedSlug, userId) { /** * Returns a token that allows only read operations * @@ -7170,7 +5360,7 @@ return signing.JWTScopeToken(this.apiSecret, '*', 'read', { feedId: feedId, expireTokens: this.expireTokens }); }, - getReadWriteToken: function(feedSlug, userId) { + getReadWriteToken: function getReadWriteToken(feedSlug, userId) { /** * Returns a token that allows read and write operations * @@ -7186,7 +5376,7 @@ return signing.JWTScopeToken(this.apiSecret, '*', '*', { feedId: feedId, expireTokens: this.expireTokens }); }, - feed: function(feedSlug, userId, token, siteId, options) { + feed: function feed(feedSlug, userId, token, siteId, options) { /** * Returns a feed object for the given feed id and token * @method feed @@ -7231,7 +5421,7 @@ return feed; }, - enrichUrl: function(relativeUrl) { + enrichUrl: function enrichUrl(relativeUrl) { /** * Combines the base url with version and the relative url * @method enrichUrl @@ -7243,7 +5433,7 @@ return url; }, - enrichKwargs: function(kwargs) { + enrichKwargs: function enrichKwargs(kwargs) { /** * Adds the API key and the signature * @method enrichKwargs @@ -7263,7 +5453,7 @@ kwargs.headers = {}; // auto-detect authentication type and set HTTP headers accordingly - if (signing.isJWTSignature(signature)) { + if (signature && signing.isJWTSignature(signature)) { kwargs.headers['stream-auth-type'] = 'jwt'; signature = signature.split(' ').reverse()[0]; } else { @@ -7275,7 +5465,7 @@ return kwargs; }, - signActivity: function(activity) { + signActivity: function signActivity(activity) { /** * We automatically sign the to parameter when in server side mode * @method signActivities @@ -7286,7 +5476,7 @@ return this.signActivities([activity])[0]; }, - signActivities: function(activities) { + signActivities: function signActivities(activities) { /** * We automatically sign the to parameter when in server side mode * @method signActivities @@ -7317,7 +5507,7 @@ return activities; }, - getFayeAuthorization: function() { + getFayeAuthorization: function getFayeAuthorization() { /** * Get the authorization middleware to use Faye with getstream.io * @method getFayeAuthorization @@ -7329,27 +5519,27 @@ self = this; return { - incoming: function(message, callback) { + incoming: function incoming(message, callback) { callback(message); }, - outgoing: function(message, callback) { + outgoing: function outgoing(message, callback) { if (message.subscription && self.subscriptions[message.subscription]) { var subscription = self.subscriptions[message.subscription]; message.ext = { 'user_id': subscription.userId, 'api_key': apiKey, - 'signature': subscription.token, + 'signature': subscription.token }; } callback(message); - }, + } }; }, - getFayeClient: function() { + getFayeClient: function getFayeClient() { /** * Returns this client's current Faye client * @method getFayeClient @@ -7357,7 +5547,7 @@ * @private * @return {object} Faye client */ - var Faye = __webpack_require__(9); + var Faye = __webpack_require__(5); if (this.fayeClient === null) { this.fayeClient = new Faye.Client(this.fayeUrl); var authExtension = this.getFayeAuthorization(); @@ -7367,7 +5557,7 @@ return this.fayeClient; }, - get: function(kwargs, cb) { + get: function get(kwargs, cb) { /** * Shorthand function for get request * @method get @@ -7377,16 +5567,16 @@ * @param {requestCallback} cb Callback to call on completion * @return {Promise} Promise object */ - return new Promise(function(fulfill, reject) { + return new Promise((function (fulfill, reject) { this.send('request', 'get', kwargs, cb); kwargs = this.enrichKwargs(kwargs); kwargs.method = 'GET'; var callback = this.wrapPromiseTask(cb, fulfill, reject); request(kwargs, callback); - }.bind(this)); + }).bind(this)); }, - post: function(kwargs, cb) { + post: function post(kwargs, cb) { /** * Shorthand function for post request * @method post @@ -7396,16 +5586,16 @@ * @param {requestCallback} cb Callback to call on completion * @return {Promise} Promise object */ - return new Promise(function(fulfill, reject) { + return new Promise((function (fulfill, reject) { this.send('request', 'post', kwargs, cb); kwargs = this.enrichKwargs(kwargs); kwargs.method = 'POST'; var callback = this.wrapPromiseTask(cb, fulfill, reject); request(kwargs, callback); - }.bind(this)); + }).bind(this)); }, - delete: function(kwargs, cb) { + 'delete': function _delete(kwargs, cb) { /** * Shorthand function for delete request * @method delete @@ -7415,19 +5605,19 @@ * @param {requestCallback} cb Callback to call on completion * @return {Promise} Promise object */ - return new Promise(function(fulfill, reject) { + return new Promise((function (fulfill, reject) { this.send('request', 'delete', kwargs, cb); kwargs = this.enrichKwargs(kwargs); kwargs.method = 'DELETE'; var callback = this.wrapPromiseTask(cb, fulfill, reject); request(kwargs, callback); - }.bind(this)); - }, + }).bind(this)); + } }; if (qs) { - StreamClient.prototype.createRedirectUrl = function(targetUrl, userId, events) { + StreamClient.prototype.createRedirectUrl = function (targetUrl, userId, events) { /** * Creates a redirect url for tracking the given events in the context of * an email using Stream's analytics platform. Learn more at @@ -7439,10 +5629,10 @@ * @param {array} events List of events to track * @return {string} The redirect url */ - var url = __webpack_require__(24); + var url = __webpack_require__(19); var uri = url.parse(targetUrl); - if (!(uri.host || (uri.hostname && uri.port)) && !uri.isUnix) { + if (!(uri.host || uri.hostname && uri.port) && !uri.isUnix) { throw new errors.MissingSchemaError('Invalid URI: "' + url.format(uri) + '"'); } @@ -7453,7 +5643,7 @@ 'authorization': authToken, 'url': targetUrl, 'api_key': this.apiKey, - 'events': JSON.stringify(events), + 'events': JSON.stringify(events) }; var qString = utils.rfc3986(qs.stringify(kwargs, null, null, {})); @@ -7472,11 +5662,10 @@ } module.exports = StreamClient; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }, -/* 13 */ +/* 9 */ /***/ function(module, exports) { // Browser Request @@ -7958,13 +6147,15 @@ /***/ }, -/* 14 */ +/* 10 */ /***/ function(module, exports, __webpack_require__) { - var errors = __webpack_require__(15); - var utils = __webpack_require__(16); + 'use strict'; + + var errors = __webpack_require__(11); + var utils = __webpack_require__(12); - var StreamFeed = function() { + var StreamFeed = function StreamFeed() { /** * Manage api calls for specific feeds * The feed object contains convenience functions such add activity, remove activity etc @@ -7974,7 +6165,7 @@ }; StreamFeed.prototype = { - initialize: function(client, feedSlug, userId, token) { + initialize: function initialize(client, feedSlug, userId, token) { /** * Initialize a feed object * @method intialize @@ -7998,7 +6189,7 @@ this.notificationChannel = 'site-' + this.client.appId + '-feed-' + this.feedTogether; }, - addActivity: function(activity, callback) { + addActivity: function addActivity(activity, callback) { /** * Adds the given activity to the feed and * calls the specified callback @@ -8013,11 +6204,11 @@ return this.client.post({ url: 'feed/' + this.feedUrl + '/', body: activity, - signature: this.signature, + signature: this.signature }, callback); }, - removeActivity: function(activityId, callback) { + removeActivity: function removeActivity(activityId, callback) { /** * Removes the activity by activityId * @method removeActivity @@ -8030,20 +6221,20 @@ * @example * feed.removeActivity({'foreign_id': foreignId}); */ - var identifier = (activityId.foreignId) ? activityId.foreignId : activityId; + var identifier = activityId.foreignId ? activityId.foreignId : activityId; var params = {}; if (activityId.foreignId) { params['foreign_id'] = '1'; } - return this.client.delete({ + return this.client['delete']({ url: 'feed/' + this.feedUrl + '/' + identifier + '/', qs: params, - signature: this.signature, + signature: this.signature }, callback); }, - addActivities: function(activities, callback) { + addActivities: function addActivities(activities, callback) { /** * Adds the given activities to the feed and calls the specified callback * @method addActivities @@ -8054,17 +6245,17 @@ */ activities = this.client.signActivities(activities); var data = { - activities: activities, + activities: activities }; var xhr = this.client.post({ url: 'feed/' + this.feedUrl + '/', body: data, - signature: this.signature, + signature: this.signature }, callback); return xhr; }, - follow: function(targetSlug, targetUserId, options, callback) { + follow: function follow(targetSlug, targetUserId, options, callback) { /** * Follows the given target feed * @method follow @@ -8085,7 +6276,7 @@ var activityCopyLimit; var last = arguments[arguments.length - 1]; // callback is always the last argument - callback = (last.call) ? last : undefined; + callback = last.call ? last : undefined; var target = targetSlug + ':' + targetUserId; // check for additional options @@ -8096,7 +6287,7 @@ } var body = { - target: target, + target: target }; if (activityCopyLimit) { @@ -8106,11 +6297,11 @@ return this.client.post({ url: 'feed/' + this.feedUrl + '/following/', body: body, - signature: this.signature, + signature: this.signature }, callback); }, - unfollow: function(targetSlug, targetUserId, callback) { + unfollow: function unfollow(targetSlug, targetUserId, callback) { /** * Unfollow the given feed * @method unfollow @@ -8124,14 +6315,14 @@ utils.validateFeedSlug(targetSlug); utils.validateUserId(targetUserId); var targetFeedId = targetSlug + ':' + targetUserId; - var xhr = this.client.delete({ + var xhr = this.client['delete']({ url: 'feed/' + this.feedUrl + '/following/' + targetFeedId + '/', - signature: this.signature, + signature: this.signature }, callback); return xhr; }, - following: function(options, callback) { + following: function following(options, callback) { /** * List which feeds this feed is following * @method following @@ -8149,11 +6340,11 @@ return this.client.get({ url: 'feed/' + this.feedUrl + '/following/', qs: options, - signature: this.signature, + signature: this.signature }, callback); }, - followers: function(options, callback) { + followers: function followers(options, callback) { /** * List the followers of this feed * @method followers @@ -8172,11 +6363,11 @@ return this.client.get({ url: 'feed/' + this.feedUrl + '/followers/', qs: options, - signature: this.signature, + signature: this.signature }, callback); }, - get: function(options, callback) { + get: function get(options, callback) { /** * Reads the feed * @method get @@ -8198,11 +6389,11 @@ return this.client.get({ url: 'feed/' + this.feedUrl + '/', qs: options, - signature: this.signature, + signature: this.signature }, callback); }, - getFayeClient: function() { + getFayeClient: function getFayeClient() { /** * Returns the current faye client object * @method getFayeClient @@ -8213,7 +6404,7 @@ return this.client.getFayeClient(); }, - subscribe: function(callback) { + subscribe: function subscribe(callback) { /** * Subscribes to any changes in the feed, return a promise * @method subscribe @@ -8231,24 +6422,25 @@ this.client.subscriptions['/' + this.notificationChannel] = { token: this.token, - userId: this.notificationChannel, + userId: this.notificationChannel }; return this.getFayeClient().subscribe('/' + this.notificationChannel, callback); - }, + } }; module.exports = StreamFeed; - /***/ }, -/* 15 */ +/* 11 */ /***/ function(module, exports) { + 'use strict'; + var errors = module.exports; - var canCapture = (typeof Error.captureStackTrace === 'function'); - var canStack = !!(new Error()).stack; + var canCapture = typeof Error.captureStackTrace === 'function'; + var canStack = !!new Error().stack; /** * Abstract error object @@ -8265,7 +6457,7 @@ if (canCapture) { Error.captureStackTrace(this, constructor); } else if (canStack) { - this.stack = (new Error()).stack; + this.stack = new Error().stack; } else { this.stack = ''; } @@ -8316,12 +6508,13 @@ errors.MissingSchemaError.prototype = new ErrorAbstract(); - /***/ }, -/* 16 */ +/* 12 */ /***/ function(module, exports, __webpack_require__) { - var errors = __webpack_require__(15); + 'use strict'; + + var errors = __webpack_require__(11); var validRe = /^[\w-]+$/; function validateFeedId(feedId) { @@ -8371,22 +6564,23 @@ exports.validateUserId = validateUserId; function rfc3986(str) { - return str.replace(/[!'()*]/g, function(c) { + return str.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); } exports.rfc3986 = rfc3986; - /***/ }, -/* 17 */ +/* 13 */ /***/ function(module, exports, __webpack_require__) { - var crypto = __webpack_require__(18); - var jwt = __webpack_require__(19); + 'use strict'; + + var crypto = __webpack_require__(14); + var jwt = __webpack_require__(15); var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - var Base64 = __webpack_require__(20); + var Base64 = __webpack_require__(16); function makeUrlSafe(s) { /* @@ -8409,7 +6603,7 @@ } function safeJsonParse(thing) { - if (typeof (thing) === 'object') return thing; + if (typeof thing === 'object') return thing; try { return JSON.parse(thing); } catch (e) { @@ -8420,19 +6614,15 @@ function padString(string) { var segmentLength = 4; var diff = string.length % segmentLength; - if (!diff) - return string; + if (!diff) return string; var padLength = segmentLength - diff; - while (padLength--) - string += '='; + while (padLength--) string += '='; return string; } function toBase64(base64UrlString) { - var b64str = padString(base64UrlString) - .replace(/\-/g, '+') - .replace(/_/g, '/'); + var b64str = padString(base64UrlString).replace(/\-/g, '+').replace(/_/g, '/'); return b64str; } @@ -8443,7 +6633,7 @@ exports.headerFromJWS = headerFromJWS; - exports.sign = function(apiSecret, feedId) { + exports.sign = function (apiSecret, feedId) { /* * Setup sha1 based on the secret * Get the digest of the value @@ -8466,7 +6656,7 @@ return token; }; - exports.JWTScopeToken = function(apiSecret, resource, action, opts) { + exports.JWTScopeToken = function (apiSecret, resource, action, opts) { /** * Creates the JWT token for feedId, resource and action using the apiSecret * @method JWTScopeToken @@ -8484,7 +6674,7 @@ noTimestamp = options.expireTokens ? !options.expireTokens : true; var payload = { resource: resource, - action: action, + action: action }; if (options.feedId) { @@ -8495,11 +6685,11 @@ payload['user_id'] = options.userId; } - var token = jwt.sign(payload, apiSecret, {algorithm: 'HS256', noTimestamp: noTimestamp}); + var token = jwt.sign(payload, apiSecret, { algorithm: 'HS256', noTimestamp: noTimestamp }); return token; }; - exports.isJWTSignature = function(signature) { + exports.isJWTSignature = function (signature) { /** * check if token is a valid JWT token * @method isJWTSignature @@ -8512,21 +6702,20 @@ return JWS_REGEX.test(token) && !!headerFromJWS(token); }; - /***/ }, -/* 18 */ +/* 14 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 19 */ +/* 15 */ /***/ function(module, exports) { - /* (ignored) */ + "use strict"; /***/ }, -/* 20 */ +/* 16 */ /***/ function(module, exports, __webpack_require__) { ;(function () { @@ -8593,51 +6782,124 @@ /***/ }, -/* 21 */ -/***/ function(module, exports) { - - /* (ignored) */ - -/***/ }, -/* 22 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { - var Promise = __webpack_require__(9).Promise; + 'use strict'; + + var Promise = __webpack_require__(5).Promise; - Promise.prototype.catch = function(onRejected) { + Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; module.exports = Promise; - /***/ }, -/* 23 */ +/* 18 */ /***/ function(module, exports) { - /* (ignored) */ + module.exports = { + "author": { + "name": "Thierry Schellenbach", + "company": "Stream.io Inc" + }, + "name": "getstream", + "description": "The official low-level GetStream.io client for Node.js and the browser.", + "main": "./src/getstream.js", + "homepage": "https://getstream.io/", + "version": "3.0.0", + "browser": { + "request": "browser-request", + "crypto": false, + "jsonwebtoken": false, + "./src/lib/batch_operations.js": false, + "qs": false, + "url": false + }, + "config": { + "blanket": { + "pattern": "src", + "data-cover-never": [ + "node_modules" + ] + } + }, + "devDependencies": { + "async": "~0.9.0", + "babel-core": "^5.8.25", + "babel-loader": "^5.3.2", + "blanket": "~1.1.6", + "bluebird": "^2.1.3", + "connect": "^3.0.1", + "coveralls": "~2.10.1", + "expect.js": "~0.3.1", + "gulp": "^3.8.7", + "gulp-browserify": "^0.5.0", + "gulp-bump": "^0.1.8", + "gulp-git": "git://github.com/stevelacy/gulp-git.git", + "gulp-jscs": "^3.0.1", + "gulp-jscs-stylish": "^1.2.1", + "gulp-jshint": "^1.6.3", + "gulp-mocha": "^0.4.1", + "gulp-shell": "^0.2.7", + "gulp-uglify": "~0.3.1", + "gulp-util": "^2.2.17", + "jshint-stylish": "^2.0.1", + "json-loader": "^0.5.4", + "mocha": "^1.20.1", + "mocha-lcov-reporter": "0.0.1", + "mocha-sauce": "git://github.com/pbakaus/mocha-sauce.git", + "quickcheck": "0.0.4", + "serve-static": "^1.2.3", + "vinyl-source-stream": "^1.1.0", + "webpack": "^1.12.2" + }, + "license": "BSD", + "dependencies": { + "Base64": "^0.3.0", + "browser-request": "matthisk/browser-request", + "faye": "^1.0.1", + "http-signature": "^1.0.2", + "jsonwebtoken": "^5.0.1", + "qs": "^5.2.0", + "request": "2.63.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/GetStream/stream-js.git" + }, + "scripts": { + "test": "gulp test" + }, + "engines": { + "node": ">=0.8 <0.11" + } + }; /***/ }, -/* 24 */ +/* 19 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 25 */ +/* 20 */ /***/ function(module, exports, __webpack_require__) { + 'use strict'; + var expect = __webpack_require__(3); - var jwt = __webpack_require__(26); - var url = __webpack_require__(27); - var qs = __webpack_require__(28); - var qc = __webpack_require__(29); - var utils = __webpack_require__(16); - var errors = __webpack_require__(15); + var jwt = __webpack_require__(15); + var url = __webpack_require__(21); + var qs = __webpack_require__(15); + var qc = __webpack_require__(22); + var utils = __webpack_require__(12); + var errors = __webpack_require__(11); var isNodeEnv = typeof window === 'undefined'; - var stream = __webpack_require__(11); + var stream = __webpack_require__(7); - var signing = signing || __webpack_require__(17); + var signing = signing || __webpack_require__(13); console.log('node is set to', isNodeEnv); @@ -8651,78 +6913,106 @@ var result = {}; - while(width--) { + while (width--) { var value = qc.arbString(), maxDepth = Math.floor(Math.random() * (3 - 1) + 1); - if(depth) { - value = arbJSON(depth-1); - } else if(depth === undefined) { + if (depth) { + value = arbJSON(depth - 1); + } else if (depth === undefined) { value = arbJSON(maxDepth); } - result[ qc.arbString() ] = value; + result[qc.arbString()] = value; } return result; } function arbNonEmptyString() { - var str = qc.arbString(); + var _again = true; - return str === '' ? arbNonEmptyString() : str; + _function: while (_again) { + str = undefined; + _again = false; + + var str = qc.arbString(); + + if (str === '') { + _again = true; + continue _function; + } else { + return str; + } + } } function arbJWT() { - return jwt.sign( arbJSON(), arbNonEmptyString(), arbJSON() ); + return jwt.sign(arbJSON(), arbNonEmptyString(), arbJSON()); } - describe('Json web token validation', function() { + describe('Json web token validation', function () { var validSignature = "feedname eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG5Eb2UiLCJhY3Rpb24iOiJyZWFkIn0.dfayorXXS1rAyd97BGCNgrCodPH9X3P80DPMH5b9D_A"; var invalidSignature = "feedname eyJhbGiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZS.dfayorXXS1rAyd97BGCNgrCodH38PH5b9D_A"; - it('should validate valid jwts', function() { - expect( signing.isJWTSignature(validSignature) ).to.be(true); + it('should validate valid jwts', function () { + expect(signing.isJWTSignature(validSignature)).to.be(true); }); - it('should validate unvalid jwts', function() { - expect( signing.isJWTSignature(invalidSignature) ).to.be(false); + it('should validate unvalid jwts', function () { + expect(signing.isJWTSignature(invalidSignature)).to.be(false); }); - if(isNodeEnv) { - it('should decode valid jwts headers', function() { - expect( qc.forAll( propertyHeaderJSON, arbJWT ) ).to.be(true); + if (isNodeEnv) { + it('should decode valid jwts headers', function () { + expect(qc.forAll(propertyHeaderJSON, arbJWT)).to.be(true); }); } }); - describe('Utility functions', function() { - it('should validate feed id\'s', function() { + describe('Utility functions', function () { + it('should validate feed id\'s', function () { expect(utils.validateFeedId('flat:0')).to.be.ok(); }); - it('should throw exception while validating faulty feed id',function() { - expect(function() { - utils.validateFeedId('b134u92fval') - }).to.throwError(function(e) { + it('should throw exception while validating faulty feed id', function () { + expect(function () { + utils.validateFeedId('b134u92fval'); + }).to.throwError(function (e) { expect(e).to.be.a(errors.FeedError); }); }); }); + describe('Stream client', function () { + var client = stream.connect('ahj2ndz7gsan'); + var userAgentString = 'stream-javascript-client-' + (isNodeEnv ? 'node' : 'browser') + '-' + __webpack_require__(18).version; + + it('#userAgent()', function () { + expect(client.userAgent).to.be.a(Function); + + var userAgent = client.userAgent(); + + expect(userAgent).to.be(userAgentString); + }); + + it('#enrichKwargs() useragent', function () { + expect(client.enrichKwargs).to.be.a(Function); + + var kwargs = client.enrichKwargs({}); + + expect(kwargs.headers['X-Stream-Client']).to.be(userAgentString); + }); + }); + if (isNodeEnv) { - describe('Stream Client', function() { + describe('Stream Client', function () { var client = stream.connect('ahj2ndz7gsan', 'gthc2t9gh7pzq52f6cky8w4r4up9dr6rju9w3fjgmkv6cdvvav2ufe5fv7e2r9qy'); - it('should create email redirects', function() { - var expectedParts = ['https://analytics.getstream.io/analytics/redirect/', - 'auth_type=jwt', - 'url=http%3A%2F%2Fgoogle.com%2F%3Fa%3Db%26c%3Dd', - 'events=%5B%7B%22foreign_ids%22%3A%5B%22tweet%3A1%22%2C%22tweet%3A2%22%2C%22tweet%3A3%22%2C%22tweet%3A4%22%2C%22tweet%3A5%22%5D%2C%22user_id%22%3A%22tommaso%22%2C%22location%22%3A%22email%22%2C%22feed_id%22%3A%22user%3Aglobal%22%7D%2C%7B%22foreign_id%22%3A%22tweet%3A1%22%2C%22label%22%3A%22click%22%2C%22position%22%3A3%2C%22user_id%22%3A%22tommaso%22%2C%22location%22%3A%22email%22%2C%22feed_id%22%3A%22user%3Aglobal%22%7D%5D', - 'api_key=ahj2ndz7gsan', - ]; + it('should create email redirects', function () { + var expectedParts = ['https://analytics.getstream.io/analytics/redirect/', 'auth_type=jwt', 'url=http%3A%2F%2Fgoogle.com%2F%3Fa%3Db%26c%3Dd', 'events=%5B%7B%22foreign_ids%22%3A%5B%22tweet%3A1%22%2C%22tweet%3A2%22%2C%22tweet%3A3%22%2C%22tweet%3A4%22%2C%22tweet%3A5%22%5D%2C%22user_id%22%3A%22tommaso%22%2C%22location%22%3A%22email%22%2C%22feed_id%22%3A%22user%3Aglobal%22%7D%2C%7B%22foreign_id%22%3A%22tweet%3A1%22%2C%22label%22%3A%22click%22%2C%22position%22%3A3%2C%22user_id%22%3A%22tommaso%22%2C%22location%22%3A%22email%22%2C%22feed_id%22%3A%22user%3Aglobal%22%7D%5D', 'api_key=ahj2ndz7gsan']; var engagement = { 'foreign_id': 'tweet:1', 'label': 'click', 'position': 3, 'user_id': 'tommaso', 'location': 'email', 'feed_id': 'user:global' }, - impression = {'foreign_ids': ['tweet:1', 'tweet:2', 'tweet:3', 'tweet:4', 'tweet:5'], 'user_id': 'tommaso', 'location': 'email', 'feed_id': 'user:global'}, + impression = { 'foreign_ids': ['tweet:1', 'tweet:2', 'tweet:3', 'tweet:4', 'tweet:5'], 'user_id': 'tommaso', 'location': 'email', 'feed_id': 'user:global' }, events = [impression, engagement], userId = 'tommaso', targetUrl = 'http://google.com/?a=b&c=d'; @@ -8734,7 +7024,7 @@ expect(decoded).to.eql({ 'resource': 'redirect_and_track', 'action': '*', - 'user_id': userId, + 'user_id': userId }); for (var i = 0; i < expectedParts.length; i++) { @@ -8742,36 +7032,22 @@ } }); - it('should fail creating email redirects on invalid targets', function() { - expect(function() { + it('should fail creating email redirects on invalid targets', function () { + expect(function () { client.createRedirectUrl('google.com', 'tommaso', []); }).to.throwException(errors.MissingSchemaError); }); - }); } - -/***/ }, -/* 26 */ -/***/ function(module, exports) { - - /* (ignored) */ - -/***/ }, -/* 27 */ -/***/ function(module, exports) { - - /* (ignored) */ - /***/ }, -/* 28 */ +/* 21 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 29 */ +/* 22 */ /***/ function(module, exports) { function arbBool() { diff --git a/test/browser/runner.js b/test/browser/runner.js deleted file mode 100644 index d203f6d1..00000000 --- a/test/browser/runner.js +++ /dev/null @@ -1,46 +0,0 @@ -var MochaSauce = require("mocha-sauce"); -var connect = require('connect'); -var serveStatic = require('serve-static'); -var path = require('path'); - -// setup a webserver to run the tests against -var directory = path.normalize(path.join(__dirname, '../../')); -console.log('starting webserver in dir ', directory); -app = connect().use(serveStatic(directory)); -server = app.listen(8080); - -// configure -var sauce = new MochaSauce({ - name: "getstream", // your project name - username: "tschellenbach", // Sauce username - accessKey: "982137a0-d75d-4cd8-a6c3-1a497e97a277", // Sauce access key - host: "127.0.0.1", // or http://ondemand.sauce.com if not using Sauce Connect - port: 4445, // 80 - // the test url - url: "http://127.0.0.1:8080/test/browser/sauce.html/", // point to the site running your mocha tests - build: process.env.TRAVIS_JOB_NUMBER -}); - - -// setup what browsers to test with -sauce.browser({ browserName: "chrome", platform: "Windows 7" }); -sauce.browser({ browserName: "firefox", platform: "Windows XP" }); -sauce.browser({ browserName: "internet explorer", platform: "Windows 8.1", version: 11 }); -sauce.browser({ browserName: "internet explorer", platform: "Windows 8", version: 10 }); - -sauce.on('init', function(browser) { - console.log(' init : %s %s', browser.browserName, browser.platform); -}); - -sauce.on('start', function(browser) { - console.log(' start : %s %s', browser.browserName, browser.platform); -}); - -sauce.on('end', function(browser, res) { - console.log(' end : %s %s : %d failures', browser.browserName, browser.platform, res.failures); -}); - -sauce.start(function completed() { - console.log('done with the sauce, giving it back'); - server.close(); -}); diff --git a/test/browser/sauce.html b/test/browser/sauce.html index 7cdd8e36..0428223f 100644 --- a/test/browser/sauce.html +++ b/test/browser/sauce.html @@ -3,19 +3,23 @@ Mocha Tests - - -
- - + - - + + + + +
\ No newline at end of file diff --git a/test/integration/index.js b/test/integration/index.js index 67e89efb..a4fa996f 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -2,6 +2,7 @@ var expect = require('expect.js'); var Faye = require('faye'); var stream = require('../../src/getstream'); var isNodeEnv = typeof window === 'undefined'; +var errors; var READ_TIMEOUT = 2000; diff --git a/test/saucelabs.js b/test/saucelabs.js new file mode 100644 index 00000000..8eb126df --- /dev/null +++ b/test/saucelabs.js @@ -0,0 +1,44 @@ +var MochaSauce = require("mocha-sauce"); +var connect = require("connect"); +var serveStatic = require("serve-static"); +var path = require("path"); + +var dir = path.normalize(path.join(__dirname, "../../")); + +console.log("Starting webserver in dir", dir); + +var app = connect().use(serveStatic(dir)); +var server = app.listen(8080); + +// configure +var sauce = new MochaSauce({ + name: "stream-js", // your project name + username: process.env.SAUCE_USERNAME, // Sauce username + accessKey: process.env.SAUCE_ACCESS_KEY, // Sauce access key + host: "localhost", // or http://ondemand.sauce.com if not using Sauce Connect + port: 4445, // 80 + + // the test url + url: "http://localhost:8080/test/browser/sauce.html", // point to the site running your mocha tests + + build: process.env.TRAVIS_JOB_NUMBER || 0, +}); + +// setup what browsers to test with +sauce.browser({ browserName: "chrome", platform: "Windows 7" }); + + +sauce.on('init', function(browser) { + console.log(' init : %s %s', browser.browserName, browser.platform); +}); + +sauce.on('start', function(browser) { + console.log(' start : %s %s', browser.browserName, browser.platform); +}); + +sauce.on('end', function(browser, res) { + console.log(' end : %s %s : %d failures', browser.browserName, browser.platform, res.failures); + server.close(); +}); + +sauce.start(); diff --git a/test/unit/index.js b/test/unit/index.js index d02949d4..a48670cd 100644 --- a/test/unit/index.js +++ b/test/unit/index.js @@ -74,13 +74,36 @@ describe('Utility functions', function() { it('should throw exception while validating faulty feed id',function() { expect(function() { - utils.validateFeedId('b134u92fval') + utils.validateFeedId('b134u92fval'); }).to.throwError(function(e) { expect(e).to.be.a(errors.FeedError); }); }); }); +describe('Stream client', function() { + var client = stream.connect('ahj2ndz7gsan'); + var userAgentString = 'stream-javascript-client-' + (isNodeEnv ? 'node' : 'browser') + '-' + require('../../package.json').version; + + it('#userAgent()', function() { + expect(client.userAgent).to.be.a(Function); + + var userAgent = client.userAgent(); + + expect(userAgent) + .to + .be(userAgentString); + }); + + it('#enrichKwargs() useragent', function() { + expect(client.enrichKwargs).to.be.a(Function); + + var kwargs = client.enrichKwargs({}); + + expect(kwargs.headers['X-Stream-Client']).to.be(userAgentString); + }); +}); + if (isNodeEnv) { describe('Stream Client', function() { var client = stream.connect('ahj2ndz7gsan', 'gthc2t9gh7pzq52f6cky8w4r4up9dr6rju9w3fjgmkv6cdvvav2ufe5fv7e2r9qy'); diff --git a/webpack.config.js b/webpack.config.js index 2fdbfb2b..d5a354c5 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -30,7 +30,8 @@ module.exports = { }, module: { loaders: [ - { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"} + { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", }, + { test: /\.json$/, loader: "json-loader", }, ] }, plugins: [new webpack.NormalModuleReplacementPlugin(/(jsonwebtoken|http-signature|batch_operations|qs)/, path.join(__dirname, "src", "/missing.js"))]